5 Commits
Author SHA1 Message Date
soarqin 476c193aa2 build: exclude nested test artifacts from parent projects 2026-10-11 03:13:07 +08:00
soarqin 307bb4740d feat(uxassist): generate blueprint production descriptions
Add native blueprint description generation with proliferation controls, separate power categories, and steady-state material and research reporting.

Distinguish necessary coproducts from overbuild and fractional headroom, with regression checks and updated architecture documentation.

Validation: 464 ProductionCheck checks and Release builds of UXAssist, CheatEnabler, and UniverseGenTweaks.
2026-10-11 03:13:07 +08:00
soarqin 8696a80a66 feat(production): include logistics charging in black-box power 2026-10-11 03:13:07 +08:00
soarqin d4ba72abf4 fix(production): correct full-load capture and solver scaling
Stop capturing the transient miner output damper, apply the sandbox boost state to artificial stars as for launchers, and keep lens-free photon flows when no ray receiver is selected.

Scale the planner conservation check by each ledger row and normalize the simplex right-hand side so large rates no longer fail. Skip non-production objects before copying native settings, decode blueprints through the native paste path, and simplify analyzer mode resolution.

Update stale ProductionCheck expectations, add regression checks, and document the rules.
2026-10-11 03:13:07 +08:00
soarqin bcc82e1056 feat(production): add shared planner and factory analysis
Add Proto-backed planning, fixed-building analysis, blueprint capture, and facility-specific material and power calculations.

Migrate belt-signal upstream statistics, include review fixes, and document the architecture and manual validation workflow.
2026-10-11 03:13:07 +08:00
133 changed files with 3982 additions and 6051 deletions

No files matched your search

-10
View File
@@ -1,10 +0,0 @@
{
"version": 1,
"isRoot": true,
"tools": {
"tcli": {
"version": "0.2.4",
"commands": ["tcli"]
}
}
}
-4
View File
@@ -21,10 +21,6 @@ build/
/*/package/patchers/ /*/package/patchers/
/*/package/plugins/ /*/package/plugins/
# Local credentials
.env
.env.*
# Agent files # Agent files
/.omo/ /.omo/
/.worktrees/ /.worktrees/
+6 -3
View File
@@ -25,14 +25,17 @@
- Keep temporary verification projects under the mod's excluded root `obj/` directory. Remove abandoned generated outputs when their source project is gone so the SDK source glob cannot compile them into the mod. - Keep temporary verification projects under the mod's excluded root `obj/` directory. Remove abandoned generated outputs when their source project is gone so the SDK source glob cannot compile them into the mod.
- Refresh game references explicitly with `dotnet build UpdateGameDlls/UpdateGameDlls.csproj`; the script publicizes installed DLLs in staging and compares generated content hashes so checkout timestamps cannot hide game updates. Missing DSP or the publicizer is a warning, not a build failure. If `assembly-publicizer` requires an unavailable .NET runtime, retry with process-local `DOTNET_ROLL_FORWARD=Major` rather than changing global runtime settings. Verify discovery warnings against the actual configured library directories and original managed DLLs; absence from the VDF `apps` list alone does not establish that DSP is uninstalled. - Refresh game references explicitly with `dotnet build UpdateGameDlls/UpdateGameDlls.csproj`; the script publicizes installed DLLs in staging and compares generated content hashes so checkout timestamps cannot hide game updates. Missing DSP or the publicizer is a warning, not a build failure. If `assembly-publicizer` requires an unavailable .NET runtime, retry with process-local `DOTNET_ROLL_FORWARD=Major` rather than changing global runtime settings. Verify discovery warnings against the actual configured library directories and original managed DLLs; absence from the VDF `apps` list alone does not establish that DSP is uninstalled.
- Package main mods with `dotnet build -t:ZipMod -c Release`; package preloaders with `dotnet build -t:CopyToParentPackage -c Release`. The mod `.csproj` `<Version>` is the single version source and packaging synchronizes `package/manifest.json`. Keep the latest English and Chinese changelog headings and notes aligned with `<Version>`; preserve existing unreleased notes and historical entries. Describe relevant triggers when documenting fixes to previously released behavior. - Package main mods with `dotnet build -t:ZipMod -c Release`; package preloaders with `dotnet build -t:CopyToParentPackage -c Release`. The mod `.csproj` `<Version>` is the single version source and packaging synchronizes `package/manifest.json`. Keep the latest English and Chinese changelog headings and notes aligned with `<Version>`; preserve existing unreleased notes and historical entries. Describe relevant triggers when documenting fixes to previously released behavior.
- When delivering UXAssist changes for local use in r2modman (R2), run `ZipMod`, verify that the zip contains the current DLL, manifest, icon, README, and changelog, and report the zip's full Windows path.
- Treat warnings as errors except the intentional obsolete API warning `0618`; do not weaken this policy to hide new warnings. - Treat warnings as errors except the intentional obsolete API warning `0618`; do not weaken this policy to hide new warnings.
- Export Thunderstore package icons as 256x256 PNG files and verify their format and dimensions. For circular exports, apply an antialiased alpha mask to the approved artwork instead of regenerating it; preserve RGB pixels and make the exterior fully transparent. Convey the mod's function through familiar, conventionally oriented symbols rather than lettering. Preserve DSP motifs and consistent materials across related mod icons. During localized edits, preserve all unrequested geometry, placement and styling from the chosen reference; do not redesign surrounding structures to produce an overlap. Use clear foreground occlusion for intersecting forms without losing the main symbol's silhouette, and check contrast in 64x64 and 32x32 side-by-side previews. Keep unselected icon candidates under `artifacts/`, outside release package directories. - Export Thunderstore package icons as 256x256 PNG files and verify their format and dimensions. For circular exports, apply an antialiased alpha mask to the approved artwork instead of regenerating it; preserve RGB pixels and make the exterior fully transparent. Convey the mod's function through familiar, conventionally oriented symbols rather than lettering. Preserve DSP motifs and consistent materials across related mod icons. During localized edits, preserve all unrequested geometry, placement and styling from the chosen reference; do not redesign surrounding structures to produce an overlap. Use clear foreground occlusion for intersecting forms without losing the main symbol's silhouette, and check contrast in 64x64 and 32x32 side-by-side previews. Keep unselected icon candidates under `artifacts/`, outside release package directories.
## Architecture ## Architecture
- UXAssist production calculations (catalog, planner, fixed-building analyzer, blueprint capture, and blueprint descriptions) are described in [production architecture](UXAssist/docs/ProductionArchitecture.md). Capture immutable Proto, PrefabDesc, and Cargo snapshots on the game thread and keep the calculation core pure-managed; report unknown material and power results independently instead of as zero. Verify special-building rules against the original DLL and update `UXAssist/tools/ProductionCheck` expectations with any rule change. Synthetic recipe IDs are calculation-only and must never reach native recipe lookups or setters. - Fixed-building UXAssist power reports include each selected logistics station, distributor, or battle base at its captured configured charging maximum in watts, not its transient draw. Keep factory and logistics consumption independently usable when the other category is unknown; retain the original total-power API and never display an incomplete category as zero. Keep charging power separate from accumulator exchange and do not double-count advanced miners or gas collectors. Blueprint and prebuild capture use native stored settings or prefab defaults when no charging setting is applied.
- CheatEnabler belt-signal upstream statistics use cached `ProductionPlanner` reports; never run the solver in the logic tick, and missing production data must not interrupt item generation. - UXAssist production calculations must use immutable snapshots captured from loaded Proto, PrefabDesc, and Cargo data on the game thread. Keep the planner and fixed-building analyzer pure-managed, express material rates in double items per minute and power in watts, and report unknown material and power results independently with structured diagnostics. Convert native ticks, fixed-point speeds, and per-second rates explicitly. Use native facility-specific production and power rules; keep generation, accumulator charging and discharging, and Dyson-sphere demand separate. Require explicit resource and operating settings when they cannot be captured, and never capture transient runtime throttles such as the miner output damper. Treat a stored sandbox boost mode as applied only through an explicit or live-captured `BoostEnabled` state. Verify native rules against the original DLL, compile affected mods, and keep the synthetic `UXAssist/tools/ProductionCheck` checks passing; leave in-game validation to a person rather than automated gameplay or save parsing. See [production architecture](UXAssist/docs/ProductionArchitecture.md).
- Production catalog synthetic recipe IDs are calculation-only negative output item IDs; never pass them to native recipe lookups or setters. Rebuild the catalog on game begin after preload mutations, and invalidate derived caches on `ProductionCatalogService.Changed`, including catalog clearing. Preserve accumulator coating through exchange and bound spray reuse by same-item output and demand. Live-selection operating overrides use signed object IDs; blueprint overrides use blueprint indices. Keep renewable generation at ideal rated conditions and do not count gas collectors' self-fueling as grid consumption.
- Black-box material classification must use process net flows while retaining gross production and consumption. Attribute redundant whole-building output using one stable shared material budget that preserves final-product capacity and does not worsen internal shortages; derive coproduct surplus from retained whole buildings required by other products, crediting internal net consumption first. Do not relabel limiting-product or single-product headroom as a coproduct or change the original full-load report. Derive separate steady-state external inputs by throttling surplus upstream processes together with all their outputs and inputs, including fractional and multi-stage headroom; preserve independently known rated final outputs and do not worsen shortages. For incomplete materials, still cap independently known upstream inputs against known demand, but protect potential consumers of unresolved processes rather than treating their demand as zero. A blueprint research-mode lab protects all native matrices manufactured in the selection from upstream reduction; classify their positive net production after other buildings' known consumption as final research products without falsely reporting excess or adding fictitious gross consumption. Leave other uncertain overbuild, coproduct, and final-product conclusions unknown.
- Blueprint auto-description reads only the current blueprint's buildings on button click. Keep the proliferation checkbox to the right of the button on one compact row above all description boxes. Shift the first native inspector group down once and the following groups after every refresh, restoring the original layout on disable. Replace the main description with nonempty Missing, Excess, Input, Output, and Research lines; group each warning category under one prefix, omit the per-minute suffix without changing rate units, and use only an optional power custom field with absent consumption categories omitted. Format material inputs from the separate steady-state estimate without altering full-load ledgers or power. Budget every research-mode lab at full prefab working power for conservative blueprint power capacity, even if current research is idle or technology is missing or invalid; apply a supported proliferation multiplier. Blueprint research treats one lab as an outlet for all six native matrix types actually manufactured within the selected buildings; capture their IDs independently of technology requirements and do not infer matrix demand, research speed, hashes, or external inputs from the current save. Display positive net matrix output only on Research, not ordinary Output; keep precise technology-dependent research requirements for callers without this blueprint assumption. Treat research power as independently complete when no other power category is unknown. Synchronize pending native field edits; update or remove exact bilingual power fields without changing any other custom fields, including fields titled Input or Output. Check the native description and field limits before writing, use native field escaping and item tags, and refresh the inspector without automatic saving or changes to native rendering or validation. Keep Spray Coater defaults and manual proliferation overrides scoped to the editing session; keep text formatting and field updates pure-managed under `ProductionCheck`. See [production architecture](UXAssist/docs/ProductionArchitecture.md).
- CheatEnabler belt-signal upstream statistics use the shared production planner's independent production and consumption ledgers. Cache per-item material results by catalog and spray settings, keep separate per-belt fractional accumulators, and never run the solver in the logic tick. Missing data must not interrupt item generation.
- UXAssist Dark Fog buy-out belt signals keep each item ID, per-Metaverse rate, localization key, and embedded icon path in one definition. Name embedded icon files after the current English item names and synchronize resource includes and loader paths when renaming them. Preserve the legacy signal and saved-stock order. Rates represent equivalent single-material value: a native bundle of 10 Silicon-based Neurons, 10 Negentropy Singularities, and 10 Matter Recombinators per Metaverse corresponds to 30 of any one selected material per Metaverse. - UXAssist Dark Fog buy-out belt signals keep each item ID, per-Metaverse rate, localization key, and embedded icon path in one definition. Name embedded icon files after the current English item names and synchronize resource includes and loader paths when renaming them. Preserve the legacy signal and saved-stock order. Rates represent equivalent single-material value: a native bundle of 10 Silicon-based Neurons, 10 Negentropy Singularities, and 10 Matter Recombinators per Metaverse corresponds to 30 of any one selected material per Metaverse.
- Tech downgrades must validate the full dependency cascade and capacity reductions before changing game state. Recompute non-invertible bonuses from native defaults and surviving levels; replaying unrelated unlock side effects can corrupt inventory geometry and station limits. - Tech downgrades must validate the full dependency cascade and capacity reductions before changing game state. Recompute non-invertible bonuses from native defaults and surviving levels; replaying unrelated unlock side effects can corrupt inventory geometry and station limits.
- Custom critical-warning text must participate in both `WarningSystem.hasCriticalWarning` and `WarningSystem.UpdateCriticalWarningText`; preserve native warnings and use one shared display priority. - Custom critical-warning text must participate in both `WarningSystem.hasCriticalWarning` and `WarningSystem.UpdateCriticalWarningText`; preserve native warnings and use one shared display priority.
Binary file not shown.
-16
View File
@@ -3,15 +3,7 @@
## Changlog ## Changlog
* 2.4.8
* Require UXAssist 1.6.3 or later for the shared production API. Older versions are rejected before initialization instead of failing while loading belt-signal features.
* `Mecha and Drones/Fleets invincible`: Fix mecha HP and energy shield protection failing when enabled after taking damage, and restore protection for space fleets.
* `Finish build immediately`: Fix possible errors when starting a new game. Construction begins after the opening cutscene ends or is skipped.
* `Belt signal item generation`:
* Improve raw-material, intermediate, by-product and proliferator statistics using current recipes, with production and consumption counted separately. Incomplete recipe data only pauses the affected upstream statistics; item generation continues.
* Fix signal belts built or destroyed on other planets, such as by Battlefield Analysis Base drones or Dark Fog attacks, affecting belts on the current planet. Destroyed signal belts no longer cause replacement belts to keep generating items.
* 2.4.7 * 2.4.7
* `Dev Shortcuts`: Work immediately when enabled after loading a save, and process each key press once per frame at accelerated game speeds.
* Extend `Unlock Tech with Key-Modifiers` with a downgrade mode. * Extend `Unlock Tech with Key-Modifiers` with a downgrade mode.
* Press `Caps Lock` to toggle downgrade mode. Modifier clicks lower tech levels and revert their bonuses and dependent tech levels; `Alt` returns the tech to locked. * Press `Caps Lock` to toggle downgrade mode. Modifier clicks lower tech levels and revert their bonuses and dependent tech levels; `Alt` returns the tech to locked.
* The current mode is shown by a popup and warning banner. A help button in the tech tree explains the key combinations. * The current mode is shown by a popup and warning banner. A help button in the tech tree explains the key combinations.
@@ -208,15 +200,7 @@
## 更新日志 ## 更新日志
* 2.4.8
* 需要 UXAssist 1.6.3 或更高版本提供共享生产计算 API。旧版本会在初始化前被拒绝加载,避免加载传送带信号功能时出错。
* `机甲和战斗无人机无敌`:修复受伤后启用时机甲耐久度和能量护盾保护可能失效的问题,并恢复太空编队的无敌保护。
* `建造秒完成`:修复开始新游戏时可能报错的问题。建造会在开场动画播放结束或跳过后开始。
* `传送带信号物品生成`:
* 按当前配方完善原料、中间产物、副产物和增产剂的统计,分别记录生产和消耗。配方数据不完整时,仅暂停受影响物品的上游统计,物品仍会正常生成。
* 修复其他星球上的信号传送带在建造或被摧毁时,错误影响当前星球上传送带的问题,例如战场分析基站无人机建造或黑雾摧毁传送带。被摧毁的信号传送带也不会再让之后替换它的传送带继续生成物品。
* 2.4.7 * 2.4.7
* `开发模式快捷键`:修复载入存档后启用时不生效的问题;加速游戏时每次按键仍只执行一次。
* `使用组合键点击解锁科技` 新增降级模式。 * `使用组合键点击解锁科技` 新增降级模式。
* 按 `Caps Lock` 切换降级模式。按住组合键点击可降低科技等级,同时回退升级效果及后继科技等级;`Alt` 将科技回退到未解锁。 * 按 `Caps Lock` 切换降级模式。按住组合键点击可降低科技等级,同时回退升级效果及后继科技等级;`Alt` 将科技回退到未解锁。
* 弹窗和警告横幅显示当前模式,科技树中的帮助按钮提供组合键说明。 * 弹窗和警告横幅显示当前模式,科技树中的帮助按钮提供组合键说明。
+1 -1
View File
@@ -10,7 +10,7 @@ using UXAssist.Common.ModFeatures;
namespace CheatEnabler; namespace CheatEnabler;
[BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)] [BepInPlugin(PluginInfo.PLUGIN_GUID, PluginInfo.PLUGIN_NAME, PluginInfo.PLUGIN_VERSION)]
[BepInDependency(UXAssist.PluginInfo.PLUGIN_GUID, "1.6.3")] [BepInDependency(UXAssist.PluginInfo.PLUGIN_GUID)]
public class CheatEnabler : BaseUnityPlugin public class CheatEnabler : BaseUnityPlugin
{ {
public new static readonly BepInEx.Logging.ManualLogSource Logger = public new static readonly BepInEx.Logging.ManualLogSource Logger =
+1 -1
View File
@@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<BepInExPluginGuid>org.soardev.cheatenabler</BepInExPluginGuid> <BepInExPluginGuid>org.soardev.cheatenabler</BepInExPluginGuid>
<Description>DSP MOD - CheatEnabler</Description> <Description>DSP MOD - CheatEnabler</Description>
<Version>2.4.8</Version> <Version>2.4.7</Version>
<PackageId>CheatEnabler</PackageId> <PackageId>CheatEnabler</PackageId>
<RootNamespace>CheatEnabler</RootNamespace> <RootNamespace>CheatEnabler</RootNamespace>
<PackHasChangelog>true</PackHasChangelog> <PackHasChangelog>true</PackHasChangelog>
@@ -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;
@@ -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)
+12 -10
View File
@@ -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()
@@ -79,10 +81,10 @@ public static class PlayerFunctions
var propertySystem = DSPGame.propertySystem; var propertySystem = DSPGame.propertySystem;
if (propertySystem == null) return; if (propertySystem == null) return;
PurgePropertySystem(propertySystem); PurgePropertySystem(propertySystem);
var itemCnt = new int[ItemIds.UniverseMatrix - ItemIds.ElectromagneticMatrix + 1]; var itemCnt = new int[ItemIds.Metaverse - ItemIds.HydrogenFuelRod + 1];
foreach (var cons in propertySystem.propertyDatas.SelectMany(data => data.totalConsumption.Where(cons => cons.id is >= ItemIds.ElectromagneticMatrix and <= ItemIds.UniverseMatrix))) foreach (var cons in propertySystem.propertyDatas.SelectMany(data => data.totalConsumption.Where(cons => cons.id is >= ItemIds.HydrogenFuelRod and <= ItemIds.Metaverse)))
{ {
itemCnt[cons.id - ItemIds.ElectromagneticMatrix] += cons.count; itemCnt[cons.id - ItemIds.HydrogenFuelRod] += cons.count;
} }
if (itemCnt.All(cnt => cnt == 0)) if (itemCnt.All(cnt => cnt == 0))
@@ -95,7 +97,7 @@ public static class PlayerFunctions
{ {
if (itemCnt[i] > 0) if (itemCnt[i] > 0)
{ {
msg += $"\n {LDB.items.Select(i + ItemIds.ElectromagneticMatrix).propertyName} x{itemCnt[i]}"; msg += $"\n {LDB.items.Select(i + ItemIds.HydrogenFuelRod).propertyName} x{itemCnt[i]}";
} }
} }
UIMessageBox.Show(Localization.RemoveAllMetadataConsumptionRecords.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () => UIMessageBox.Show(Localization.RemoveAllMetadataConsumptionRecords.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () =>
@@ -119,7 +121,7 @@ public static class PlayerFunctions
var propertySystem = DSPGame.propertySystem; var propertySystem = DSPGame.propertySystem;
if (propertySystem == null) return; if (propertySystem == null) return;
PurgePropertySystem(propertySystem); PurgePropertySystem(propertySystem);
var itemCnt = new int[ItemIds.UniverseMatrix - ItemIds.ElectromagneticMatrix + 1]; var itemCnt = new int[ItemIds.Metaverse - ItemIds.HydrogenFuelRod + 1];
var seedKey = DSPGame.GameDesc.seedKey64; var seedKey = DSPGame.GameDesc.seedKey64;
var clusterPropertyData = propertySystem.propertyDatas.FirstOrDefault(cpd => cpd.seedKey == seedKey); var clusterPropertyData = propertySystem.propertyDatas.FirstOrDefault(cpd => cpd.seedKey == seedKey);
if (clusterPropertyData == null) if (clusterPropertyData == null)
@@ -128,9 +130,9 @@ public static class PlayerFunctions
return; return;
} }
var currentGamePropertyData = GameMain.data.history.propertyData; var currentGamePropertyData = GameMain.data.history.propertyData;
foreach (var cons in currentGamePropertyData.totalConsumption.Where(cons => cons.id is >= ItemIds.ElectromagneticMatrix and <= ItemIds.UniverseMatrix)) foreach (var cons in currentGamePropertyData.totalConsumption.Where(cons => cons.id is >= ItemIds.HydrogenFuelRod and <= ItemIds.Metaverse))
{ {
itemCnt[cons.id - ItemIds.ElectromagneticMatrix] += cons.count; itemCnt[cons.id - ItemIds.HydrogenFuelRod] += cons.count;
} }
if (itemCnt.All(cnt => cnt == 0)) if (itemCnt.All(cnt => cnt == 0))
@@ -143,7 +145,7 @@ public static class PlayerFunctions
{ {
if (itemCnt[i] > 0) if (itemCnt[i] > 0)
{ {
msg += $"\n {LDB.items.Select(i + ItemIds.ElectromagneticMatrix).propertyName} x{itemCnt[i]}"; msg += $"\n {LDB.items.Select(i + ItemIds.HydrogenFuelRod).propertyName} x{itemCnt[i]}";
} }
} }
UIMessageBox.Show(Localization.RemoveMetadataConsumptionRecordInCurrentGame.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () => UIMessageBox.Show(Localization.RemoveMetadataConsumptionRecordInCurrentGame.Translate(), msg, Localization.Cancel.Translate(), Localization.OK.Translate(), UIMessageBox.QUESTION, null, () =>
@@ -152,8 +154,8 @@ public static class PlayerFunctions
{ {
if (clusterPropertyData.totalConsumption[i].count == 0) continue; if (clusterPropertyData.totalConsumption[i].count == 0) continue;
var id = clusterPropertyData.totalConsumption[i].id; var id = clusterPropertyData.totalConsumption[i].id;
if (id < ItemIds.ElectromagneticMatrix || id > ItemIds.UniverseMatrix) continue; if (id < ItemIds.HydrogenFuelRod || id > ItemIds.Metaverse) continue;
var currentGameCount = itemCnt[id - ItemIds.ElectromagneticMatrix]; var currentGameCount = itemCnt[id - ItemIds.HydrogenFuelRod];
if (currentGameCount == 0) continue; if (currentGameCount == 0) continue;
var totalCount = clusterPropertyData.totalConsumption[i].count; var totalCount = clusterPropertyData.totalConsumption[i].count;
clusterPropertyData.totalConsumption[i] = new IDCNT(id, totalCount > currentGameCount ? totalCount - currentGameCount : 0); clusterPropertyData.totalConsumption[i] = new IDCNT(id, totalCount > currentGameCount ? totalCount - currentGameCount : 0);
+17 -28
View File
@@ -1,11 +1,10 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Reflection;
using System.Reflection.Emit; using System.Reflection.Emit;
using BepInEx.Configuration; using BepInEx.Configuration;
using HarmonyLib; using HarmonyLib;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.ModFeatures; using UXAssist.Common.ModFeatures;
using UXAssist.Common.Patching;
namespace CheatEnabler.Patches; namespace CheatEnabler.Patches;
@@ -49,37 +48,27 @@ public static class CombatPatch
); );
return matcher.InstructionEnumeration(); return matcher.InstructionEnumeration();
} }
// Harmony transpiler: Mecha_Invincible_Transpiler // Harmony transpiler: SkillSystem_DamageObject_Transpiler
// Target: Mecha.TakeDamage, Mecha.EnergyShieldResist (both overloads) // Target: SkillSystem.DamageGroundObjectByLocalCaster, SkillSystem.DamageGroundObjectByRemoteCaster, SkillSystem.DamageObject
// Fallback: Return original instructions if the invincibility check is not found. // Fallback: None — patch will fail loudly if the target method body changes.
[HarmonyTranspiler] [HarmonyTranspiler]
[HarmonyPatch(typeof(Mecha), nameof(Mecha.TakeDamage))]
[HarmonyPatch(typeof(Mecha), nameof(Mecha.EnergyShieldResist), [typeof(int)], [ArgumentType.Ref])]
[HarmonyPatch(typeof(Mecha), nameof(Mecha.EnergyShieldResist), [typeof(int), typeof(int)], [ArgumentType.Ref, ArgumentType.Out])]
private static IEnumerable<CodeInstruction> Mecha_Invincible_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
// Repatch the consumers too: an already inlined getter bypasses its own Harmony patch.
var original = instructions.ToList();
var matcher = new CodeMatcher(original, generator);
matcher.MatchForward(false, new CodeMatch(ci => ci.Calls(AccessTools.PropertyGetter(typeof(Player), nameof(Player.invincible)))));
if (matcher.IsInvalid) return matcher.Finish(original, CheatEnabler.Logger, nameof(Mecha_Invincible_Transpiler));
matcher.Set(OpCodes.Pop, null).Advance(1).Insert(new CodeInstruction(OpCodes.Ldc_I4_1));
return matcher.InstructionEnumeration();
}
[HarmonyPrefix]
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByLocalCaster))] [HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByLocalCaster))]
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByRemoteCaster))] [HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageGroundObjectByRemoteCaster))]
private static void SkillSystem_DamageGroundObject_Prefix(ref int damage, ref SkillTargetLocal target)
{
if (target.type == ETargetType.Craft) damage = 0;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageObject))] [HarmonyPatch(typeof(SkillSystem), nameof(SkillSystem.DamageObject))]
private static void SkillSystem_DamageObject_Prefix(ref int damage, ref SkillTarget target) private static IEnumerable<CodeInstruction> SkillSystem_DamageObject_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase __originalMethod)
{ {
if (target.type == ETargetType.Craft) damage = 0; var matcher = new CodeMatcher(instructions, generator);
matcher.MatchForward(false,
new CodeMatch(ci => ci.IsLdarg()),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(SkillTargetLocal), nameof(SkillTargetLocal.type))),
new CodeMatch(OpCodes.Ldc_I4_6),
new CodeMatch(ci => ci.opcode == OpCodes.Bne_Un || ci.opcode == OpCodes.Bne_Un_S)
);
matcher.Repeat(m => m.Advance(4).InsertAndAdvance(
new CodeInstruction(OpCodes.Ldc_I4_0),
new CodeInstruction(OpCodes.Starg_S, __originalMethod.Name == "DamageObject" ? 1 : 2)
));
return matcher.InstructionEnumeration();
} }
} }
+27 -41
View File
@@ -16,13 +16,13 @@ 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;
private static readonly Dictionary<(int itemId, bool proliferated, bool sprayed), private static readonly Dictionary<(int itemId, bool proliferated, bool sprayed),
IReadOnlyList<BeltSignalSourceRate>> SourceCache = []; IReadOnlyList<BeltSignalSourceRate>> SourceCache = [];
private static readonly HashSet<(int itemId, bool proliferated, bool sprayed)> FailedSources = []; private static readonly HashSet<(int itemId, bool proliferated, bool sprayed)> FailedSources = [];
private static readonly HashSet<BeltSignal> PendingSources = [];
public static void Init() public static void Init()
{ {
@@ -36,20 +36,13 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
ProductionCatalogService.Changed -= OnProductionCatalogChanged; ProductionCatalogService.Changed -= OnProductionCatalogChanged;
} }
public static void OnUpdate()
{
if (PendingSources.Count == 0) return;
foreach (var beltSignal in PendingSources) TryApplySources(beltSignal, true);
PendingSources.Clear();
}
private static void ResetState() private static void ResetState()
{ {
_initialized = false; _initialized = false;
_signalBelts = null; _signalBelts = null;
_portalFrom = null; _portalFrom = null;
_portalTo = null; _portalTo = null;
PendingSources.Clear(); _signalBeltsCapacity = 0;
ClearSourceCache(); ClearSourceCache();
} }
@@ -82,7 +75,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
GameLogicProc.OnGameBegin -= OnGameBegin; GameLogicProc.OnGameBegin -= OnGameBegin;
_initialized = false; _initialized = false;
_signalBelts = null; _signalBelts = null;
PendingSources.Clear(); _signalBeltsCapacity = 0;
ClearSourceCache(); ClearSourceCache();
} }
@@ -178,6 +171,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 +215,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 +236,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)
@@ -307,15 +302,8 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
private static void AddSourcesToBeltSignal(BeltSignal beltSignal) private static void AddSourcesToBeltSignal(BeltSignal beltSignal)
{ {
beltSignal.SourceStats = null; beltSignal.SourceStats = null;
// Signals can change inside the logic tick, for example when drones finish a blueprint, so missing rates
// are planned in the next frame update and the tick only applies cached rates.
if (!TryApplySources(beltSignal, false)) PendingSources.Add(beltSignal);
}
private static bool TryApplySources(BeltSignal beltSignal, bool calculate)
{
var itemId = beltSignal.SignalId; var itemId = beltSignal.SignalId;
if (itemId < 1000 || beltSignal.Stack == 0) return true; if (itemId < 1000 || beltSignal.Stack == 0) return;
var catalog = ProductionCatalogService.Current; var catalog = ProductionCatalogService.Current;
if (!ReferenceEquals(_sourceCatalog, catalog)) if (!ReferenceEquals(_sourceCatalog, catalog))
{ {
@@ -331,13 +319,12 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
if (catalog == null) if (catalog == null)
{ {
LogSourceFailure(key, "Production data is not loaded."); LogSourceFailure(key, "Production data is not loaded.");
return true; return;
} }
if (FailedSources.Contains(key)) return true; if (FailedSources.Contains(key)) return;
if (!SourceCache.TryGetValue(key, out var rates)) if (!SourceCache.TryGetValue(key, out var rates))
{ {
if (!calculate) return false;
try try
{ {
var request = BeltSignalSourcePreset.Create(catalog, itemId, proliferated, sprayed); var request = BeltSignalSourcePreset.Create(catalog, itemId, proliferated, sprayed);
@@ -345,7 +332,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
if (!report.MaterialComplete) if (!report.MaterialComplete)
{ {
LogSourceFailure(key, string.Join("; ", report.Diagnostics.Select(diagnostic => diagnostic.Message))); LogSourceFailure(key, string.Join("; ", report.Diagnostics.Select(diagnostic => diagnostic.Message)));
return true; return;
} }
rates = BeltSignalSourceStats.FromReport(report, itemId); rates = BeltSignalSourceStats.FromReport(report, itemId);
@@ -353,14 +340,13 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
catch (Exception exception) catch (Exception exception)
{ {
LogSourceFailure(key, exception.ToString()); LogSourceFailure(key, exception.ToString());
return true; return;
} }
SourceCache[key] = rates; SourceCache[key] = rates;
} }
if (rates.Count > 0) beltSignal.SourceStats = new BeltSignalSourceStats(rates); if (rates.Count > 0) beltSignal.SourceStats = new BeltSignalSourceStats(rates);
return true;
} }
private static void LogSourceFailure((int itemId, bool proliferated, bool sprayed) key, string reason) private static void LogSourceFailure((int itemId, bool proliferated, bool sprayed) key, string reason)
@@ -422,15 +408,13 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
[HarmonyPrefix] [HarmonyPrefix]
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RemoveBeltComponent))] [HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RemoveBeltComponent))]
public static void CargoTraffic_RemoveBeltComponent_Prefix(CargoTraffic __instance, int id) public static void CargoTraffic_RemoveBeltComponent_Prefix(int id)
{ {
if (!_initialized) return; if (!_initialized) return;
// Belts also change on planets other than the local one, for example through Battlefield Analysis Base var planet = GameMain.localPlanet;
// construction or Dark Fog attacks, so always use the factory that owns the belt. if (planet == null) return;
var factory = __instance.factory; RemoveSignalBeltPortalEnd(planet.factoryIndex, id);
if (factory == null) return; RemoveSignalBelt(planet.factoryIndex, id);
RemoveSignalBeltPortalEnd(factory.index, id);
RemoveSignalBelt(factory.index, id);
} }
[HarmonyPostfix] [HarmonyPostfix]
@@ -438,8 +422,9 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
public static void CargoTraffic_SetBeltSignalIcon_Postfix(CargoTraffic __instance, int signalId, int entityId) public static void CargoTraffic_SetBeltSignalIcon_Postfix(CargoTraffic __instance, int signalId, int entityId)
{ {
if (!_initialized) return; if (!_initialized) return;
var planet = GameMain.localPlanet;
if (planet == null) return;
var factory = __instance.factory; var factory = __instance.factory;
if (factory == null) return;
int number; int number;
var needAdd = false; var needAdd = false;
switch (signalId) switch (signalId)
@@ -456,7 +441,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
break; break;
case >= 601 and <= 609: case >= 601 and <= 609:
number = Mathf.RoundToInt(factory.entitySignPool[entityId].count0); number = Mathf.RoundToInt(factory.entitySignPool[entityId].count0);
var factoryIndex = factory.index; var factoryIndex = planet.factoryIndex;
var beltId = factory.entityPool[entityId].beltId; var beltId = factory.entityPool[entityId].beltId;
if (number > 0) if (number > 0)
SetSignalBeltPortalTo(factoryIndex, beltId, number); SetSignalBeltPortalTo(factoryIndex, beltId, number);
@@ -468,7 +453,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
} }
{ {
var factoryIndex = factory.index; var factoryIndex = planet.factoryIndex;
var beltId = factory.entityPool[entityId].beltId; var beltId = factory.entityPool[entityId].beltId;
if (needAdd) if (needAdd)
{ {
@@ -488,8 +473,9 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
public static void CargoTraffic_SetBeltSignalNumber_Postfix(CargoTraffic __instance, float number, int entityId) public static void CargoTraffic_SetBeltSignalNumber_Postfix(CargoTraffic __instance, float number, int entityId)
{ {
if (!_initialized) return; if (!_initialized) return;
var planet = GameMain.localPlanet;
if (planet == null) return;
var factory = __instance.factory; var factory = __instance.factory;
if (factory == null) return;
var entitySignPool = factory.entitySignPool; var entitySignPool = factory.entitySignPool;
uint signalId; uint signalId;
if (entitySignPool[entityId].iconType == 0U || (signalId = entitySignPool[entityId].iconId0) == 0U) return; if (entitySignPool[entityId].iconType == 0U || (signalId = entitySignPool[entityId].iconId0) == 0U) return;
@@ -501,7 +487,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
case >= 1000 and < 20000: case >= 1000 and < 20000:
break; break;
case >= 601 and <= 609: case >= 601 and <= 609:
var factoryIndex = factory.index; var factoryIndex = planet.factoryIndex;
var beltId = factory.entityPool[entityId].beltId; var beltId = factory.entityPool[entityId].beltId;
RemoveSignalBeltPortalEnd(factoryIndex, beltId); RemoveSignalBeltPortalEnd(factoryIndex, beltId);
SetSignalBeltPortalTo(factoryIndex, beltId, Mathf.RoundToInt(number)); SetSignalBeltPortalTo(factoryIndex, beltId, Mathf.RoundToInt(number));
@@ -511,7 +497,7 @@ internal class BeltSignalGenerator : PatchImpl<BeltSignalGenerator>
} }
{ {
var factoryIndex = factory.index; var factoryIndex = planet.factoryIndex;
var beltId = factory.entityPool[entityId].beltId; var beltId = factory.entityPool[entityId].beltId;
var n = Mathf.RoundToInt(number); var n = Mathf.RoundToInt(number);
if (n == 0) if (n == 0)
@@ -113,27 +113,11 @@ internal static class BeltSignalSourcePreset
if (catalog.Items.ContainsKey(externalItemId)) request.ExternalMaterials.Add(externalItemId); if (catalog.Items.ContainsKey(externalItemId)) request.ExternalMaterials.Add(externalItemId);
} }
// Keep the legacy preference for explicit recipes, which include the rare-resource alternatives. Explicit
// recipes that consume their own product, X-ray Cracking and Reforming Refine, never supply an item.
foreach (var recipe in catalog.Recipes.Values
.Where(recipe => recipe.Explicit && !recipe.Outputs.Keys.Any(recipe.Inputs.ContainsKey))
.OrderBy(recipe => recipe.Id))
{
foreach (var outputId in recipe.Outputs.Keys)
{
if (request.RecipeByItem.ContainsKey(outputId) || request.ExternalMaterials.Contains(outputId) ||
!catalog.Items.TryGetValue(outputId, out var output) || output.IsNatural) continue;
request.RecipeByItem[outputId] = recipe.Id;
}
}
if (!useProliferator) return request; if (!useProliferator) return request;
if (sprayDeliveredItem) request.SprayDeliveredItems.Add(itemId); if (sprayDeliveredItem) request.SprayDeliveredItems.Add(itemId);
foreach (var item in catalog.Items.Values) foreach (var item in catalog.Items.Values)
{ {
var recipeId = request.RecipeByItem.TryGetValue(item.Id, out var selectedRecipeId) if (!catalog.Recipes.TryGetValue(item.DefaultRecipeId, out var recipe) ||
? selectedRecipeId : item.DefaultRecipeId;
if (!catalog.Recipes.TryGetValue(recipeId, out var recipe) ||
!recipe.Outputs.ContainsKey(item.Id) || recipe.Inputs.Count == 0) continue; !recipe.Outputs.ContainsKey(item.Id) || recipe.Inputs.Count == 0) continue;
request.ProliferationModeByItem[item.Id] = ItemIds.NoProliferationItemIds.Contains(item.Id) request.ProliferationModeByItem[item.Id] = ItemIds.NoProliferationItemIds.Contains(item.Id)
? ProliferationMode.None ? ProliferationMode.None
+4 -7
View File
@@ -88,14 +88,14 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
ControlPanelRemoteLogistics.Enable(ControlPanelRemoteLogisticsEnabled.Value); ControlPanelRemoteLogistics.Enable(ControlPanelRemoteLogisticsEnabled.Value);
Enable(true); Enable(true);
CargoTrafficPatch.Enable(true); CargoTrafficPatch.Enable(true);
GameLogicProc.OnGameBegin += OnGameBeginOrGuideComplete; GameLogicProc.OnGameBegin += OnGameBegin_For_ImmBuild;
GameLogicProc.OnDataLoaded += OnDataLoaded; GameLogicProc.OnDataLoaded += OnDataLoaded;
} }
public static void Uninit() public static void Uninit()
{ {
GameLogicProc.OnDataLoaded -= OnDataLoaded; GameLogicProc.OnDataLoaded -= OnDataLoaded;
GameLogicProc.OnGameBegin -= OnGameBeginOrGuideComplete; GameLogicProc.OnGameBegin -= OnGameBegin_For_ImmBuild;
CargoTrafficPatch.Enable(false); CargoTrafficPatch.Enable(false);
Enable(false); Enable(false);
ImmediateBuild.Enable(false); ImmediateBuild.Enable(false);
@@ -152,8 +152,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
if (factory.prebuildCount <= 0) return; if (factory.prebuildCount <= 0) return;
var imm = ImmediateEnabled.Value; var imm = ImmediateEnabled.Value;
var architect = ArchitectModeEnabled.Value; var architect = ArchitectModeEnabled.Value;
if ((!imm && !architect) || GameMain.gameScenario == null || if ((!imm && !architect) || GameMain.gameScenario == null) return;
GameMain.data?.guideComplete != true) return;
var prebuilds = factory.prebuildPool; var prebuilds = factory.prebuildPool;
if (imm) if (imm)
{ {
@@ -194,9 +193,7 @@ public class FactoryPatch : PatchImpl<FactoryPatch>
} }
} }
[HarmonyPostfix] private static void OnGameBegin_For_ImmBuild()
[HarmonyPatch(typeof(GameData), nameof(GameData.EndStandardModeGuide))]
private static void OnGameBeginOrGuideComplete()
{ {
if (DSPGame.IsMenuDemo) return; if (DSPGame.IsMenuDemo) return;
var factory = GameMain.mainPlayer?.factory; var factory = GameMain.mainPlayer?.factory;
@@ -174,7 +174,6 @@ internal class ImmediateBuild : PatchImpl<ImmediateBuild>
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic.FactoryConstructionSystemGameTick))] [HarmonyPatch(typeof(GameLogic), nameof(GameLogic.FactoryConstructionSystemGameTick))]
private static void GameLogic_FactoryConstructionSystemGameTick_Prefix(GameLogic __instance) private static void GameLogic_FactoryConstructionSystemGameTick_Prefix(GameLogic __instance)
{ {
if (GameMain.data?.guideComplete != true || GameMain.gameScenario == null) return;
var time = __instance.timei; var time = __instance.timei;
if (time % 6 != 0) return; if (time % 6 != 0) return;
var planet = GameMain.localPlanet; var planet = GameMain.localPlanet;
+8 -26
View File
@@ -36,12 +36,6 @@ public static class GamePatch
DevShortcuts.Enable(false); DevShortcuts.Enable(false);
} }
public static void OnInputUpdate()
{
if (!DevShortcutsEnabled.Value || DSPGame.IsMenuDemo || GameMain.isPaused || !GameMain.isRunning) return;
DevShortcuts.OnInputUpdate();
}
private static void ResetState() private static void ResetState()
{ {
AbnormalDisabler.ResetState(); AbnormalDisabler.ResetState();
@@ -114,7 +108,6 @@ public static class GamePatch
protected override void OnEnable() protected override void OnEnable()
{ {
AttachToController(GameMain.mainPlayer?.controller);
if (_test != null) _test.active = true; if (_test != null) _test.active = true;
} }
@@ -132,36 +125,25 @@ public static class GamePatch
[HarmonyPatch(typeof(PlayerController), nameof(PlayerController.Init))] [HarmonyPatch(typeof(PlayerController), nameof(PlayerController.Init))]
private static void PlayerController_Init_Postfix(PlayerController __instance) private static void PlayerController_Init_Postfix(PlayerController __instance)
{ {
AttachToController(__instance); var cnt = __instance.actions.Length;
}
private static void AttachToController(PlayerController controller)
{
if (controller?.actions == null) return;
foreach (var action in controller.actions)
{
if (action is not PlayerAction_Test test) continue;
_test = test;
_test.active = DevShortcutsEnabled.Value;
return;
}
var cnt = controller.actions.Length;
var newActions = new PlayerAction[cnt + 1]; var newActions = new PlayerAction[cnt + 1];
for (var i = 0; i < cnt; i++) for (var i = 0; i < cnt; i++)
{ {
newActions[i] = controller.actions[i]; newActions[i] = __instance.actions[i];
} }
_test = new PlayerAction_Test(); _test = new PlayerAction_Test();
_test.Init(controller.player); _test.Init(__instance.player);
_test.active = DevShortcutsEnabled.Value; _test.active = DevShortcutsEnabled.Value;
newActions[cnt] = _test; newActions[cnt] = _test;
controller.actions = newActions; __instance.actions = newActions;
} }
internal static void OnInputUpdate() [HarmonyPostfix]
[HarmonyPatch(typeof(PlayerAction_Test), nameof(PlayerAction_Test.GameTick))]
private static void PlayerAction_Test_GameTick_Postfix(PlayerAction_Test __instance)
{ {
if (GetHarmony() != null && _test?.active == true) _test.Update(); __instance.Update();
} }
// Harmony transpiler: PlayerAction_Test_Update_Transpiler // Harmony transpiler: PlayerAction_Test_Update_Transpiler
// Target: PlayerAction_Test.Update // Target: PlayerAction_Test.Update
+1 -2
View File
@@ -35,10 +35,9 @@ public static class ResourcePatch
{ {
static private readonly float InfiniteResourceRate = 0f; static private readonly float InfiniteResourceRate = 0f;
// Harmony transpiler: Transpiler // Harmony transpiler: Transpiler
// Target: FactorySystem.GameTick, GameLogic._miner_parallel, PlanetTransport.GameTick, FactoryPatch.GetMiningCostRate (UXAssist), UIChartAstroResource.CalculateMaxAmount, UIChartVeinGroup.CalculateMaxAmount, UIControlPanelAdvancedMinerEntry._OnUpdate, UIControlPanelVeinCollectorPanel._OnUpdate, UIMinerWindow._OnUpdate, UIMiningUpgradeLabel.Update, UIVeinCollectorPanel._OnUpdate // Target: FactorySystem.GameTick, GameLogic._miner_parallel, PlanetTransport.GameTick, UIChartAstroResource.CalculateMaxAmount, UIChartVeinGroup.CalculateMaxAmount, UIControlPanelAdvancedMinerEntry._OnUpdate, UIControlPanelVeinCollectorPanel._OnUpdate, UIMinerWindow._OnUpdate, UIMiningUpgradeLabel.Update, UIVeinCollectorPanel._OnUpdate
// Fallback: None — patch will fail loudly if the target method body changes. // Fallback: None — patch will fail loudly if the target method body changes.
[HarmonyTranspiler] [HarmonyTranspiler]
[HarmonyPatch(typeof(UXAssist.Patches.Factory.FactoryPatch), nameof(UXAssist.Patches.Factory.FactoryPatch.GetMiningCostRate))]
[HarmonyPatch(typeof(FactorySystem), nameof(FactorySystem.GameTick), typeof(long), typeof(bool))] [HarmonyPatch(typeof(FactorySystem), nameof(FactorySystem.GameTick), typeof(long), typeof(bool))]
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic._miner_parallel))] [HarmonyPatch(typeof(GameLogic), nameof(GameLogic._miner_parallel))]
[HarmonyPatch(typeof(PlanetTransport), nameof(PlanetTransport.GameTick))] [HarmonyPatch(typeof(PlanetTransport), nameof(PlanetTransport.GameTick))]
+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);
+1 -25
View File
@@ -26,7 +26,6 @@
* Factory: * Factory:
* Finish build immediately * Finish build immediately
* Completes pending buildings as soon as their required building items are available * Completes pending buildings as soon as their required building items are available
* Starts after the opening cutscene has ended or been skipped
* Architect mode * Architect mode
* Unlimited use of buildings, Logistics Bots, Logistics Drones and Interstellar Logistics Vessels * Unlimited use of buildings, Logistics Bots, Logistics Drones and Interstellar Logistics Vessels
* Construction and inventory availability checks show at least 999 of each supported item. * Construction and inventory availability checks show at least 999 of each supported item.
@@ -75,25 +74,14 @@
* Keep the highest-production shells and remove the others * Keep the highest-production shells and remove the others
* Duplicate the highest-production shells with a configurable shell count * Duplicate the highest-production shells with a configurable shell count
* Mecha/Combat: * Mecha/Combat:
* Mecha and Drones/Fleets invincible * Mecha and Drones/Fleets invicible
* Protects mecha HP and energy shields, ground combat drones, and space fleets, including when enabled during combat.
* Buildings invicible * Buildings invicible
* Enable warp without space warpers * Enable warp without space warpers
* Teleport to outer space * Teleport to outer space
* Teleport to selected astronomical * Teleport to selected astronomical
## Belt signal generator example
1. Open the UXAssist settings, select `Cheat Enabler` -> `Factory`, and enable `Belt signal generator`.
2. Leave `Belt signal alt format` unchecked for this example.
3. Click a conveyor belt and choose the item you want to generate as its signal icon.
4. Set the signal number to `6001` to generate one item per second. Leave room on the belt for the generated items.
The item icon selects the output; no hotkey is needed.
## Notes ## Notes
* Requires UXAssist 1.6.3 or later. When upgrading manually, replace the old UXAssist DLL and remove duplicate copies from the BepInEx plugins folder.
* Please upgrade `BepInEx` 5.4.21 or later if using with [BlueprintTweaks](https://dsp.thunderstore.io/package/kremnev8/BlueprintTweaks/) to avoid possible conflicts. * Please upgrade `BepInEx` 5.4.21 or later if using with [BlueprintTweaks](https://dsp.thunderstore.io/package/kremnev8/BlueprintTweaks/) to avoid possible conflicts.
* You can download [BepInEx here](https://github.com/bepinex/bepinex/releases/latest)(choose x64 edition). * You can download [BepInEx here](https://github.com/bepinex/bepinex/releases/latest)(choose x64 edition).
* If using with r2modman, you can upgrade `BepInEx` by clicking `Settings` -> `Browse profile folder`, then extract downloaded zip to the folder and overwrite existing files. * If using with r2modman, you can upgrade `BepInEx` by clicking `Settings` -> `Browse profile folder`, then extract downloaded zip to the folder and overwrite existing files.
@@ -132,7 +120,6 @@ The item icon selects the output; no hotkey is needed.
* 工厂: * 工厂:
* 建造秒完成 * 建造秒完成
* 所需建筑物品齐备后立即完成待建造建筑 * 所需建筑物品齐备后立即完成待建造建筑
* 开场动画播放结束或跳过后生效
* 建筑师模式 * 建筑师模式
* 建筑、配送运输机、物流运输机和星际物流运输船可无限使用 * 建筑、配送运输机、物流运输机和星际物流运输船可无限使用
* 建造及库存可用数量检查中,每种受支持物品至少显示 999 个。 * 建造及库存可用数量检查中,每种受支持物品至少显示 999 个。
@@ -182,24 +169,13 @@ The item icon selects the output; no hotkey is needed.
* 从发电量最高的壳复制戴森壳,可设置壳面数量 * 从发电量最高的壳复制戴森壳,可设置壳面数量
* 机甲/战斗: * 机甲/战斗:
* 机甲和战斗无人机无敌 * 机甲和战斗无人机无敌
* 保护机甲耐久度和能量护盾、地面战斗无人机和太空编队,战斗中开启同样生效。
* 建筑无敌 * 建筑无敌
* 无需空间翘曲器即可曲速飞行 * 无需空间翘曲器即可曲速飞行
* 传送到外太空 * 传送到外太空
* 传送到选定的天体 * 传送到选定的天体
## 传送带信号物品生成示例
1. 打开 UXAssist 设置,在 `Cheat Enabler` -> `工厂` 中勾选 `传送带信号物品生成`。
2. 此示例保持 `传送带信号替换格式` 不勾选。
3. 点击传送带,将需要生成的物品选为信号图标。
4. 将信号数值设为 `6001`,即可每秒生成一个物品。传送带上需要有空位接收物品。
信号图标决定生成哪种物品,无需快捷键。
## 注意事项 ## 注意事项
* 需要 UXAssist 1.6.3 或更高版本。手动升级时,请替换旧的 UXAssist DLL,并删除 BepInEx 插件目录中的重复副本。
* 如果和[BlueprintTweaks](https://dsp.thunderstore.io/package/kremnev8/BlueprintTweaks/)一起使用,请升级`BepInEx`到5.4.21或更高版本,以避免可能的冲突 * 如果和[BlueprintTweaks](https://dsp.thunderstore.io/package/kremnev8/BlueprintTweaks/)一起使用,请升级`BepInEx`到5.4.21或更高版本,以避免可能的冲突
* 你可以在[这里](https://github.com/bepinex/bepinex/releases/latest)(选择x64版本)下载`BepInEx` * 你可以在[这里](https://github.com/bepinex/bepinex/releases/latest)(选择x64版本)下载`BepInEx`
* 如果使用r2modman,你可以点击`Settings` -> `Browse profile folder`,然后将下载的zip解压到该文件夹并覆盖现有文件 * 如果使用r2modman,你可以点击`Settings` -> `Browse profile folder`,然后将下载的zip解压到该文件夹并覆盖现有文件
-6
View File
@@ -1,6 +0,0 @@
# TODO
Feature requests awaiting a development decision.
- [#75](https://github.com/soarqin/DSP_Mods/issues/75): Add vegetation preservation/removal choices and optional colored equator/meridian lines when reforming an entire planet.
- [#74](https://github.com/soarqin/DSP_Mods/issues/74): Add instant item transfer from producing buildings to consuming buildings on a planet, with an optional interstellar mode.
+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;
+2 -2
View File
@@ -1,10 +1,10 @@
{ {
"name": "CheatEnabler", "name": "CheatEnabler",
"version_number": "2.4.8", "version_number": "2.4.7",
"website_url": "https://github.com/soarqin/DSP_Mods/tree/master/CheatEnabler", "website_url": "https://github.com/soarqin/DSP_Mods/tree/master/CheatEnabler",
"description": "Add various cheat functions while disabling abnormal determinants / 添加一些作弊功能,同时屏蔽异常检测", "description": "Add various cheat functions while disabling abnormal determinants / 添加一些作弊功能,同时屏蔽异常检测",
"dependencies": [ "dependencies": [
"xiaoye97-BepInEx-5.4.17", "xiaoye97-BepInEx-5.4.17",
"soarqin-UXAssist-1.6.3" "soarqin-UXAssist-1.4.0"
] ]
} }
+14
View File
@@ -4,6 +4,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UXAssist", "UXAssist\UXAssi
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CheatEnabler", "CheatEnabler\CheatEnabler.csproj", "{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CheatEnabler", "CheatEnabler\CheatEnabler.csproj", "{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LogisticMiner", "LogisticMiner\LogisticMiner.csproj", "{7149D717-C913-4153-9425-38CB9D087F83}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HideTips", "HideTips\HideTips.csproj", "{4EABD71D-477F-448B-801B-48F8745A3FA7}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HideTips", "HideTips\HideTips.csproj", "{4EABD71D-477F-448B-801B-48F8745A3FA7}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dustbin", "Dustbin\Dustbin.csproj", "{931F0230-5941-4E49-AB19-66921AF14096}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dustbin", "Dustbin\Dustbin.csproj", "{931F0230-5941-4E49-AB19-66921AF14096}"
@@ -63,6 +65,18 @@ Global
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x64.Build.0 = Release|Any CPU {F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x64.Build.0 = Release|Any CPU
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.ActiveCfg = Release|Any CPU {F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.ActiveCfg = Release|Any CPU
{F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.Build.0 = Release|Any CPU {F9F16B62-D1D3-466B-BE22-E64B9EA957C2}.Release|x86.Build.0 = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x64.ActiveCfg = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x64.Build.0 = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x86.ActiveCfg = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Debug|x86.Build.0 = Debug|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|Any CPU.Build.0 = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x64.ActiveCfg = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x64.Build.0 = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x86.ActiveCfg = Release|Any CPU
{7149D717-C913-4153-9425-38CB9D087F83}.Release|x86.Build.0 = Release|Any CPU
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.Build.0 = Debug|Any CPU {4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|x64.ActiveCfg = Debug|Any CPU {4EABD71D-477F-448B-801B-48F8745A3FA7}.Debug|x64.ActiveCfg = Debug|Any CPU
-5
View File
@@ -26,11 +26,6 @@
<_ZipPath>$(_PackageDir)\$(ProjectName)-$(Version).zip</_ZipPath> <_ZipPath>$(_PackageDir)\$(ProjectName)-$(Version).zip</_ZipPath>
</PropertyGroup> </PropertyGroup>
<!-- Refresh referenced preloaders before collecting patchers; other projects skip this target. -->
<MSBuild Projects="@(ProjectReference)" Targets="CopyToParentPackage"
Properties="Configuration=$(Configuration)"
Condition="'$(PackUsePluginsLayout)' == 'true'" />
<!-- Sync manifest.json version_number from .csproj $(Version) before packaging --> <!-- Sync manifest.json version_number from .csproj $(Version) before packaging -->
<Exec Condition="Exists('$(_PackageDir)\manifest.json')" <Exec Condition="Exists('$(_PackageDir)\manifest.json')"
Command="powershell.exe -NoProfile -ExecutionPolicy Bypass -Command &quot;$f='$(_PackageDir)\manifest.json'; $c=[IO.File]::ReadAllText($f); $c=$c -replace '(\u0022version_number\u0022\s*:\s*\u0022)[^\u0022]*(\u0022)','${1}$(Version)${2}'; [IO.File]::WriteAllText($f,$c,[Text.UTF8Encoding]::new($true))&quot;" /> Command="powershell.exe -NoProfile -ExecutionPolicy Bypass -Command &quot;$f='$(_PackageDir)\manifest.json'; $c=[IO.File]::ReadAllText($f); $c=$c -replace '(\u0022version_number\u0022\s*:\s*\u0022)[^\u0022]*(\u0022)','${1}$(Version)${2}'; [IO.File]::WriteAllText($f,$c,[Text.UTF8Encoding]::new($true))&quot;" />
+73 -31
View File
@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib; using HarmonyLib;
using UnityEngine; using UnityEngine;
@@ -10,6 +11,7 @@ namespace Dustbin;
public static class BeltSignal public static class BeltSignal
{ {
private static HashSet<int>[] _signalBelts; private static HashSet<int>[] _signalBelts;
private static int _signalBeltsCapacity;
private static bool _initialized; private static bool _initialized;
private static Harmony _patch; private static Harmony _patch;
@@ -25,17 +27,35 @@ public static class BeltSignal
_patch?.UnpatchSelf(); _patch?.UnpatchSelf();
_patch = null; _patch = null;
_signalBelts = null; _signalBelts = null;
_signalBeltsCapacity = 0;
} }
} }
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 +64,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 +73,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();
@@ -65,6 +86,7 @@ public static class BeltSignal
{ {
if (!GameMain.isRunning) return; if (!GameMain.isRunning) return;
_signalBelts = new HashSet<int>[64]; _signalBelts = new HashSet<int>[64];
_signalBeltsCapacity = 64;
var factories = GameMain.data?.factories; var factories = GameMain.data?.factories;
if (factories == null) return; if (factories == null) return;
@@ -88,24 +110,35 @@ public static class BeltSignal
private static void SetSignalBelt(int factory, int beltId) private static void SetSignalBelt(int factory, int beltId)
{ {
var signalBelts = GetOrCreateSignalBelts(factory); var signalBelts = GetOrCreateSignalBelts(factory);
signalBelts?.Add(beltId); signalBelts.Add(beltId);
} }
private static HashSet<int> GetOrCreateSignalBelts(int index) private static HashSet<int> GetOrCreateSignalBelts(int index)
{ {
if (index < 0 || _signalBelts == null) return null; HashSet<int> obj;
if (index >= _signalBelts.Length) if (index < 0) return null;
if (index >= _signalBeltsCapacity)
{ {
var newCapacity = _signalBelts.Length * 2; var newCapacity = _signalBeltsCapacity * 2;
while (newCapacity <= index) newCapacity *= 2; var newSignalBelts = new HashSet<int>[newCapacity];
Array.Resize(ref _signalBelts, newCapacity); Array.Copy(_signalBelts, newSignalBelts, _signalBeltsCapacity);
_signalBelts = newSignalBelts;
_signalBeltsCapacity = newCapacity;
} }
return _signalBelts[index] ??= []; else
{
obj = _signalBelts[index];
if (obj != null) return obj;
}
obj = [];
_signalBelts[index] = obj;
return obj;
} }
private static HashSet<int> GetSignalBelts(int index) private static HashSet<int> GetSignalBelts(int index)
{ {
return _signalBelts != null && index >= 0 && index < _signalBelts.Length ? _signalBelts[index] : null; return index >= 0 && index < _signalBeltsCapacity ? _signalBelts[index] : null;
} }
private static void RemoveSignalBelt(int factory, int beltId) private static void RemoveSignalBelt(int factory, int beltId)
@@ -138,17 +171,21 @@ public static class BeltSignal
[HarmonyPrefix] [HarmonyPrefix]
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RemoveBeltComponent))] [HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.RemoveBeltComponent))]
public static void CargoTraffic_RemoveBeltComponent_Prefix(CargoTraffic __instance, int id) public static void CargoTraffic_RemoveBeltComponent_Prefix(int id)
{ {
RemoveSignalBelt(__instance.factory.index, id); var planet = GameMain.localPlanet;
if (planet == null) return;
RemoveSignalBelt(planet.factoryIndex, id);
} }
[HarmonyPostfix] [HarmonyPostfix]
[HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.SetBeltSignalIcon))] [HarmonyPatch(typeof(CargoTraffic), nameof(CargoTraffic.SetBeltSignalIcon))]
public static void CargoTraffic_SetBeltSignalIcon_Postfix(CargoTraffic __instance, int signalId, int entityId) public static void CargoTraffic_SetBeltSignalIcon_Postfix(CargoTraffic __instance, int signalId, int entityId)
{ {
var planet = GameMain.localPlanet;
if (planet == null) return;
var factory = __instance.factory; var factory = __instance.factory;
var factoryIndex = factory.index; var factoryIndex = planet.factoryIndex;
var beltId = factory.entityPool[entityId].beltId; var beltId = factory.entityPool[entityId].beltId;
if (signalId == 410) if (signalId == 410)
{ {
@@ -160,34 +197,39 @@ public static class BeltSignal
} }
} }
[HarmonyPostfix] [HarmonyTranspiler]
[HarmonyPatch(typeof(GameLogic), nameof(GameLogic.OnFactoryFrameBegin))] [HarmonyPatch(typeof(GameData), nameof(GameData.GameTick))]
public static void GameLogic_OnFactoryFrameBegin_Postfix(GameLogic __instance) public static IEnumerable<CodeInstruction> GameData_GameTick_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{ {
// TrashSystemGameTick overlaps worker-thread inserters; mutate cargo before factory workers start. var matcher = new CodeMatcher(instructions, generator);
var data = __instance.data; matcher.MatchForward(false,
var factories = data?.factories; new CodeMatch(OpCodes.Call, AccessTools.Method(typeof(PerformanceMonitor), nameof(PerformanceMonitor.EndSample)))
if (factories == null || _signalBelts == null) return; ).Advance(1).Insert(
for (var i = 0; i < data.factoryCount; i++) Transpilers.EmitDelegate(() =>
{
var factories = GameMain.data?.factories;
if (factories == null) return;
foreach (var factory in factories)
{ {
var factory = factories[i];
if (factory == null) continue; if (factory == null) continue;
var belts = GetSignalBelts(factory.index); var index = factory.index;
var belts = GetSignalBelts(index);
if (belts == null || belts.Count == 0) continue; if (belts == null || belts.Count == 0) continue;
var consumeRegister = data.statistics.production.factoryStatPool[factory.index].consumeRegister; var consumeRegister = GameMain.statistics.production.factoryStatPool[index].consumeRegister;
var cargoTraffic = factory.cargoTraffic; var cargoTraffic = factory.cargoTraffic;
foreach (var beltId in belts) foreach (var beltId in belts)
{ {
if (beltId <= 0 || beltId >= cargoTraffic.beltCursor) continue;
ref var belt = ref cargoTraffic.beltPool[beltId]; ref var belt = ref cargoTraffic.beltPool[beltId];
if (belt.id != beltId) continue;
var cargoPath = cargoTraffic.GetCargoPath(belt.segPathId); var cargoPath = cargoTraffic.GetCargoPath(belt.segPathId);
if (cargoPath == null) continue; if (cargoPath == null) continue;
var itemId = cargoPath.TryPickItem(belt.segIndex + belt.segPivotOffset - 5, 12, out var stack, out _); int itemId;
if (itemId <= 0) continue; if ((itemId = cargoPath.TryPickItem(belt.segIndex + belt.segPivotOffset - 5, 12, out var stack, out _)) <= 0) continue;
consumeRegister[itemId] += stack; consumeRegister[itemId] += stack;
Dustbin.CalcGetSands(itemId, stack, 0); Dustbin.CalcGetSands(itemId, stack, 0);
} }
} }
})
);
return matcher.InstructionEnumeration();
} }
} }
-10
View File
@@ -3,11 +3,6 @@
## Changelog ## Changelog
* 1.5.0
* `Storage dustbin`: Destroy splitter input to a storage placed above it, including stacked and proliferated cargo. Enabling dustbin mode also clears cached full-storage state. Move the checkbox to the title bar to prevent overlap with the English automation input label.
* `Tank dustbin`: Fix single tanks blocking liquid input after receiving their first stack, both with and without dustbin mode.
* `Belt signal dustbin`: Restore item disposal and startup compatibility with the current game simulation loop after DSP 0.10.33/0.10.34 updates.
* 1.4.0 * 1.4.0
* Refactorying Tank input logic codes, for better performance, and resolve a bug [#53](https://github.com/soarqin/DSP_Mods/issues/53) * Refactorying Tank input logic codes, for better performance, and resolve a bug [#53](https://github.com/soarqin/DSP_Mods/issues/53)
* Remove use of AssetBundle, move the belt signal icon into `Assembly Resources`, for better flexibility. * Remove use of AssetBundle, move the belt signal icon into `Assembly Resources`, for better flexibility.
@@ -48,11 +43,6 @@
## 更新日志 ## 更新日志
* 1.5.0
* `储物仓垃圾桶`:销毁四向分流器送入上方储物仓的物品,包括堆叠和喷涂增产剂的物品;启用垃圾桶时清除已满状态缓存。将复选框移至标题栏,避免与英文自动化输入说明重叠。
* `储液罐垃圾桶`:修复单层储液罐装入第一批液体后停止输入的问题,普通储存和垃圾桶模式均可正常工作。
* `传送带信号垃圾桶`:适配当前游戏的模拟循环,修复 DSP 0.10.33/0.10.34 更新后的启动报错和物品无法销毁问题。
* 1.4.0 * 1.4.0
* 重构储液罐的输入逻辑代码,以提高性能并解决bug [#53](https://github.com/soarqin/DSP_Mods/issues/53) * 重构储液罐的输入逻辑代码,以提高性能并解决bug [#53](https://github.com/soarqin/DSP_Mods/issues/53)
* 移除了AssetBundle的使用,将传送带信号图标移入`Assembly资源`,以获得更好的灵活性 * 移除了AssetBundle的使用,将传送带信号图标移入`Assembly资源`,以获得更好的灵活性
+1 -20
View File
@@ -3,7 +3,7 @@
<PropertyGroup> <PropertyGroup>
<BepInExPluginGuid>org.soardev.dustbin</BepInExPluginGuid> <BepInExPluginGuid>org.soardev.dustbin</BepInExPluginGuid>
<Description>DSP MOD - Dustbin</Description> <Description>DSP MOD - Dustbin</Description>
<Version>1.5.0</Version> <Version>1.4.0</Version>
<PackageId>Dustbin</PackageId> <PackageId>Dustbin</PackageId>
<RootNamespace>Dustbin</RootNamespace> <RootNamespace>Dustbin</RootNamespace>
<PackHasChangelog>true</PackHasChangelog> <PackHasChangelog>true</PackHasChangelog>
@@ -13,28 +13,9 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="DysonSphereProgram.Modding.DSPModSave" Version="1.*" /> <PackageReference Include="DysonSphereProgram.Modding.DSPModSave" Version="1.*" />
<PackageReference Include="DysonSphereProgram.Modding.NebulaMultiplayerModApi" Version="2.0.0" /> <PackageReference Include="DysonSphereProgram.Modding.NebulaMultiplayerModApi" Version="2.0.0" />
<ProjectReference Include="..\DustbinPreloader\DustbinPreloader.csproj" ReferenceOutputAssembly="false" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Include="assets/icon/signal-410.png" /> <EmbeddedResource Include="assets/icon/signal-410.png" />
</ItemGroup> </ItemGroup>
<!-- Compile against the current game with the same fields injected at runtime. -->
<Target Name="UsePreloaderGameReference" BeforeTargets="CoreCompile" DependsOnTargets="ResolveReferences">
<MSBuild Projects="..\DustbinPreloader\DustbinPreloader.csproj" Targets="GetTargetPath" Properties="Configuration=$(Configuration)">
<Output TaskParameter="TargetOutputs" ItemName="_DustbinPreloaderTarget" />
</MSBuild>
<PropertyGroup>
<_DustbinGameReference>$(MSBuildProjectDirectory)\$(IntermediateOutputPath)game-reference\Assembly-CSharp.dll</_DustbinGameReference>
<_OriginalGameReference>@(ReferencePath->WithMetadataValue('Filename', 'Assembly-CSharp'))</_OriginalGameReference>
</PropertyGroup>
<Exec Command="powershell.exe -NoProfile -ExecutionPolicy Bypass -File &quot;$(MSBuildProjectDirectory)\GenerateGameReference.ps1&quot; -InputAssembly &quot;$(_OriginalGameReference)&quot; -OutputAssembly &quot;$(_DustbinGameReference)&quot; -PreloaderAssembly &quot;@(_DustbinPreloaderTarget)&quot; -CecilAssembly &quot;@(ReferencePath->WithMetadataValue('Filename', 'Mono.Cecil'))&quot; -BepInExAssembly &quot;@(ReferencePath->WithMetadataValue('Filename', 'BepInEx'))&quot; -UnityAssembly &quot;@(ReferencePath->WithMetadataValue('Filename', 'UnityEngine.CoreModule'))&quot;" />
<ItemGroup>
<ReferencePath Remove="$(_OriginalGameReference)" />
<ReferencePath Include="$(_DustbinGameReference)" Private="false" />
<ReferencePathWithRefAssemblies Remove="$(_OriginalGameReference)" />
<ReferencePathWithRefAssemblies Include="$(_DustbinGameReference)" Private="false" />
</ItemGroup>
</Target>
</Project> </Project>
Binary file not shown.
-36
View File
@@ -1,36 +0,0 @@
param(
[Parameter(Mandatory = $true)][string]$InputAssembly,
[Parameter(Mandatory = $true)][string]$OutputAssembly,
[Parameter(Mandatory = $true)][string]$PreloaderAssembly,
[Parameter(Mandatory = $true)][string]$CecilAssembly,
[Parameter(Mandatory = $true)][string]$BepInExAssembly,
[Parameter(Mandatory = $true)][string]$UnityAssembly
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
[void][Reflection.Assembly]::LoadFrom($CecilAssembly)
[void][Reflection.Assembly]::LoadFrom($BepInExAssembly)
$preloader = [Reflection.Assembly]::LoadFrom($PreloaderAssembly)
$resolver = [Mono.Cecil.DefaultAssemblyResolver]::new()
foreach ($assemblyPath in @($InputAssembly, $UnityAssembly, $BepInExAssembly, $CecilAssembly)) {
$resolver.AddSearchDirectory([IO.Path]::GetDirectoryName($assemblyPath))
}
$parameters = [Mono.Cecil.ReaderParameters]::new()
$parameters.AssemblyResolver = $resolver
$reference = [Mono.Cecil.AssemblyDefinition]::ReadAssembly($InputAssembly, $parameters)
try {
$preloader.GetType('DustbinPreloader.Preloader').GetMethod('Patch').Invoke($null, @($reference)) | Out-Null
foreach ($typeName in @('StorageComponent', 'TankComponent')) {
$fields = $reference.MainModule.GetType($typeName).Fields
if (-not ($fields | Where-Object { $_.Name -eq 'IsDustbin' -and $_.FieldType.FullName -eq 'System.Boolean' })) {
throw "Dustbin preloader did not inject $typeName.IsDustbin."
}
}
[void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($OutputAssembly))
$reference.Write($OutputAssembly)
} finally {
$reference.Dispose()
$resolver.Dispose()
}
-2
View File
@@ -9,7 +9,6 @@
* A checkbox is added to Storages and Tanks UI, which turns them into dustbins. * A checkbox is added to Storages and Tanks UI, which turns them into dustbins.
* Items sent into dustbins are removed immediately. * Items sent into dustbins are removed immediately.
* For a belt dustbin, open a belt's signal picker and select the dustbin icon on the first tab. Items passing that belt segment are destroyed, including stacked and proliferated items.
* Can get soil piless from destroyed items, configurable through a json encoded config entry. * Can get soil piless from destroyed items, configurable through a json encoded config entry.
* You can get item ID list from [dsp-wiki](https://dsp-wiki.com/Modding:Items_IDs). * You can get item ID list from [dsp-wiki](https://dsp-wiki.com/Modding:Items_IDs).
@@ -24,7 +23,6 @@
* 在储物仓和储液罐上增加一个垃圾桶的勾选框。 * 在储物仓和储液罐上增加一个垃圾桶的勾选框。
* 送进垃圾桶的物品会立即被移除。 * 送进垃圾桶的物品会立即被移除。
* 使用传送带垃圾桶时,打开传送带的信号选择面板,在第一个页签选择垃圾桶图标。经过该段传送带的物品会被销毁,包括堆叠和喷涂增产剂的物品。
* 可以从移除的物品中获得沙子,可以通过json编码的设置项进行配置。 * 可以从移除的物品中获得沙子,可以通过json编码的设置项进行配置。
* 可以在[这里](https://dsp-wiki.com/Modding:Items_IDs)获得物品ID列表。 * 可以在[这里](https://dsp-wiki.com/Modding:Items_IDs)获得物品ID列表。
+8 -14
View File
@@ -3,6 +3,7 @@ using System.IO;
using System.Reflection.Emit; using System.Reflection.Emit;
using HarmonyLib; using HarmonyLib;
using NebulaAPI; using NebulaAPI;
using UnityEngine;
namespace Dustbin; namespace Dustbin;
@@ -105,7 +106,7 @@ public static class StoragePatch
[HarmonyPatch(typeof(UIStorageWindow), nameof(UIStorageWindow._OnCreate))] [HarmonyPatch(typeof(UIStorageWindow), nameof(UIStorageWindow._OnCreate))]
private static void UIStorageWindow__OnCreate_Postfix(UIStorageWindow __instance) private static void UIStorageWindow__OnCreate_Postfix(UIStorageWindow __instance)
{ {
_storageDustbinCheckBox = UI.MyCheckBox.CreateCheckBox(false, __instance.transform, 220f, 26f, Localization.CurrentLanguageLCID == Localization.LCID_ZHCN ? "垃圾桶" : "Dustbin"); _storageDustbinCheckBox = UI.MyCheckBox.CreateCheckBox(false, __instance.transform, 50f, 50f, Localization.CurrentLanguageLCID == Localization.LCID_ZHCN ? "垃圾桶" : "Dustbin");
var window = __instance; var window = __instance;
_storageDustbinCheckBox.OnChecked += () => _storageDustbinCheckBox.OnChecked += () =>
{ {
@@ -115,7 +116,6 @@ public static class StoragePatch
if (storagePool[storageId].id != storageId) return; if (storagePool[storageId].id != storageId) return;
var enabled = _storageDustbinCheckBox.Checked; var enabled = _storageDustbinCheckBox.Checked;
storagePool[storageId].IsDustbin = enabled; storagePool[storageId].IsDustbin = enabled;
storagePool[storageId].ResetOptimizationFlags();
if (!NebulaModAPI.IsMultiplayerActive) return; if (!NebulaModAPI.IsMultiplayerActive) return;
var planetId = window.factory.planetId; var planetId = window.factory.planetId;
NebulaModAPI.MultiplayerSession.Network.SendPacketToLocalStar(new NebulaSupport.Packet.ToggleEvent(planetId, storageId, enabled)); NebulaModAPI.MultiplayerSession.Network.SendPacketToLocalStar(new NebulaSupport.Packet.ToggleEvent(planetId, storageId, enabled));
@@ -133,6 +133,10 @@ public static class StoragePatch
var storagePool = __instance.factoryStorage.storagePool; var storagePool = __instance.factoryStorage.storagePool;
if (storagePool[storageId].id != storageId) return; if (storagePool[storageId].id != storageId) return;
_storageDustbinCheckBox.Checked = storagePool[storageId].IsDustbin; _storageDustbinCheckBox.Checked = storagePool[storageId].IsDustbin;
if (__instance.transform is RectTransform rectTrans)
{
_storageDustbinCheckBox.rectTrans.anchoredPosition3D = new Vector3(190, 57 - rectTrans.sizeDelta.y, 0);
}
} }
/* Adopt fix from starfi5h's NebulaCompatiblilityAssist */ /* Adopt fix from starfi5h's NebulaCompatiblilityAssist */
@@ -140,8 +144,8 @@ public static class StoragePatch
[HarmonyPatch(typeof(UIStorageGrid), nameof(UIStorageGrid.OnStorageSizeChanged))] [HarmonyPatch(typeof(UIStorageGrid), nameof(UIStorageGrid.OnStorageSizeChanged))]
private static void UIStorageGrid_OnStorageSizeChanged_Postfix() private static void UIStorageGrid_OnStorageSizeChanged_Postfix()
{ {
// Storage data arrives asynchronously on multiplayer clients. // Due to storage window is empty when open in client, the size will change after receiving data from host
_lastStorageId = 0; // Refresh checkbox state on the client _lastStorageId = 0; // Refresh UI to reposition button on client side
} }
@@ -206,16 +210,6 @@ public static class StoragePatch
return matcher.InstructionEnumeration(); return matcher.InstructionEnumeration();
} }
[HarmonyPrefix]
[HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.AddCargo))]
private static bool StorageComponent_AddCargo_Prefix(StorageComponent __instance, ref Cargo cargo, ref bool __result)
{
if (!__instance.IsDustbin) return true;
__result = cargo.item > 0 && cargo.stack > 0;
if (__result) Dustbin.CalcGetSands(cargo.item, cargo.stack, cargo.inc);
return false;
}
/* We keep this to make MOD compatible with older version */ /* We keep this to make MOD compatible with older version */
[HarmonyPostfix] [HarmonyPostfix]
[HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.Import))] [HarmonyPatch(typeof(StorageComponent), nameof(StorageComponent.Import))]
+1 -1
View File
@@ -212,7 +212,7 @@ public static class TankPatch
} }
if (thisTank.fluidCount < thisTank.fluidCapacity || thisTank.IsDustbin) if (thisTank.fluidCount < thisTank.fluidCapacity || thisTank.IsDustbin)
{ {
if (cargoTraffic.GetItemIdAtRear(belt) != thisFluidId) return; if (cargoTraffic.GetItemIdAtRear(belt) != thisFluidId || thisTank.nextTankId <= 0) return;
if (cargoTraffic.TryPickItemAtRear(belt, thisFluidId, null, out stack, out inc) <= 0 || thisTank.IsDustbin) return; if (cargoTraffic.TryPickItemAtRear(belt, thisFluidId, null, out stack, out inc) <= 0 || thisTank.IsDustbin) return;
thisTank.fluidCount += stack; thisTank.fluidCount += stack;
thisTank.fluidInc += inc; thisTank.fluidInc += inc;
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "Dustbin", "name": "Dustbin",
"version_number": "1.5.0", "version_number": "1.4.0",
"website_url": "https://github.com/soarqin/DSP_Mods/tree/master/Dustbin", "website_url": "https://github.com/soarqin/DSP_Mods/tree/master/Dustbin",
"description": "Can turn Storages and Tanks into Dustbin(Destroy incoming items) / 储物仓和储液罐可以转变为垃圾桶(销毁送进的物品)", "description": "Can turn Storages and Tanks into Dustbin(Destroy incoming items) / 储物仓和储液罐可以转变为垃圾桶(销毁送进的物品)",
"dependencies": [ "dependencies": [
+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;
}
}
*/
+1 -1
View File
@@ -140,7 +140,7 @@ python LiveStreamAssist/js/scripts/generate_icons.py --game-root "<DSP install>"
python LiveStreamAssist/js/scripts/pack_js.py python LiveStreamAssist/js/scripts/pack_js.py
``` ```
The generator locates Steam/DSP the same way `UpdateGameDlls.ps1` does when `--game-root` is omitted. It reads BOM-aware `Locale/` files in the header's stable page order and extracts prototype id/name maps from `resources.assets`. DSP 0.10.35's `VehiclePartProtoSet` retains the existing `creationPart` dictionary group. Missing item or tech tables abort generation before overwriting the dictionary. Edit `src/` and repack rather than editing `livestream-assist.js` directly. The generator locates Steam/DSP the same way `UpdateGameDlls.ps1` does when `--game-root` is omitted. It reads BOM-aware `Locale/` files in the header's stable page order and extracts prototype id/name maps from `resources.assets`. Missing item or tech tables abort generation before overwriting the dictionary. Edit `src/` and repack rather than editing `livestream-assist.js` directly.
## Validation ## Validation
+1 -1
View File
@@ -1,2 +1,2 @@
/* Generated from a local Dyson Sphere Program install by generate_icons.py. Do not edit. */ /* Generated from a local Dyson Sphere Program install by generate_icons.py. Do not edit. */
globalThis.LiveStreamAssistIconData = {"version":"1.0.0","icons":{"item":{"1000":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAACfElEQVR42u2cMU4DMRBFvydbBtFAQQRIaXIBjsIV4FScAYmrUEIBoiGKqEAUNJFpDMouibCzXu/MeL7kZuUknuc/49lA1nnvkUOXN88AgLWbgLPurs6zvh/lhCdBuddKNcEbYs1UG7zca3f71kApNW/omki1OS93LFQzvBwxUe3w+sYWXQO11LzcNZFqd17fWMng9YuZGMPzYbCGuLMGjlzzuotyXGsiMXVezDUWTiQB8FhDJMgSO4hNd9KIfZ6HQJGA1GXtQhIGjx1EEgiPFURauwk2hx0qbe3i8wORNAdf9BARDG/UVCbo0GgQG0XB+hL3zN1zgmpxirYaqGaDSGFwXiNAdamrNYWLbxgpdp/XAFBt6mpP4WIbSOY+c+CoG0mVuM+bAytKYV9TKpsDmQHkfvJ6c6C1MQZQeuPszYGWwgbQZADzqBG01hcAKwBvAD4BTAGcADgGcGYAd+sLwD2Ap871jzAeACzCOLAU/qtt8Lp6DMNq4Ja0fYqc+wjg1QC2tUqcvzSAbb0NDFw9wM/E+e+SAQ7xn1HTxPmHpdfJ3YEnifOPLIXbOk6cfyodYO40PgsNcowWAGaly4yERnoRAXGRAJr9rZxD3i8tDwBchHq4DK3KezgwjkLazkbIjkHvhXNDRIA067Geau+FWWtIgI5JjE4qQA4QnWQHjg2xyOc2hYPx2jaMlLmiuNubEVPLSwb3C3Di160LBX8zvBm0lwKty4vLH5W4tDzWSJfU7fUcdHs9NxJ7wgM2np216+ET2p8XmFrzNuG1UticmOa8rTXQIKbB23qIGMR4eK0a2FWtNfG/mhfdxpgT4zhQnxfXDi+qka4VYmzc30cF05B5ubOJAAAAAElFTkSuQmCC","1001":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAn2klEQVR42s2cd7xkR3Xnv1U39+3wcpqcpZFmRgkhFBACgQAvtlcE2eB1ALQmWQbvwmIZbBawRXCQMbBgmbVhMRgjwHitXYwRimAEQgjl0eTRzLzYr3PfWFX7R7/3Jo9GiaX6U5+6p+umOvfU75w6darEpW/+LIvJGIMQ4mdCG2PAmF6FEIePgejQPQDU5mu9asdj07nnAuBX+nDCkKTbXTq/b2wIgKybUin5HJm2f+/HPJN06//68CnrxaVv+szhBvwMyyUGnuSc1r7vA9BqNZcY6BdLYFkAaCHwS8UeU0OfTifFXfhWU7v2HNXIvlLhGTHxax9/50nrJIsS8rMtHWAYEEuSd0zZajVptZpHvWzcbgHghGGPbrUZnhgEIAxdAColn03nnMnQ6uGlbA+GPHbP3dSn5pbyY/fczei6VUv5sXvuxh4MT5iv+chNTyKBP/tkGWM8oHuiykXpe7oSeLKUGp70nFOlv3/3rx73n/3/o/tijDqKeQt19b134wUFbMc6CgOPlMAjMTButZcYGIbuCTHw2FRtdBishE+LgW/7zDf49Fv+4zEMPKLrGGMQhxH/uaWPYV40fR9e0MOqJE2xhEWpVD6qG/vFUk9ZdDpwhAQCSxLYaMXHYeCxqXzGWnY/tvtpMfElb3mUWz9z/eHXN8aw7ZW/8ZRuUp64uKcEFhovhHjKkmiO0LqqtZ1WdRYALyhQm5058nGOcLyXbjr33HuA6rFaeMWmVbQaneO0cLU+d8o2tKbmKY0NPO3u/JX3Xttj4NZX/PrTukFp/AXHCNLJweVYc2bJjFlgHkCnXsNxe4ogj+PF0144V2/99fi69ZvWnrGhmafZ57Gsm4AHTwsDs+4p2zC1+wBja5c/fUy8/k1Pn4EAaTdFON4SPbjqBVT3/ftx5Ynq53bdiRQ9JpaHRo+SQFQG8MczM/Xrxy+4mNXrV6DSDJ0n+L6H1vxt0u1eB7SfqR2oNFjy6SuWZ8bAKD8sUSpHWPbJpfAE9Ubl9I9NLHyMzuLf5ydR56bJPfvP3fiKV7HtF66iMzeHTiOSbkY59CgGDkkUTzWqzU8Cf/xM7cB6dZ6+wYGfPQMXmWi0RrreSc/RaXJcvcmzE0nge7M0vaFdb7B229m89S/+iEOdmEd3HyTA4ANSa7qdCNtAwbFo1Zo/bTU61wF3ngoDg9IAUWv+pO/4dOvtZ2rQ9Q2P0O1Ex3Tt1lH19dkZTJ4dRS8ybiFtkpb9N1G7eWkcp/h+wK//zm+xYbjMfLXG5ol+ZK7ZPTVPYElGhiokUYI0Br9c3FZtxndk7eifXcFbG634EIBtFY+Bw/S4/56N+mfEwDzOaGSHbTWhUozlImxniW7UaiekTZ7RnJsGeKtW5pMqz6Xjehw8NMO1v/krbNx6Ft/8yeOsKPj0OQ5eYDE7U6fR6XLmspWgDJPVGlmeExQckm7nF3NlXjhYCa8GbvtZjQieEQO1EbAgWQCGp0RLlat/MIbXgkHaFp12l+UTY1z2yis5UK9DrmgkKXGWkyQpw30FtMp5dNchBkoFcpUzX2tSKfqkTcmKFeN9s/umvrv7sd2XA3f+3DPQDWyy7GmNjVboNLkFY7YIIUEIhBDMzFZ52zt+i60XnMFX73uUscCj7HtEeU6eCertLrYUzEcxxmj6Cj5DlTJZHCNtiySKGF8+xMG9++4ojQ28CviX55qBEhE8Ax0e4Lj+cdko9WT5vwujtxggiiOMNiilCUtFznneOXQNKKUwuabkOiwrhoS2jTCglaZS9ukvBfSFBTYsG0FIAdqwa8cT2J7DBc/fytzOQ//b1vJ5tpY8p3nRnnML7lPXwJ0Gblg5riz2j/Ss/erUyS71jNZYjsPYYB/tVodatcGaNasoTYwxPdfgrJFBnqi36GYZY8UQpTRDpZA09Dg4V2O+0cYTkk6ry55dkzRmqvihQxTFjAz1k2c5Bx/e831Lcj7wwHPahZca/xSZ6IYVjrp+gVZZjuXYjC5fBsD0/v3HXjqXK0WhVORFV72YW2/5DnvqT3DZlS9kxdoJDh6axUIQODZRmjHfjfBtm/lGm7luB8+xidME1xI8OjnN3OQs7fkG64ZWEkcJD+55jE67iy21HZZK/9Y3OLAcyJ4zBi423vVD0mju9K82EYgA1+95N1w/JI07WE4PWrvtNoViEa11Dy8sG6NzgOVpnNI30I/jOjQbTRCC8y7YwlpbULctfjo7z0SlhBSCuVYHR0jiNKXVjujrL7B2bJA8SZCWoeBKYlsihaA2V+PAvoN4novtWMxPPjEytfORNwKffU4YeKTkpHHnqSuSBaYdef2iBBaKxSXGLTpUhON+UKj86narxZoNa/ACn6lDMwyNDXPets2EgBECCdTaHSrFkKLjIBEEBZ9VgUOcZRRsm3t37CePEpIoISj6CGGo1VpoBF7o43oetYMp81MHr3nOGHhU9zPRUx4LIzrHYeBxEqhygGts1/lYmiQrw4JPqVxi/ZkbqM5Ukbbk+Zc9n4GRIepAVykmKiUa3S7TzRYrikXmOhHaEszOt1k31I+UEiMFaZxQr7eo9JdQuSZNMtzABVdiYeMXyzh+sOy508KLWPYUmXcsBlqWdxQGAosSeLWQ8qee5/wDWq/0fY9ut8uGszZxyUteyI5HtmOUZu261ZjQZ2ezS5wpNgwNkGvFVK2BQJCpnN0Hp+h0uqwd6GewUuLM1eNoo1FZhi0FnmOjlCKNY6Jml6jVQdoOtuOMOK4XOq7Hs53lEpY9nbRwneuHKJUsYeGCBF7Wbbdvm9q/72uuJbcKIF1gbKvZ4ZwLz0UIwa7tO4m6EVmWMehb1DoRA76HMppqlLB6sEIpcDkwX0MYeMWWM8mMBgHjQwMkcYotBatWjhF3E5IoQiu15DKTlo2QVh+w7rlRIk+XeQt24JHYt1AOqiz/VNypX5N0WtiWBNdHOC6hbRO1OzhSce9dd7P9gYeIMkNhdBnFgQHGgGoQ4NsWDx6YZLxUYtPwAPVuRJIkrBnsY/XIEI9OzTAcuuQaBgoF9lrQaUXs2b4brVNGRkbISEjjHMt2kLaNSlPxnGnhp+2J6TRO9PdrMVxjjMZ2bBwvICj34VnQmGuSxR0c12Hfzt0kSYo7up6xTes5c8smFLC8WGC2G+O5LisHQubbXTppyoaREVYP9XGo0WSwGOIKyUDoEAhBuxMzPTVHt1mnf7Afx5LEqcYYhe16uF5AJ+oOPGcY+LSHcgUXrdSx+SpjFEqDtF36B0r4Imd26iDNThfheBhpI6RHODBOmuasXt7P2etWkAPagC0lA4UA37ZJlKYVJWwYG6avXGK60SRKEoq+SznwmJmdx7Isup0WQRDQ399HluYI2ZsxtWwHNwgxWr/caM2znZ+OBIol3wDglwKSTnJk/RW5MgS+x9BAiTTLmKs2SBRYfhkpDWG5jPTLRHGGaXRwgoBumhD5NkjwLIuiY1PrdLEFrB3qx7YsumlOkuZMJw3OXjnOt+/6MQ8+vBMHRRZrxleMY0sLlSlyleM4Ln4hoFDppzF98JeB//Zz1YWP0CaLB2dqIyph0GNeN1XMznfRwsEvlXBsm7BSJuzrB9fDTzXab/Lw4zPcfOuPeeULt1F2HCwEnuVgi5TRSonAstg7N89Uo0Wc5ly8aQ2Hpqt857YfkkUxRmrGV07guQ5ZkpFnOXGUMDRSpjk3xdzBfRRHxu/4ecFAcyQRteMjybe7jk1Y8Km2EhrdFNtxqRRDgjDACQqUCj65tMgcjyDwGPJCJvcf4p/+6S5GxwbYsnEFw47LcOijjabWjYlMSidNGSoXGSoEFFyH7YdmSKOYPIsZHB+hUi6SRgnSCJI0x7Ftup2UyX17STsthlau+8zPnRKJuylCyqMxVVrMt1OS3FAsFiiVQiz Line truncated globalThis.LiveStreamAssistIconData = {"version":"1.0.0","icons":{"item":{"1000":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAACfElEQVR42u2cMU4DMRBFvydbBtFAQQRIaXIBjsIV4FScAYmrUEIBoiGKqEAUNJFpDMouibCzXu/MeL7kZuUknuc/49lA1nnvkUOXN88AgLWbgLPurs6zvh/lhCdBuddKNcEbYs1UG7zca3f71kApNW/omki1OS93LFQzvBwxUe3w+sYWXQO11LzcNZFqd17fWMng9YuZGMPzYbCGuLMGjlzzuotyXGsiMXVezDUWTiQB8FhDJMgSO4hNd9KIfZ6HQJGA1GXtQhIGjx1EEgiPFURauwk2hx0qbe3i8wORNAdf9BARDG/UVCbo0GgQG0XB+hL3zN1zgmpxirYaqGaDSGFwXiNAdamrNYWLbxgpdp/XAFBt6mpP4WIbSOY+c+CoG0mVuM+bAytKYV9TKpsDmQHkfvJ6c6C1MQZQeuPszYGWwgbQZADzqBG01hcAKwBvAD4BTAGcADgGcGYAd+sLwD2Ap871jzAeACzCOLAU/qtt8Lp6DMNq4Ja0fYqc+wjg1QC2tUqcvzSAbb0NDFw9wM/E+e+SAQ7xn1HTxPmHpdfJ3YEnifOPLIXbOk6cfyodYO40PgsNcowWAGaly4yERnoRAXGRAJr9rZxD3i8tDwBchHq4DK3KezgwjkLazkbIjkHvhXNDRIA067Geau+FWWtIgI5JjE4qQA4QnWQHjg2xyOc2hYPx2jaMlLmiuNubEVPLSwb3C3Di160LBX8zvBm0lwKty4vLH5W4tDzWSJfU7fUcdHs9NxJ7wgM2np216+ET2p8XmFrzNuG1UticmOa8rTXQIKbB23qIGMR4eK0a2FWtNfG/mhfdxpgT4zhQnxfXDi+qka4VYmzc30cF05B5ubOJAAAAAElFTkSuQmCC","1001":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQCAYAAACOEfKtAAAn2klEQVR42s2cd7xkR3Xnv1U39+3wcpqcpZFmRgkhFBACgQAvtlcE2eB1ALQmWQbvwmIZbBawRXCQMbBgmbVhMRgjwHitXYwRimAEQgjl0eTRzLzYr3PfWFX7R7/3Jo9GiaX6U5+6p+umOvfU75w6darEpW/+LIvJGIMQ4mdCG2PAmF6FEIePgejQPQDU5mu9asdj07nnAuBX+nDCkKTbXTq/b2wIgKybUin5HJm2f+/HPJN06//68CnrxaVv+szhBvwMyyUGnuSc1r7vA9BqNZcY6BdLYFkAaCHwS8UeU0OfTifFXfhWU7v2HNXIvlLhGTHxax9/50nrJIsS8rMtHWAYEEuSd0zZajVptZpHvWzcbgHghGGPbrUZnhgEIAxdAColn03nnMnQ6uGlbA+GPHbP3dSn5pbyY/fczei6VUv5sXvuxh4MT5iv+chNTyKBP/tkGWM8oHuiykXpe7oSeLKUGp70nFOlv3/3rx73n/3/o/tijDqKeQt19b134wUFbMc6CgOPlMAjMTButZcYGIbuCTHw2FRtdBishE+LgW/7zDf49Fv+4zEMPKLrGGMQhxH/uaWPYV40fR9e0MOqJE2xhEWpVD6qG/vFUk9ZdDpwhAQCSxLYaMXHYeCxqXzGWnY/tvtpMfElb3mUWz9z/eHXN8aw7ZW/8ZRuUp64uKcEFhovhHjKkmiO0LqqtZ1WdRYALyhQm5058nGOcLyXbjr33HuA6rFaeMWmVbQaneO0cLU+d8o2tKbmKY0NPO3u/JX3Xttj4NZX/PrTukFp/AXHCNLJweVYc2bJjFlgHkCnXsNxe4ogj+PF0144V2/99fi69ZvWnrGhmafZ57Gsm4AHTwsDs+4p2zC1+wBja5c/fUy8/k1Pn4EAaTdFON4SPbjqBVT3/ftx5Ynq53bdiRQ9JpaHRo+SQFQG8MczM/Xrxy+4mNXrV6DSDJ0n+L6H1vxt0u1eB7SfqR2oNFjy6SuWZ8bAKD8sUSpHWPbJpfAE9Ubl9I9NLHyMzuLf5ydR56bJPfvP3fiKV7HtF66iMzeHTiOSbkY59CgGDkkUTzWqzU8Cf/xM7cB6dZ6+wYGfPQMXmWi0RrreSc/RaXJcvcmzE0nge7M0vaFdb7B229m89S/+iEOdmEd3HyTA4ANSa7qdCNtAwbFo1Zo/bTU61wF3ngoDg9IAUWv+pO/4dOvtZ2rQ9Q2P0O1Ex3Tt1lH19dkZTJ4dRS8ybiFtkpb9N1G7eWkcp/h+wK//zm+xYbjMfLXG5ol+ZK7ZPTVPYElGhiokUYI0Br9c3FZtxndk7eifXcFbG634EIBtFY+Bw/S4/56N+mfEwDzOaGSHbTWhUozlImxniW7UaiekTZ7RnJsGeKtW5pMqz6Xjehw8NMO1v/krbNx6Ft/8yeOsKPj0OQ5eYDE7U6fR6XLmspWgDJPVGlmeExQckm7nF3NlXjhYCa8GbvtZjQieEQO1EbAgWQCGp0RLlat/MIbXgkHaFp12l+UTY1z2yis5UK9DrmgkKXGWkyQpw30FtMp5dNchBkoFcpUzX2tSKfqkTcmKFeN9s/umvrv7sd2XA3f+3DPQDWyy7GmNjVboNLkFY7YIIUEIhBDMzFZ52zt+i60XnMFX73uUscCj7HtEeU6eCertLrYUzEcxxmj6Cj5DlTJZHCNtiySKGF8+xMG9++4ojQ28CviX55qBEhE8Ax0e4Lj+cdko9WT5vwujtxggiiOMNiilCUtFznneOXQNKKUwuabkOiwrhoS2jTCglaZS9ukvBfSFBTYsG0FIAdqwa8cT2J7DBc/fytzOQ//b1vJ5tpY8p3nRnnML7lPXwJ0Gblg5riz2j/Ss/erUyS71jNZYjsPYYB/tVodatcGaNasoTYwxPdfgrJFBnqi36GYZY8UQpTRDpZA09Dg4V2O+0cYTkk6ry55dkzRmqvihQxTFjAz1k2c5Bx/e831Lcj7wwHPahZca/xSZ6IYVjrp+gVZZjuXYjC5fBsD0/v3HXjqXK0WhVORFV72YW2/5DnvqT3DZlS9kxdoJDh6axUIQODZRmjHfjfBtm/lGm7luB8+xidME1xI8OjnN3OQs7fkG64ZWEkcJD+55jE67iy21HZZK/9Y3OLAcyJ4zBi423vVD0mju9K82EYgA1+95N1w/JI07WE4PWrvtNoViEa11Dy8sG6NzgOVpnNI30I/jOjQbTRCC8y7YwlpbULctfjo7z0SlhBSCuVYHR0jiNKXVjujrL7B2bJA8SZCWoeBKYlsihaA2V+PAvoN4novtWMxPPjEytfORNwKffU4YeKTkpHHnqSuSBaYdef2iBBaKxSXGLTpUhON+UKj86narxZoNa/ACn6lDMwyNDXPets2EgBECCdTaHSrFkKLjIBEEBZ9VgUOcZRRsm3t37CePEpIoISj6CGGo1VpoBF7o43oetYMp81MHr3nOGHhU9zPRUx4LIzrHYeBxEqhygGts1/lYmiQrw4JPqVxi/ZkbqM5Ukbbk+Zc9n4GRIepAVykmKiUa3S7TzRYrikXmOhHaEszOt1k31I+UEiMFaZxQr7eo9JdQuSZNMtzABVdiYeMXyzh+sOy508KLWPYUmXcsBlqWdxQGAosSeLWQ8qee5/wDWq/0fY9ut8uGszZxyUteyI5HtmOUZu261ZjQZ2ezS5wpNgwNkGvFVK2BQJCpnN0Hp+h0uqwd6GewUuLM1eNoo1FZhi0FnmOjlCKNY6Jml6jVQdoOtuOMOK4XOq7Hs53lEpY9nbRwneuHKJUsYeGCBF7Wbbdvm9q/72uuJbcKIF1gbKvZ4ZwLz0UIwa7tO4m6EVmWMehb1DoRA76HMppqlLB6sEIpcDkwX0MYeMWWM8mMBgHjQwMkcYotBatWjhF3E5IoQiu15DKTlo2QVh+w7rlRIk+XeQt24JHYt1AOqiz/VNypX5N0WtiWBNdHOC6hbRO1OzhSce9dd7P9gYeIMkNhdBnFgQHGgGoQ4NsWDx6YZLxUYtPwAPVuRJIkrBnsY/XIEI9OzTAcuuQaBgoF9lrQaUXs2b4brVNGRkbISEjjHMt2kLaNSlPxnGnhp+2J6TRO9PdrMVxjjMZ2bBwvICj34VnQmGuSxR0c12Hfzt0kSYo7up6xTes5c8smFLC8WGC2G+O5LisHQubbXTppyoaREVYP9XGo0WSwGOIKyUDoEAhBuxMzPTVHt1mnf7Afx5LEqcYYhe16uF5AJ+oOPGcY+LSHcgUXrdSx+SpjFEqDtF36B0r4Imd26iDNThfheBhpI6RHODBOmuasXt7P2etWkAPagC0lA4UA37ZJlKYVJWwYG6avXGK60SRKEoq+SznwmJmdx7Isup0WQRDQ399HluYI2ZsxtWwHNwgxWr/caM2znZ+OBIol3wDglwKSTnJk/RW5MgS+x9BAiTTLmKs2SBRYfhkpDWG5jPTLRHGGaXRwgoBumhD5NkjwLIuiY1PrdLEFrB3qx7YsumlOkuZMJw3OXjnOt+/6MQ8+vBMHRRZrxleMY0sLlSlyleM4Ln4hoFDppzF98JeB//Zz1YWP0CaLB2dqIyph0GNeN1XMznfRwsEvlXBsm7BSJuzrB9fDTzXab/Lw4zPcfOuPeeULt1F2HCwEnuVgi5TRSonAstg7N89Uo0Wc5ly8aQ2Hpqt857YfkkUxRmrGV07guQ5ZkpFnOXGUMDRSpjk3xdzBfRRHxu/4ecFAcyQRteMjybe7jk1Y8Km2EhrdFNtxqRRDgjDACQqUCj65tMgcjyDwGPJCJvcf4p/+6S5GxwbYsnEFw47LcOijjabWjYlMSidNGSoXGSoEFFyH7YdmSKOYPIsZHB+hUi6SRgnSCJI0x7Ftup2UyX17STsthlau+8zPnRKJuylCyqMxVVrMt1OS3FAsFiiVQiz Line truncated
+1 -1
View File
@@ -1,2 +1,2 @@
/* Generated from a local Dyson Sphere Program install by generate_text.py. Do not edit. */ /* Generated from a local Dyson Sphere Program install by generate_text.py. Do not edit. */
globalThis.LiveStreamAssistTextData = {"version":"1.0.0","languages":{"2052":{"lcid":2052,"name":"简体中文","abbr":"zh-CN","abbr2":"zh","fallback":1033},"1033":{"lcid":1033,"name":"English","abbr":"en-US","abbr2":"en","fallback":2052},"1036":{"lcid":1036,"name":"Français","abbr":"fr-FR","abbr2":"fr","fallback":1033},"1031":{"lcid":1031,"name":"Deutsch","abbr":"de-DE","abbr2":"de","fallback":1033},"1041":{"lcid":1041,"name":"日本語","abbr":"ja-JA","abbr2":"ja","fallback":1033}},"ids":{"item":{"1001":"铁矿","1002":"铜矿","1003":"硅石","1004":"钛石","1005":"石矿","1006":"煤矿","1030":"木材","1031":"植物燃料","1011":"可燃冰","1012":"金伯利矿石","1013":"分形硅石","1014":"光栅石","1015":"刺笋结晶","1016":"单极磁石","1101":"铁块","1104":"铜块","1105":"高纯硅块","1106":"钛块","1108":"石材","1109":"高能石墨","1103":"钢材","1107":"钛合金","1110":"玻璃","1119":"钛化玻璃","1111":"棱镜","1112":"金刚石","1113":"晶格硅","1201":"齿轮","1102":"磁铁","1202":"磁线圈","1203":"电动机","1204":"电磁涡轮","1205":"超级磁场环","1206":"粒子容器","1127":"奇异物质","1301":"电路板","1303":"处理器","1305":"量子芯片","1302":"微晶元件","1304":"位面过滤器","1402":"粒子宽带","1401":"电浆激发器","1404":"光子合并器","1501":"太阳帆","1000":"水","1007":"原油","1114":"精炼油","1116":"硫酸","1120":"氢","1121":"重氢","1122":"反物质","1208":"临界光子","1801":"氢燃料棒","1802":"氘核燃料棒","1803":"反物质燃料棒","1804":"金色燃料棒","1115":"塑料","1123":"石墨烯","1124":"碳纳米管","1117":"有机晶体","1118":"钛晶石","1126":"卡西米尔晶体","1128":"燃烧单元","1129":"爆破单元","1130":"晶石爆破单元","1209":"引力透镜","1210":"空间翘曲器","1211":"黑雾引力透镜","1403":"湮灭约束球","1407":"动力引擎","1405":"推进器2","1406":"加力推进器","5003":"配送运输机","5001":"物流运输机","5002":"星际物流运输船","1125":"框架材料","1502":"戴森球组件","1503":"小型运载火箭","1131":"地基","1141":"增产剂 Mk.I","1142":"增产剂 Mk.II","1143":"增产剂 Mk.III","1601":"机枪弹箱","1602":"钛化弹箱","1603":"超合金弹箱","1604":"炮弹组","1605":"高爆炮弹组","1606":"晶石炮弹组","1607":"等离子胶囊","1608":"反物质胶囊","1609":"导弹组","1610":"超音速导弹组","1611":"引力导弹组","1612":"电磁干扰胶囊","1613":"电磁压制胶囊","5101":"地面战斗机-E型","5102":"地面战斗机-A型","5103":"地面战斗机-F型","5111":"太空战斗机-A型","5112":"太空战斗机-F型","5201":"存储单元","5202":"硅基神经元","5203":"物质重组器","5204":"负熵奇点","5205":"虚粒子","5206":"能量碎片","2001":"低速传送带","2002":"高速传送带","2003":"极速传送带","2011":"低速分拣器","2012":"高速分拣器","2013":"极速分拣器","2014":"集装分拣器","2020":"四向分流器","2040":"自动集装机","2030":"流速器","2313":"喷涂机","2107":"物流配送器","2101":"小型储物仓","2102":"大型储物仓","2106":"储液罐","2303":"制造台 Mk.I","2304":"制造台 Mk.II","2305":"制造台 Mk.III","2318":"制造台 Mk.IV","2201":"电力感应塔","2202":"无线输电塔","2212":"卫星配电站","2401":"激光灯塔","2203":"风力涡轮机","2204":"火力发电厂","2211":"微型聚变发电站","2213":"地热发电站","2301":"采矿机","2316":"大型采矿机","2306":"抽水站","2302":"电弧熔炉","2315":"位面熔炉","2319":"熔炉 Mk.III","2307":"原油萃取站","2308":"原油精炼厂","2309":"化工厂","2317":"化工厂 Mk.II","2314":"分馏塔","2205":"太阳能板","2206":"蓄电器","2207":"蓄电器(满)","2311":"电磁轨道弹射器","2208":"射线接收站","2312":"垂直发射井","2209":"能量枢纽","2310":"微型粒子对撞机","2210":"人造恒星","2103":"物流运输站","2104":"星际物流运输站","2105":"轨道采集器","2901":"矩阵研究站","2902":"矩阵研究站 Mk.II","3001":"高斯机枪塔","3002":"高频激光塔","3003":"聚爆加农炮","3004":"磁化电浆炮","3005":"导弹防御塔","3006":"干扰塔","3007":"信标","3008":"护盾发生器","3009":"战场分析基站","3010":"地面电浆炮","6001":"电磁矩阵","6002":"能量矩阵","6003":"结构矩阵","6004":"信息矩阵","6005":"引力矩阵","6006":"宇宙矩阵","1099":"沙土"},"tech":{"1":"T戴森球计划","1001":"T电磁学","1002":"T电磁矩阵","1101":"T高效电浆控制","1102":"T等离子萃取精炼","1103":"TX射线裂解","1104":"T重整精炼","1105":"T电弧激光","1111":"T能量矩阵","1112":"T氢燃料棒","1113":"T推进器","1114":"T加力推进器","1120":"T流体储存封装","1121":"T基础化工","1122":"T高分子化工","1123":"T高强度晶体","1124":"T结构矩阵","1125":"T卡西米尔晶体","1126":"T高强度玻璃","1131":"T应用型超导体","1132":"T高强度材料","113Line truncated globalThis.LiveStreamAssistTextData = {"version":"1.0.0","languages":{"2052":{"lcid":2052,"name":"简体中文","abbr":"zh-CN","abbr2":"zh","fallback":1033},"1033":{"lcid":1033,"name":"English","abbr":"en-US","abbr2":"en","fallback":2052},"1036":{"lcid":1036,"name":"Français","abbr":"fr-FR","abbr2":"fr","fallback":1033},"1031":{"lcid":1031,"name":"Deutsch","abbr":"de-DE","abbr2":"de","fallback":1033},"1041":{"lcid":1041,"name":"日本語","abbr":"ja-JA","abbr2":"ja","fallback":1033}},"ids":{"item":{"1001":"铁矿","1002":"铜矿","1003":"硅石","1004":"钛石","1005":"石矿","1006":"煤矿","1030":"木材","1031":"植物燃料","1011":"可燃冰","1012":"金伯利矿石","1013":"分形硅石","1014":"光栅石","1015":"刺笋结晶","1016":"单极磁石","1101":"铁块","1104":"铜块","1105":"高纯硅块","1106":"钛块","1108":"石材","1109":"高能石墨","1103":"钢材","1107":"钛合金","1110":"玻璃","1119":"钛化玻璃","1111":"棱镜","1112":"金刚石","1113":"晶格硅","1201":"齿轮","1102":"磁铁","1202":"磁线圈","1203":"电动机","1204":"电磁涡轮","1205":"超级磁场环","1206":"粒子容器","1127":"奇异物质","1301":"电路板","1303":"处理器","1305":"量子芯片","1302":"微晶元件","1304":"位面过滤器","1402":"粒子宽带","1401":"电浆激发器","1404":"光子合并器","1501":"太阳帆","1000":"水","1007":"原油","1114":"精炼油","1116":"硫酸","1120":"氢","1121":"重氢","1122":"反物质","1208":"临界光子","1801":"氢燃料棒","1802":"氘核燃料棒","1803":"反物质燃料棒","1804":"金色燃料棒","1115":"塑料","1123":"石墨烯","1124":"碳纳米管","1117":"有机晶体","1118":"钛晶石","1126":"卡西米尔晶体","1128":"燃烧单元","1129":"爆破单元","1130":"晶石爆破单元","1209":"引力透镜","1210":"空间翘曲器","1403":"湮灭约束球","1407":"动力引擎","1405":"推进器2","1406":"加力推进器","5003":"配送运输机","5001":"物流运输机","5002":"星际物流运输船","1125":"框架材料","1502":"戴森球组件","1503":"小型运载火箭","1131":"地基","1141":"增产剂 Mk.I","1142":"增产剂 Mk.II","1143":"增产剂 Mk.III","1601":"机枪弹箱","1602":"钛化弹箱","1603":"超合金弹箱","1604":"炮弹组","1605":"高爆炮弹组","1606":"晶石炮弹组","1607":"等离子胶囊","1608":"反物质胶囊","1609":"导弹组","1610":"超音速导弹组","1611":"引力导弹组","1612":"电磁干扰胶囊","1613":"电磁压制胶囊","5101":"地面战斗机-E型","5102":"地面战斗机-A型","5103":"地面战斗机-F型","5111":"太空战斗机-A型","5112":"太空战斗机-F型","5201":"存储单元","5202":"硅基神经元","5203":"物质重组器","5204":"负熵奇点","5205":"虚粒子","5206":"能量碎片","2001":"低速传送带","2002":"高速传送带","2003":"极速传送带","2011":"低速分拣器","2012":"高速分拣器","2013":"极速分拣器","2014":"集装分拣器","2020":"四向分流器","2040":"自动集装机","2030":"流速器","2313":"喷涂机","2107":"物流配送器","2101":"小型储物仓","2102":"大型储物仓","2106":"储液罐","2303":"制造台 Mk.I","2304":"制造台 Mk.II","2305":"制造台 Mk.III","2318":"制造台 Mk.IV","2201":"电力感应塔","2202":"无线输电塔","2212":"卫星配电站","2401":"激光灯塔","2203":"风力涡轮机","2204":"火力发电厂","2211":"微型聚变发电站","2213":"地热发电站","2301":"采矿机","2316":"大型采矿机","2306":"抽水站","2302":"电弧熔炉","2315":"位面熔炉","2319":"熔炉 Mk.III","2307":"原油萃取站","2308":"原油精炼厂","2309":"化工厂","2317":"化工厂 Mk.II","2314":"分馏塔","2205":"太阳能板","2206":"蓄电器","2207":"蓄电器(满)","2311":"电磁轨道弹射器","2208":"射线接收站","2312":"垂直发射井","2209":"能量枢纽","2310":"微型粒子对撞机","2210":"人造恒星","2103":"物流运输站","2104":"星际物流运输站","2105":"轨道采集器","2901":"矩阵研究站","2902":"矩阵研究站 Mk.II","3001":"高斯机枪塔","3002":"高频激光塔","3003":"聚爆加农炮","3004":"磁化电浆炮","3005":"导弹防御塔","3006":"干扰塔","3007":"信标","3008":"护盾发生器","3009":"战场分析基站","3010":"地面电浆炮","6001":"电磁矩阵","6002":"能量矩阵","6003":"结构矩阵","6004":"信息矩阵","6005":"引力矩阵","6006":"宇宙矩阵","1099":"沙土"},"tech":{"1":"T戴森球计划","1001":"T电磁学","1002":"T电磁矩阵","1101":"T高效电浆控制","1102":"T等离子萃取精炼","1103":"TX射线裂解","1104":"T重整精炼","1105":"T电弧激光","1111":"T能量矩阵","1112":"T氢燃料棒","1113":"T推进器","1114":"T加力推进器","1120":"T流体储存封装","1121":"T基础化工","1122":"T高分子化工","1123":"T高强度晶体","1124":"T结构矩阵","1125":"T卡西米尔晶体","1126":"T高强度玻璃","1131":"T应用型超导体","1132":"T高强度材料","1133":"T粒子可控技术","11Line truncated
+1 -1
View File
@@ -34,7 +34,7 @@ KIND_FROM_SET = {
"DoodadProtoSet": "doodad", "DoodadProtoSet": "doodad",
"AbnormalityProtoSet": "abnormality", "AbnormalityProtoSet": "abnormality",
"FleetProtoSet": "fleet", "FleetProtoSet": "fleet",
"VehiclePartProtoSet": "creationPart", "CreationPartProtoSet": "creationPart",
"EffectEmitterProtoSet": "effectEmitter", "EffectEmitterProtoSet": "effectEmitter",
"MIDIProtoSet": "midi", "MIDIProtoSet": "midi",
"PlayerProtoSet": "player", "PlayerProtoSet": "player",
+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));
} }
@@ -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;
}
*/
} }
+108 -69
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;
}
} }
-424
View File
@@ -1,424 +0,0 @@
#requires -Version 5.1
<#
.SYNOPSIS
Builds and publishes one mod to the Dyson Sphere Program Thunderstore community.
Resolves its Team from the service-account token before publishing.
.PARAMETER EnvFile
Optional token file. Defaults to .env in the caller's current directory when present,
otherwise TCLI_AUTH_TOKEN is read from the process environment.
.EXAMPLE
.\Publish-Mod.ps1 -Project UXAssist -DryRun
.EXAMPLE
.\Publish-Mod.ps1 -Project Dustbin -EnvFile C:\Secrets\thunderstore.env
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidatePattern('^[A-Za-z0-9_][A-Za-z0-9_.-]*\z')]
[string]$Project,
[string]$EnvFile,
[switch]$DryRun
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
function Invoke-PublishDotNet {
param([string[]]$Arguments, [switch]$Capture, [string]$Secret, [int[]]$SuccessExitCodes = @(0))
$previousOutputEncoding = [Console]::OutputEncoding
try {
# Localized .NET SDK output is UTF-8. PowerShell decodes native output
# with Console.OutputEncoding, which can still be a legacy code page.
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
# Windows PowerShell turns native stderr into error records. Check the exit
# code ourselves and redact credentials before forwarding any tcli output.
$ErrorActionPreference = 'Continue'
$lines = New-Object 'System.Collections.Generic.List[string]'
& dotnet @Arguments 2>&1 | ForEach-Object {
$line = $_.ToString()
if (-not [string]::IsNullOrEmpty($Secret)) { $line = $line.Replace($Secret, '[REDACTED]') }
if ($Capture) { $lines.Add($line) } else { Write-Host $line }
}
$commandExit = $LASTEXITCODE
if ($commandExit -notin $SuccessExitCodes) {
if ($Capture) { foreach ($line in $lines) { Write-Host $line } }
throw "dotnet $($Arguments[0]) failed (exit $commandExit). No further publishing steps were run."
}
if ($Capture) { return ($lines -join [Environment]::NewLine) }
} finally { [Console]::OutputEncoding = $previousOutputEncoding }
}
function Assert-PublishTcli {
try {
# tcli 0.2.4 returns 1 for --version because its parser treats it as an
# unparsed command. Accept it only here, with a recognizable version.
$versionOutput = Invoke-PublishDotNet -Capture -Arguments @('tool', 'run', 'tcli', '--', '--version') -SuccessExitCodes @(0, 1)
if ($versionOutput -notmatch '(?m)^tcli [0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?\s*$') {
throw 'The version check did not return a recognizable tcli version.'
}
Write-Host $versionOutput
} catch {
throw "Cannot verify the pinned tcli tool. Run dotnet tool restore in the repository root, then dotnet tool run tcli -- --version to inspect startup diagnostics. $($_.Exception.Message)"
}
}
function Get-PublishJsonProperty {
param($Object, [string]$Name)
if ($null -ne $Object) {
$property = $Object.PSObject.Properties[$Name]
if ($null -ne $property) { return $property.Value }
}
return $null
}
function Read-PublishJson {
param([string]$Path)
try { return ([IO.File]::ReadAllText($Path) | ConvertFrom-Json -ErrorAction Stop) }
catch { throw "Cannot read JSON from '$Path'. Check that it is a valid JSON object." }
}
function Get-PublishProject {
param([string]$Path)
$query = Invoke-PublishDotNet -Capture -Arguments @(
'msbuild', $Path, '-nologo', '-verbosity:quiet', '-property:Configuration=Release',
'-getProperty:Version,ProjectName,TargetPath,PackHasChangelog,PackUsePluginsLayout,PackPreloaderTargetDir,ProjectAssetsFile',
'-getItem:ProjectReference'
)
try { $result = $query | ConvertFrom-Json -ErrorAction Stop }
catch { throw "Cannot evaluate '$Path'. MSBuild 17.8 or newer is required; check 'dotnet msbuild -version'." }
if ($null -eq (Get-PublishJsonProperty $result 'Properties')) { throw "MSBuild returned no properties for '$Path'." }
return $result
}
function Test-PublishPathWithin {
param([string]$Path, [string]$Directory)
$fullPath = [IO.Path]::GetFullPath($Path).TrimEnd('\', '/')
$fullDirectory = [IO.Path]::GetFullPath($Directory).TrimEnd('\', '/')
return ($fullPath.Equals($fullDirectory, [StringComparison]::OrdinalIgnoreCase) -or
$fullPath.StartsWith($fullDirectory + [IO.Path]::DirectorySeparatorChar, [StringComparison]::OrdinalIgnoreCase))
}
function Get-PublishPhysicalPath {
param([string]$Path)
# Resolve parent junctions as well as file symlinks on .NET Framework 4.x.
if (-not ('DSPModPublish.PhysicalPath' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace DSPModPublish {
public static class PhysicalPath {
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFile(string name, uint access, uint share,
IntPtr security, uint disposition, uint flags, IntPtr template);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint GetFinalPathNameByHandle(SafeFileHandle file,
StringBuilder path, uint length, uint flags);
public static string Resolve(string path) {
using (var handle = CreateFile(path, 0, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) {
if (handle.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
var buffer = new StringBuilder(32768);
var length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Capacity, 0);
if (length == 0 || length >= buffer.Capacity)
throw new Win32Exception(Marshal.GetLastWin32Error());
var result = buffer.ToString();
if (result.StartsWith(@"\\?\UNC\")) return @"\\" + result.Substring(8);
return result.StartsWith(@"\\?\") ? result.Substring(4) : result;
}
}
}
}
'@
}
return [DSPModPublish.PhysicalPath]::Resolve([IO.Path]::GetFullPath($Path))
}
function Get-PublishToken {
param([string]$EnvironmentFile)
if ([string]::IsNullOrWhiteSpace($EnvironmentFile)) {
$defaultFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath('.env')
if ([IO.File]::Exists($defaultFile)) { $EnvironmentFile = $defaultFile }
}
if (-not [string]::IsNullOrWhiteSpace($EnvironmentFile)) {
$filePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($EnvironmentFile)
if (-not [IO.File]::Exists($filePath)) { throw 'The environment file does not exist. Supply a UTF-8 file with TCLI_AUTH_TOKEN.' }
$token = $null
foreach ($line in [IO.File]::ReadAllLines($filePath, [Text.UTF8Encoding]::new($false, $true))) {
if ($line -match '^\s*(#.*)?$') { continue }
if ($line -notmatch '^\s*TCLI_AUTH_TOKEN\s*=\s*(.*?)\s*$' -or $null -ne $token) {
throw 'Invalid environment file. Use one TCLI_AUTH_TOKEN assignment, optional blank lines, and full-line comments.'
}
$token = $Matches[1]
if ($token.StartsWith('"') -or $token.StartsWith("'")) {
if ($token.Length -lt 2 -or $token[0] -ne $token[$token.Length - 1]) { throw 'The token has unmatched quotes in the environment file.' }
$token = $token.Substring(1, $token.Length - 2)
}
}
} else {
$token = [Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'Process')
}
if ([string]::IsNullOrWhiteSpace($token) -or $token -match '\s') {
throw 'Set a non-empty TCLI_AUTH_TOKEN without whitespace, create .env in the current directory, or supply -EnvFile.'
}
# tcli 0.2.4 reads the persisted Windows User value before the process value.
$userToken = Get-PublishUserToken
if (-not [string]::IsNullOrWhiteSpace($userToken) -and $userToken -cne $token) {
throw 'A different User-scoped TCLI_AUTH_TOKEN overrides the selected token in tcli. Remove or reconcile that setting before retrying.'
}
return $token
}
function Get-PublishUserToken {
return [Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'User')
}
function Get-PublishNamespace {
param([string]$Token)
$endpoint = 'https://thunderstore.io/api/experimental/current-user/'
try {
# Keep credentials on the fixed HTTPS endpoint and out of diagnostics.
$profile = Invoke-RestMethod -Uri $endpoint -Method Get -Headers @{ Authorization = "Bearer $Token" } -TimeoutSec 30 -MaximumRedirection 0 -ErrorAction Stop
} catch {
throw "Cannot query the token's Team at $endpoint. Check the service-account token, connectivity, and server availability before retrying; nothing was uploaded."
}
$username = Get-PublishJsonProperty $profile 'username'
$teamsProperty = if ($null -ne $profile) { $profile.PSObject.Properties['teams'] }
if ($username -isnot [string] -or [string]::IsNullOrWhiteSpace($username) -or
$null -eq $teamsProperty -or $teamsProperty.Value -isnot [array]) {
throw 'The current-user endpoint returned an unauthenticated or malformed response. Check the service-account token before publishing.'
}
$teams = $teamsProperty.Value
if ($teams.Count -eq 0) { throw 'The service-account token has no active Team. Check its Team membership before publishing.' }
if ($teams.Count -ne 1) { throw 'The token belongs to multiple Teams; publication requires exactly one Team.' }
if ($teams[0] -isnot [string] -or $teams[0] -notmatch '^[A-Za-z0-9_]+\z') {
throw 'The current-user endpoint returned an invalid Team name. Nothing was uploaded.'
}
return $teams[0]
}
function Assert-PublishChangelog {
param([string]$Text, [string]$Version)
$sections = @([regex]::Matches($Text, '(?is)<details\b[^>]*>(.*?)</details>') | ForEach-Object { $_.Groups[1].Value })
if ($sections.Count -eq 0) { $sections = @($Text) }
foreach ($section in $sections) {
$latest = [regex]::Match($section, '(?m)^\s*(?:[*-]\s+|#{1,6}\s+)(\d+\.\d+\.\d+)(?=\s|$)')
if (-not $latest.Success -or $latest.Groups[1].Value -cne $Version) {
throw "The latest changelog entry in every language must match project version $Version. Update the release notes before publishing."
}
}
}
function Get-PublishStreamHash {
param([IO.Stream]$Stream)
$hash = [Security.Cryptography.SHA256]::Create()
try { return [BitConverter]::ToString($hash.ComputeHash($Stream)) }
finally { $hash.Dispose() }
}
function Assert-PublishArchive {
param([string]$ZipPath, [string]$PackageName, [string]$Version, [hashtable]$Files, [bool]$HasChangelog)
Add-Type -AssemblyName System.IO.Compression.FileSystem
Add-Type -AssemblyName System.Drawing
$archive = [IO.Compression.ZipFile]::OpenRead($ZipPath)
try {
$entries = @{}
foreach ($entry in $archive.Entries) {
$entryName = $entry.FullName.Replace('\', '/')
if ($entryName -match '(^/|:|(^|/)\.\.(/|$))' -or $entries.ContainsKey($entryName)) {
throw 'The ZIP contains an unsafe path or duplicate entry. Rebuild the package.'
}
if ($entryName -match '(^|/)(\.env(?:\..*)?|thunderstore\.toml)$') { throw 'The ZIP contains a local publishing or credential file.' }
$entries[$entryName] = $entry
}
foreach ($entryName in $Files.Keys) {
if (-not $entries.ContainsKey($entryName) -or $entries[$entryName].FullName -cne $entryName) {
throw "The ZIP is missing the expected file '$entryName'. Rebuild the package."
}
$zipStream = $entries[$entryName].Open()
$fileStream = [IO.File]::OpenRead($Files[$entryName])
try {
if ((Get-PublishStreamHash $zipStream) -cne (Get-PublishStreamHash $fileStream)) {
throw "The ZIP file '$entryName' differs from its current source or build output. Rebuild the package."
}
} finally { $zipStream.Dispose(); $fileStream.Dispose() }
}
$reader = [IO.StreamReader]::new($entries['manifest.json'].Open(), [Text.Encoding]::UTF8, $true)
try { $manifest = $reader.ReadToEnd() | ConvertFrom-Json -ErrorAction Stop } finally { $reader.Dispose() }
if ((Get-PublishJsonProperty $manifest 'name') -cne $PackageName -or
(Get-PublishJsonProperty $manifest 'version_number') -cne $Version) {
throw 'The ZIP manifest does not match the selected package name and project version.'
}
$iconStream = $entries['icon.png'].Open()
try {
$icon = [Drawing.Image]::FromStream($iconStream)
try {
if ($icon.RawFormat.Guid -ne [Drawing.Imaging.ImageFormat]::Png.Guid -or $icon.Width -ne 256 -or $icon.Height -ne 256) {
throw 'The package icon must be a 256x256 PNG.'
}
} finally { $icon.Dispose() }
} finally { $iconStream.Dispose() }
if ($HasChangelog) {
$reader = [IO.StreamReader]::new($entries['CHANGELOG.md'].Open(), [Text.Encoding]::UTF8, $true)
try { Assert-PublishChangelog $reader.ReadToEnd() $Version } finally { $reader.Dispose() }
}
} finally { $archive.Dispose() }
}
function Assert-PublishVersionAvailable {
param([string]$Namespace, [string]$PackageName, [string]$Version)
$endpoint = "https://thunderstore.io/api/experimental/package/$Namespace/$PackageName/$Version/"
try {
$response = Invoke-RestMethod -Uri $endpoint -Method Get -TimeoutSec 30 -ErrorAction Stop
} catch {
$httpResponse = Get-PublishJsonProperty $_.Exception 'Response'
$status = Get-PublishJsonProperty $httpResponse 'StatusCode'
if ($null -ne $status -and [int]$status -eq 404) { return }
throw "Cannot check the remote version at $endpoint. Check connectivity and the server response before retrying; nothing was uploaded."
}
if ((Get-PublishJsonProperty $response 'namespace') -cne $Namespace -or
(Get-PublishJsonProperty $response 'name') -cne $PackageName -or
(Get-PublishJsonProperty $response 'version_number') -cne $Version) {
throw 'The package-version endpoint returned an unexpected response. Nothing was uploaded.'
}
throw "Version $Namespace-$PackageName-$Version already exists. Select an unpublished project version; this script does not bump versions."
}
function Invoke-ModPublish {
param([string]$RepositoryRoot, [string]$Project, [string]$EnvFile, [switch]$DryRun)
if ($Project -notmatch '^[A-Za-z0-9_][A-Za-z0-9_.-]*\z') {
throw 'Supply one top-level -Project directory name.'
}
$projectDir = Join-Path $RepositoryRoot $Project
$projectPath = Join-Path $projectDir "$Project.csproj"
$packageDir = Join-Path $projectDir 'package'
foreach ($required in @($projectPath, (Join-Path $packageDir 'manifest.json'), (Join-Path $packageDir 'icon.png'), (Join-Path $projectDir 'README.md'))) {
if (-not [IO.File]::Exists($required)) {
if ($Project.EndsWith('Preloader', [StringComparison]::OrdinalIgnoreCase)) {
throw "Select the main mod with -Project $($Project.Substring(0, $Project.Length - 9)); preloaders are bundled, not published separately."
}
throw "Required project/package file not found: $required. Select a packaged main mod, not a helper project."
}
}
$manifestPath = Join-Path $packageDir 'manifest.json'
$packageName = Get-PublishJsonProperty (Read-PublishJson $manifestPath) 'name'
if ($packageName -isnot [string] -or $packageName -notmatch '^[A-Za-z0-9_]+\z') { throw 'The manifest must have a valid, non-empty string name.' }
$token = $null
$namespace = $null
# Resolve token files before changing to the repository's build directory.
if (-not $DryRun) { $token = Get-PublishToken $EnvFile }
$oldToken = [Environment]::GetEnvironmentVariable('TCLI_AUTH_TOKEN', 'Process')
$configDir = $null
$configPath = $null
$configBase = Join-Path $projectDir 'obj\thunderstore-publish'
Push-Location -LiteralPath $RepositoryRoot
try {
$null = Get-Command dotnet -CommandType Application -ErrorAction Stop
if (-not $DryRun) {
Assert-PublishTcli
$namespace = Get-PublishNamespace $token
}
$metadata = Get-PublishProject $projectPath
$properties = $metadata.Properties
if (-not [string]::IsNullOrEmpty($properties.PackPreloaderTargetDir)) { throw 'Select a main mod; this project is a preloader or helper.' }
$version = $properties.Version
if ($version -notmatch '^[0-9]+\.[0-9]+\.[0-9]+\z') { throw 'The evaluated project Version must have the Thunderstore format major.minor.patch.' }
$bundled = @()
$needsRestore = -not [IO.File]::Exists($properties.ProjectAssetsFile)
foreach ($reference in @($metadata.Items.ProjectReference)) {
$referenceMetadata = Get-PublishProject $reference.FullPath
$referenceProperties = $referenceMetadata.Properties
if (-not [IO.File]::Exists($referenceProperties.ProjectAssetsFile)) { $needsRestore = $true }
if ([string]::IsNullOrEmpty($referenceProperties.PackPreloaderTargetDir)) { continue }
$targetDir = $referenceProperties.PackPreloaderTargetDir
if (-not [IO.Path]::IsPathRooted($targetDir)) { $targetDir = Join-Path ([IO.Path]::GetDirectoryName($reference.FullPath)) $targetDir }
$targetDir = [IO.Path]::GetFullPath($targetDir)
if (Test-PublishPathWithin $targetDir $packageDir) {
$bundled += [pscustomobject]@{ Path = $reference.FullPath; TargetDir = $targetDir; Output = $referenceProperties.TargetPath }
}
}
if ($needsRestore) { Invoke-PublishDotNet -Arguments @('restore', $projectPath) }
foreach ($preloader in $bundled) {
Invoke-PublishDotNet -Arguments @('build', $preloader.Path, '-t:CopyToParentPackage', '-c', 'Release', '--no-restore')
}
Invoke-PublishDotNet -Arguments @('build', $projectPath, '-t:ZipMod', '-c', 'Release', '--no-restore')
$zipPath = Join-Path $packageDir "$($properties.ProjectName)-$version.zip"
if (-not [IO.File]::Exists($zipPath)) { throw "The build did not produce the expected ZIP: $zipPath" }
$files = @{
'manifest.json' = $manifestPath
'icon.png' = Join-Path $packageDir 'icon.png'
'README.md' = Join-Path $projectDir 'README.md'
}
$dllName = [IO.Path]::GetFileName($properties.TargetPath)
$hasChangelog = $properties.PackHasChangelog -eq 'true'
if ($properties.PackUsePluginsLayout -eq 'true') { $files["plugins/$dllName"] = $properties.TargetPath }
else { $files[$dllName] = $properties.TargetPath }
foreach ($preloader in $bundled) {
$relativeDir = $preloader.TargetDir.Substring($packageDir.Length).TrimStart('\', '/').Replace('\', '/')
$entryName = ($relativeDir + '/' + [IO.Path]::GetFileName($preloader.Output)).TrimStart('/')
$files[$entryName] = $preloader.Output
}
if ($hasChangelog) { $files['CHANGELOG.md'] = Join-Path $projectDir 'CHANGELOG.md' }
Assert-PublishArchive $zipPath $packageName $version $files $hasChangelog
$teamLabel = if ($DryRun) { 'not queried (resolved from token when publishing)' } else { $namespace }
Write-Host "Project: $Project | Team: $teamLabel | Package: $packageName | Version: $version"
Write-Host 'Community: dyson-sphere-program | Categories: empty (retain existing listing categories)'
Write-Host "ZIP: $zipPath"
if ($DryRun) { Write-Host 'Dry run complete. Package validated; Team lookup and upload were skipped.'; return }
$configDir = Join-Path $configBase ([Guid]::NewGuid().ToString('N'))
$null = [IO.Directory]::CreateDirectory($configDir)
$configPath = Join-Path $configDir 'thunderstore.toml'
$configText = @"
[config]
schemaVersion = "0.0.1"
[package]
namespace = "$namespace"
name = "$packageName"
versionNumber = "$version"
[build]
outdir = "."
[publish]
repository = "https://thunderstore.io"
communities = ["dyson-sphere-program"]
categories = []
"@
[IO.File]::WriteAllText($configPath, $configText + [Environment]::NewLine, [Text.UTF8Encoding]::new($false))
Write-Host ('dotnet tool run tcli -- publish --config-path "{0}" --file "{1}"' -f $configPath, $zipPath)
Assert-PublishVersionAvailable $namespace $packageName $version
[Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', $token, 'Process')
try { Invoke-PublishDotNet -Arguments @('tool', 'run', 'tcli', '--', 'publish', '--config-path', $configPath, '--file', $zipPath) -Secret $token }
catch { throw "Publication did not finish successfully. Inspect https://thunderstore.io/c/dyson-sphere-program/p/$namespace/$packageName/v/$version/ before retrying; a submission may already have succeeded." }
Write-Host "Published: https://thunderstore.io/c/dyson-sphere-program/p/$namespace/$packageName/"
} finally {
# PowerShell converts $null to an empty string for this .NET call.
# Modern runtimes preserve empty environment values; use a true null.
if ($null -eq $oldToken) { [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', [NullString]::Value, 'Process') }
else { [Environment]::SetEnvironmentVariable('TCLI_AUTH_TOKEN', $oldToken, 'Process') }
Pop-Location
if ($null -ne $configDir -and (Test-PublishPathWithin $configDir $configBase) -and
[IO.Directory]::Exists($configDir) -and
(Test-PublishPathWithin (Get-PublishPhysicalPath $configDir) (Get-PublishPhysicalPath $configBase))) {
try {
if ([IO.File]::Exists($configPath)) { [IO.File]::Delete($configPath) }
[IO.Directory]::Delete($configDir, $false)
} catch { Write-Warning "Could not remove generated configuration directory: $configDir. Remove it when no longer needed." }
}
}
}
try {
Invoke-ModPublish -RepositoryRoot $PSScriptRoot -Project $Project -EnvFile $EnvFile -DryRun:$DryRun
} catch {
Write-Error -Message $_.Exception.Message -ErrorAction Continue
exit 1
}
-52
View File
@@ -68,55 +68,3 @@ Some functions and patches for better user experience
## [LiveStreamAssist](LiveStreamAssist) ## [LiveStreamAssist](LiveStreamAssist)
Keeps the statistics window active for live streams by switching between the Production Statistics and Dyson Sphere tabs every 15 to 30 seconds. Keeps the statistics window active for live streams by switching between the Production Statistics and Dyson Sphere tabs every 15 to 30 seconds.
## Publishing to Thunderstore
Use Windows PowerShell 5.1 or PowerShell 7, a .NET SDK with MSBuild 17.8 or newer, and the repository's normal game references and build prerequisites. Restore the pinned local tcli tool once from the repository root:
```powershell
dotnet tool restore
```
Select a single main mod with `-Project`. Package Name comes from `<Project>/package/manifest.json`; version comes from the project file. For publication, the script queries Thunderstore's `/api/experimental/current-user/` endpoint with the service-account token and uses its single Team as the namespace. Missing, invalid, or multiple Teams and request failures stop publication before building. Preview the build and package without a token or network access:
```powershell
.\Publish-Mod.ps1 -Project UXAssist -DryRun
```
To publish, put a Team service-account token in a UTF-8 `.env` file in the directory where the command is invoked, then run the same command without `-DryRun`. If `.env` is absent, the script reads the process environment variable `TCLI_AUTH_TOKEN`. To select another file, pass `-EnvFile`:
```powershell
.\Publish-Mod.ps1 -Project Dustbin -EnvFile "$env:USERPROFILE\.config\DSP_Mods\thunderstore.env"
```
The file accepts one `TCLI_AUTH_TOKEN=...` assignment, optional quotes, blank lines, and full-line comments. Token selection follows this order: explicit `-EnvFile`, the caller directory's `.env`, then the process variable. A selected file with an invalid or missing token is an error. `.env` and `.env.*` are ignored by Git; keep real tokens out of version control and shell command history. tcli 0.2.4 prioritizes a persisted Windows User-scoped token over the process token; if the values conflict, the script stops so that the stale setting can be reconciled.
The script always uses Release builds and the existing `ZipMod` target. It refreshes bundled preloaders before packaging, validates the exact ZIP, rejects an already published version, and uploads only the selected main mod. `-DryRun` still creates normal build/package outputs but skips credential loading, Team lookup, remote version checks, and uploads; its Team remains unresolved until publication. Publication always targets **Dyson Sphere Program** (`dyson-sphere-program`) with empty Category input, preserving the existing listing's categories; a first release starts without categories. Versions are never bumped automatically. After an interrupted or failed submission, check the printed version page before retrying because the release may already exist.
Run the focused script checks with `powershell.exe -NoProfile -File tools/tests/Test-PublishMod.ps1` or `pwsh -NoProfile -File tools/tests/Test-PublishMod.ps1`. They use synthetic credentials and stubbed network/publication commands; scratch files stay under `UXAssist/obj/publish-mod-check`.
## 发布到 Thunderstore
使用 Windows PowerShell 5.1 或 PowerShell 7,并安装包含 MSBuild 17.8 或更新版本的 .NET SDK。游戏引用和其他构建依赖与正常编译一致。首次使用时,在仓库根目录还原固定版本的本地 tcli 工具:
```powershell
dotnet tool restore
```
通过 `-Project` 选择一个主 mod。Package Name 读取 `<Project>/package/manifest.json`,版本读取项目文件。正式发布时,脚本使用服务账号 token 查询 Thunderstore 的 `/api/experimental/current-user/` 接口,将返回的唯一 Team 作为 namespace。没有 Team、Team 名称无效、存在多个 Team 或请求失败时,脚本会在构建前停止。可以先预览构建和打包,无需 token,也无需联网:
```powershell
.\Publish-Mod.ps1 -Project UXAssist -DryRun
```
正式发布时,将 Team 服务账号的 token 写入调用目录下的 UTF-8 `.env` 文件,再去掉 `-DryRun` 执行。如果 `.env` 不存在,脚本会读取进程环境变量 `TCLI_AUTH_TOKEN`。也可以通过 `-EnvFile` 指定其他文件:
```powershell
.\Publish-Mod.ps1 -Project Dustbin -EnvFile "$env:USERPROFILE\.config\DSP_Mods\thunderstore.env"
```
文件允许一条 `TCLI_AUTH_TOKEN=...` 赋值,以及可选的引号、空行和整行注释。token 的读取优先级为:显式 `-EnvFile`、调用目录下的 `.env`、进程环境变量。选中的文件缺少 token 或格式无效时,脚本会报错。`.env` 和 `.env.*` 已加入 Git 忽略规则;真实 token 不应提交到版本控制,也不要写入 shell 命令历史。tcli 0.2.4 会优先读取 Windows 持久化的用户级 token;如果它与本次选定的 token 不同,脚本会停止,需先处理旧设置。
脚本始终使用 Release 构建和现有的 `ZipMod` 目标。它会在打包前更新附带的 preloader,检查本次生成的确切 ZIP,拒绝重复发布已有版本,并且只上传选定的主 mod。`-DryRun` 仍会生成正常的构建和打包产物,但跳过凭据读取、Team 查询、远程版本检查和上传;Team 留待正式发布时确定。发布社区固定为 **Dyson Sphere Program**(`dyson-sphere-program`);Category 输入留空,保留已有条目的分类,首次发布则不设置分类。脚本不会自动修改版本号。提交中断或失败后,应先检查输出的版本页面,再决定是否重试,因为该版本可能已经发布成功。
可以运行 `powershell.exe -NoProfile -File tools/tests/Test-PublishMod.ps1` 或 `pwsh -NoProfile -File tools/tests/Test-PublishMod.ps1` 检查脚本。测试使用虚构的凭据,以及模拟的网络和发布命令;临时文件保存在 `UXAssist/obj/publish-mod-check` 下。
+4 -42
View File
@@ -3,32 +3,13 @@
## Changlog ## Changlog
* 1.6.4 * 1.6.2 - Unrelease
* `Reverse conveyor belt`: Enable it on the Factory tab and press `Alt+R` over a built belt to reverse it without opening its panel. The shortcut can be changed in the system options.
* `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.
* `Auto-cruise`: Fix the mecha diving back into the ground right after taking off from a moon that is close to its gas giant.
* 1.6.3
* `Quick build Mining Machines`:
* Add a Factory-tab button to arrange ordinary Mining Machines densely around the nearest solid vein group. Each miner covers at least 3 nodes from that group, without including nearby groups. Layouts are not limited by stock; missing miners remain as ghosts awaiting materials. Placement respects construction range and does not include belts or power facilities. Click again to cancel a search.
* `Allow restoring/burying veins` is off by default, using only visible nodes without restoring or burying any. Enable it to restore unobstructed nodes away from Dark Fog Planetary Bases and allow unused nodes to be buried for better coverage. Nodes used by existing miners or miner ghosts are protected.
* `Blueprint descriptions`:
* Add an `Auto-fill` entry to the native description header in the blueprint browser, copy, and paste inspectors. It opens generation options without moving native fields or covering the file list. Generation replaces the main description with material flows per minute, separating shortages, surpluses, inputs, outputs, and research use, and adds factory and logistics power demand to a `Power` custom field.
* Choose `Final-product output` (the default on opening the inspector) to retain rated final outputs and show intermediate shortages and excess, or `Lowest intermediate throughput` to scale the final-product mix to the bottleneck using recipe ratios. Complete, balanceable chains have no internal shortages in the latter mode; unused intermediate capacity appears as excess. External inputs use the selected basis; power still covers every selected building at full load. If a balanced basis cannot be determined, the original description is kept.
* A `Proliferation` checkbox controls whether calculations include proliferation, defaulting to on when the blueprint contains a Spray Coater. Large rates use K/M/G where display precision is preserved, and numbers with four or more integer digits use comma thousands separators, including before suffixes; unknown values are marked separately. Other custom fields are preserved, and the blueprint still needs to be saved manually.
* `Sunlight at night`: Lighting now follows the camera, including planet view, and stays consistent across buildings, terrain, solar panels, and belts. Restore lighting correctly after switching planets, and return to native lighting when sailing, disabling the feature, or using white rendering mode.
* `Protect veins from exhaustion`: Fix the option failing to take effect in 1.6.2, restoring protection of configured vein reserves and minimum oil rates, along with the corresponding mining statistics.
* 1.6.2
* `Increase maximum power usage in Logistic Stations and Advanced Mining Machines`: Fix zero or corrupted mining speeds when adjusting an Advanced Mining Machine's speed slider with the option enabled.
* `Tweak building buffers`: Restore the Ray Receiver Graviton Lens buffer setting on DSP 0.10.35.29104 and later, and correct the displayed native buffer value to 2.
* `Drag building power poles`: Fix invalid alternating previews when enabling the option after loading a save, and restore original spacing when disabling it.
* Close building and belt hover popups when opening the pause menu so they cannot obscure menu controls.
* `Protect veins from exhaustion`: Exclude protected veins from mining-rate estimates, mining resource counts, and miner hover counts while retaining their remaining reserves.
* `Dismantle blueprint selected buildings`: Respect sandbox instant-dismantle settings when discarding logistics station contents, and return them normally outside instant dismantling.
* `Treat stack items as single in monitor components`: Fix the option taking effect at game startup when disabled, until toggled on and off. * `Treat stack items as single in monitor components`: Fix the option taking effect at game startup when disabled, until toggled on and off.
* `Building options`: Honor saved toggle states at startup for off-grid construction, power-pole dragging, fast tank transfers, and Ctrl+Shift belt pickup. * `Building options`: Honor saved toggle states at startup for off-grid construction, power-pole dragging, fast tank transfers, and Ctrl+Shift belt pickup.
* `Belt signals for buy out dark fog items automatically`: Use the current in-game material names and retain the original exchange ratios. * `Belt signals for buy out dark fog items automatically`: Use the current in-game material names and retain the original exchange ratios.
* `Initialize This Planet`: Fix an occasional array index error after initializing a planet with Holo Beacons. * `Initialize This Planet`: Fix an occasional array index error after initializing a planet with Holo Beacons.
* `Planet vein utilization`: Restore the original vertical alignment of vein-group counts and keep resource names in their original positions. * `Planet vein utilization`: Restore the original vertical alignment of vein-group counts and keep resource names in their original positions.
* `Blueprint descriptions`: Add a row with an Auto-fill description button and a right-hand Proliferation checkbox above all description boxes in the browser, copy, and paste inspectors. Replace the main description with wrapping, nonempty Missing, Excess, Input, Output, and Research lines: group each warning category under one label and omit the per-minute suffix while keeping per-minute rates. Cap upstream inputs at sustainable downstream throughput even when unrelated parameters are unknown, without assuming unknown downstream demand is zero; keep independently known rated outputs and power. Budget every research-mode lab at full working power, and treat one selected lab as an outlet for all six matrix types made within the blueprint, regardless of the save's technology or research speed. Display positive net matrix output only under Research, after other buildings' known matrix use; keep unrelated final products under Output. Do not invent matrix consumption rates or imports, and do not flag the accepted output as excess. Keep Power as the only optional generated custom field, showing factory and logistics demand only when present and marking unknown demand separately. Report necessary coproducts and incomplete results, preserve other custom fields, and never save automatically. Fix false coproduct output in mixed production lines and at fractional building ratios.
* 1.6.1 * 1.6.1
* `Larger area for terraform`: Restore 11x11 through 30x30 foundation and Restore Terrain brushes after DSP 0.10.35.29104. * `Larger area for terraform`: Restore 11x11 through 30x30 foundation and Restore Terrain brushes after DSP 0.10.35.29104.
* Fix the title-screen background turning black, even when the UXAssist window is closed. * Fix the title-screen background turning black, even when the UXAssist window is closed.
@@ -448,32 +429,13 @@
## 更新日志 ## 更新日志
* 1.6.4 * 1.6.2 - Unreleased
* `反转传送带`:在「工厂」页启用后,将鼠标移到已建成的传送带上,按 `Alt+R` 直接反转,无需打开面板;可在系统选项中修改快捷键。
* `在和平模式下隐藏战斗相关科技`:修复在同一次游戏运行中从和平模式存档切换到战斗模式存档后打开科技树时的数组越界,以及再次加载和平模式存档后关闭选项时的同类问题。
* `自动巡航`:修复从紧邻气态巨星的卫星上起飞后,机甲又扎回地面的问题。
* 1.6.3
* `快速铺设采矿机`:
* 在「工厂」页增加按钮,自动在最近的固体矿脉周围密集铺设普通采矿机。每台至少覆盖选中矿脉的 3 个矿点,不混入附近其他矿脉。布局数量不受库存限制,采矿机不足的位置保留待建造虚影。遵守建造范围,不自动铺设传送带和电力设施。计算期间再次点击可取消。
* 「允许恢复/掩埋矿物」默认关闭,仅使用可见矿点,不恢复或掩埋矿点。开启后可恢复未被建筑阻挡、且远离黑雾行星基地的矿点,并允许掩埋未使用的矿点来提高覆盖数;已有矿机和待建造矿机使用的矿点会受到保护。
* `蓝图说明`:
* 在蓝图浏览、复制和粘贴检查面板的说明标题行增加「自动填写」入口,点击展开生成选项,不移动原生字段或遮挡文件列表。生成时用每分钟的物料流量替换原说明,分别列出「缺少」「多余」「输入」「输出」「研究」,并将工厂与物流耗电写入「耗电」自定义字段。
* 可选择「最终产物产量」(每次打开检查面板时的默认值),保留最终产物的额定产量并显示中间产物的缺口和余量;也可选择「最低产量中间产物」,按配方比例换算瓶颈,等比例缩放各最终产物。后一种模式下,数据完整且可平衡的生产链没有内部缺口,未使用的中间产能列为「多余」。外部输入采用所选基准,耗电仍按所选全部建筑满载估算。无法确定平衡基准时保留原说明。
* 可用「增产」复选框选择是否计入增产效果,蓝图含喷涂机时默认勾选。较大的流量在保留显示精度的前提下使用 K/M/G 单位;整数部分达到四位的数字用逗号每三位分隔,带单位时也适用。无法计算的数值单独标注。保留其他自定义字段,填写后仍需手动保存蓝图。
* `夜间日光灯`:光照改为随镜头变化,行星视图也适用;建筑、地表、太阳能板和传送带的光照方向保持一致。切换行星后正确恢复光照,航行、关闭功能或进入白模渲染时恢复原版光照。
* `保护矿脉不会枯竭`:修复 1.6.2 中开启后仍不生效的问题,恢复设定的矿脉剩余量、油井最低流速保护及相应开采统计。
* 1.6.2
* `提升物流塔和大型采矿机的最大功耗`:修复启用后调整大型采矿机开采速度时出现 0% 或异常速度的问题。
* `调整建筑输入缓冲`:修复 DSP 0.10.35.29104 及后续版本中射线接收器透镜缓冲设置不生效的问题,并将显示的游戏原始值更正为 2。
* `拖建电线杆`:修复载入存档后才启用功能时交替放置的预览异常,并在关闭时恢复原有间距。
* 打开暂停菜单时关闭建筑和传送带的悬浮提示,避免提示遮挡菜单。
* `保护矿脉不会枯竭`:开采速度估算、开采中资源数量和采矿机悬浮信息不再把受保护的矿脉计入开采;仍保留剩余储量显示。
* `拆除蓝图选中的建筑`:按沙盒模式的瞬间拆除设置销毁物流站库存;常规拆除时仍正常返还库存。
* `在流速计中将堆叠物品视为单个物品`:修复未勾选时仍在启动游戏后生效、必须切换一次才能关闭的问题。 * `在流速计中将堆叠物品视为单个物品`:修复未勾选时仍在启动游戏后生效、必须切换一次才能关闭的问题。
* `建造选项`:修复不对齐网格建造、拖建电线杆、储液罐快速存取和 Ctrl+Shift 拾取整段传送带物品在启动时忽略已保存开关的问题。 * `建造选项`:修复不对齐网格建造、拖建电线杆、储液罐快速存取和 Ctrl+Shift 拾取整段传送带物品在启动时忽略已保存开关的问题。
* `用于自动购买黑雾物品的传送带信号`:统一使用当前游戏中的材料名称,保留原有兑换比例。 * `用于自动购买黑雾物品的传送带信号`:统一使用当前游戏中的材料名称,保留原有兑换比例。
* `初始化本行星`:修复行星上存在全息信标时,初始化后可能出现数组越界报错的问题。 * `初始化本行星`:修复行星上存在全息信标时,初始化后可能出现数组越界报错的问题。
* `宇宙视图行星/星系矿脉数量显示`:修复矿脉数量文字偏下和矿物名称向右偏移的问题。 * `宇宙视图行星/星系矿脉数量显示`:修复矿脉数量文字偏下和矿物名称向右偏移的问题。
* `蓝图说明`:在蓝图浏览、复制和粘贴界面的所有说明框上方增加「自动填写说明」按钮,并将「增产」复选框放在按钮右侧。直接用可换行内容替换原说明:按需依次显示「缺少:」「多余:」「输入:」「输出:」「研究:」,缺少或多余的物品共用一次行标签;标签不再显示「每分钟」,材料速率仍按每分钟计算。上游产量超过下游需求时,即使其他参数未知,也按已知下游的可持续产量估算输入;不把未知下游需求当作零。独立可确定的输出和耗电仍按额定值计算。所有研究模式研究站都按额定满负荷计入耗电;只要蓝图内有一座研究站,就假设它能接纳蓝图内产出的全部六种矩阵,不受存档科技或研究速度影响。扣除蓝图内其他建筑已知的矩阵消耗后,仅将净产量写入「研究」行;其他最终产物仍写入「输出」行。既不虚构研究站的矩阵消耗速率或外部需求,也不把被接纳的矩阵计为多余产量。仅在有耗电或耗电未知时生成「耗电」自定义字段,分别标注工厂与物流的有效类别。标出必要的联产盈余和数据不完整的结果;保留其他自定义字段,也不自动保存蓝图。修复混合生产线及非整数建筑配比下的副产物误报。
* 1.6.1 * 1.6.1
* `范围铺设地基的最大区域扩大`:适配 DSP 0.10.35.29104,恢复 11x11 至 30x30 的铺设地基与恢复地形范围。 * `范围铺设地基的最大区域扩大`:适配 DSP 0.10.35.29104,恢复 11x11 至 30x30 的铺设地基与恢复地形范围。
* 修复标题画面背景变黑的问题,包括关闭 UXAssist 窗口后背景仍不显示的情况。 * 修复标题画面背景变黑的问题,包括关闭 UXAssist 窗口后背景仍不显示的情况。
@@ -26,7 +26,6 @@ public static class FactoryConfigProvider
public static ConfigEntry<bool> TankFastFillInAndTakeOutEnabled => FactoryPatch.TankFastFillInAndTakeOutEnabled; public static ConfigEntry<bool> TankFastFillInAndTakeOutEnabled => FactoryPatch.TankFastFillInAndTakeOutEnabled;
public static ConfigEntry<int> TankFastFillInAndTakeOutMultiplier => FactoryPatch.TankFastFillInAndTakeOutMultiplier; public static ConfigEntry<int> TankFastFillInAndTakeOutMultiplier => FactoryPatch.TankFastFillInAndTakeOutMultiplier;
public static ConfigEntry<bool> CutConveyorBeltEnabled => FactoryPatch.CutConveyorBeltEnabled; public static ConfigEntry<bool> CutConveyorBeltEnabled => FactoryPatch.CutConveyorBeltEnabled;
public static ConfigEntry<bool> ReverseConveyorBeltEnabled => FactoryPatch.ReverseConveyorBeltEnabled;
public static ConfigEntry<bool> TweakBuildingBufferEnabled => FactoryPatch.TweakBuildingBufferEnabled; public static ConfigEntry<bool> TweakBuildingBufferEnabled => FactoryPatch.TweakBuildingBufferEnabled;
public static ConfigEntry<int> AssemblerBufferTimeMultiplier => FactoryPatch.AssemblerBufferTimeMultiplier; public static ConfigEntry<int> AssemblerBufferTimeMultiplier => FactoryPatch.AssemblerBufferTimeMultiplier;
public static ConfigEntry<int> AssemblerBufferMininumMultiplier => FactoryPatch.AssemblerBufferMininumMultiplier; public static ConfigEntry<int> AssemblerBufferMininumMultiplier => FactoryPatch.AssemblerBufferMininumMultiplier;
+70 -56
View File
@@ -13,98 +13,112 @@ public static class ItemIds
public const int SulfuricAcid = 1116; public const int SulfuricAcid = 1116;
public const int Hydrogen = 1120; public const int Hydrogen = 1120;
public const int Deuterium = 1121; public const int Deuterium = 1121;
public const int CriticalPhoton = 1208; public const int Photon = 1208;
/* Materials and components */ /* Materials used by recipes */
public const int TitaniumAlloy = 1107; public const int OrganicCrystal = 1015;
public const int Prism = 1111; public const int FireIce = 1012;
public const int FrameMaterial = 1125; public const int CriticalPhoton = 1124;
public const int CasimirCrystal = 1126; public const int CircuitBoard = 1112; // used in proliferator mk.III recipe
public const int MagneticCoil = 1202; public const int Steel = 1107;
public const int ElectricMotor = 1203; public const int TitaniumGlass = 1111;
public const int ElectromagneticTurbine = 1204; public const int GravitonLens = 1125;
public const int SuperMagneticRing = 1205;
public const int GravitonLens = 1209;
public const int CircuitBoard = 1301;
public const int QuantumChip = 1305;
public const int PlasmaExciter = 1401;
public const int ParticleBroadband = 1402;
public const int AnnihilationConstraintSphere = 1403;
public const int Thruster = 1405;
public const int ReinforcedThruster = 1406;
/* Proliferators */ /* Proliferators */
public const int ProliferatorMkI = 1141; public const int ProliferatorMkI = 1141;
public const int ProliferatorMkII = 1142; public const int ProliferatorMkII = 1142;
public const int ProliferatorMkIII = 1143; public const int ProliferatorMkIII = 1143;
/* Logistics */ /* Logistics carriers */
public const int SpaceWarper = 1210;
public const int LogisticsDrone = 5001; public const int LogisticsDrone = 5001;
public const int LogisticsVessel = 5002; public const int LogisticsVessel = 5002;
public const int LogisticsBot = 5003; public const int LogisticsBot = 5003;
public const int SpaceWarper = 1126;
/* Matrices */
public const int ElectromagneticMatrix = 1202;
public const int EnergyMatrix = 1203;
public const int StructureMatrix = 1204;
public const int InformationMatrix = 1205;
public const int UniverseMatrix = 1209;
public const int Antimatter = 1210;
/* Components */
public const int PlasmaExciter = 1301;
public const int ParticleBroadband = 1305;
public const int Processor = 1401;
public const int QuantumChip = 1402;
public const int MicrocrystallineComponent = 1403;
public const int PlaneFilter = 1405;
public const int ParticleContainer = 1406;
/* Dyson sphere materials */ /* Dyson sphere materials */
public const int DysonSphereComponent = 1502; public const int SolarSail = 1502;
public const int SmallCarrierRocket = 1503; public const int FrameMaterial = 1503;
public const int DysonSphereComponent = 1802;
/* Fuel rods */
public const int DeuteronFuelRod = 1802;
public const int StrangeAnnihilationFuelRod = 1804;
/* Power nodes */
public const int TeslaTower = 2201;
/* Power generators */ /* Power generators */
public const int WindTurbine = 2203; public const int WindTurbine = 2203;
/* Mining */
public const int MiningMachine = 2301;
/* Dark Fog items (combat expansion) */ /* Dark Fog items (combat expansion) */
public const int DarkFogMatrix = 5201; public const int DarkFogMemoryUnit = 5201;
public const int DarkFogSiliconNeuron = 5202; public const int DarkFogSiliconNeuron = 5202;
public const int DarkFogMatterRecombinator = 5203; public const int DarkFogMatterReassembler = 5203;
public const int DarkFogNegentropySingularity = 5204; public const int DarkFogNegentropySingularity = 5204;
public const int DarkFogCoreElement = 5205; public const int DarkFogVirtualParticle = 5205;
public const int DarkFogEnergyShard = 5206; public const int DarkFogEnergyFragment = 5206;
/* Matrices. Metadata types use the same IDs; the Universe Matrix's metadata is Metaverse. */ /* Fuel and advanced items */
public const int ElectromagneticMatrix = 6001; public const int HydrogenFuelRod = 6001;
public const int EnergyMatrix = 6002; public const int DeuteronFuelRod = 6002;
public const int StructureMatrix = 6003; public const int AntimatterFuelRod = 6003;
public const int InformationMatrix = 6004; public const int StrangeAnnihilationFuelRod = 1804;
public const int GravityMatrix = 6005; public const int StrangeMatter = 6004;
public const int UniverseMatrix = 6006; public const int Foundation = 6005;
public const int Metaverse = 6006; // also called property/meta-data item
/* Item groups used by belt signal recipe calculations. */ /* Item groups used by belt signal recipe calculations. */
public static readonly int[] ExtraOreItemIds = public static readonly int[] ExtraOreItemIds =
[ [
Water, SulfuricAcid, Hydrogen, Deuterium, CriticalPhoton, Water, SulfuricAcid, Hydrogen, Deuterium, Photon,
DarkFogMatrix, DarkFogSiliconNeuron, DarkFogMatterRecombinator, DarkFogMemoryUnit, DarkFogSiliconNeuron, DarkFogMatterReassembler,
DarkFogNegentropySingularity, DarkFogCoreElement, DarkFogEnergyShard DarkFogNegentropySingularity, DarkFogVirtualParticle, DarkFogEnergyFragment
]; ];
// Listed in the same order as the belt signal option tips.
public static readonly HashSet<int> ExtraProliferationItemIds = public static readonly HashSet<int> ExtraProliferationItemIds =
[ [
TitaniumAlloy, Prism, FrameMaterial, ProliferatorMkII, ProliferatorMkIII, Steel, TitaniumGlass, GravitonLens, ProliferatorMkII, ProliferatorMkIII,
MagneticCoil, ElectricMotor, ElectromagneticTurbine, SuperMagneticRing, ElectromagneticMatrix, EnergyMatrix, StructureMatrix, InformationMatrix,
CircuitBoard, Thruster, ReinforcedThruster, PlasmaExciter, ParticleBroadband, UniverseMatrix, Antimatter, PlasmaExciter, ParticleBroadband,
GravitonLens, QuantumChip, AnnihilationConstraintSphere, DeuteronFuelRod, SpaceWarper, Processor, QuantumChip, MicrocrystallineComponent, PlaneFilter, ParticleContainer,
DysonSphereComponent, SmallCarrierRocket, ElectromagneticMatrix, StructureMatrix, SolarSail, FrameMaterial, DysonSphereComponent,
InformationMatrix, GravityMatrix, UniverseMatrix HydrogenFuelRod, AntimatterFuelRod, StrangeMatter, Foundation, Metaverse
]; ];
public static readonly HashSet<int> NoProliferationItemIds = public static readonly HashSet<int> NoProliferationItemIds =
[ [
CasimirCrystal, EnergyMatrix SpaceWarper, DeuteronFuelRod
];
/// <summary>
/// All source items used to create 25 proliferators mk.III (not self-sprayed).
/// </summary>
public static readonly List<(int ItemId, float Count)> ProliferatorSources =
[
(OrganicCrystal, 60f),
(CriticalPhoton, 20f),
(Coal, 64f),
(FireIce, 16f),
(CircuitBoard, 32f),
(ProliferatorMkI, 64f),
(ProliferatorMkII, 40f),
(ProliferatorMkIII, 25f)
]; ];
/* Dark Fog materials used by production calculations. */ /* Dark Fog materials used by production calculations. */
public static readonly int[] DarkFogItemIds = public static readonly int[] DarkFogItemIds =
[ [
DarkFogMatrix, DarkFogSiliconNeuron, DarkFogMatterRecombinator, DarkFogMemoryUnit, DarkFogSiliconNeuron, DarkFogMatterReassembler,
DarkFogNegentropySingularity, DarkFogCoreElement, DarkFogEnergyShard DarkFogNegentropySingularity, DarkFogVirtualParticle, DarkFogEnergyFragment
]; ];
} }
+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 -57
View File
@@ -6,14 +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 BlueprintDescriptionOptions = "UXAssist Blueprint Description Options";
public const string BlueprintDescriptionOptionsTip = "UXAssist Blueprint Description Options Tip";
public const string BlueprintProliferation = "UXAssist Blueprint Proliferation"; public const string BlueprintProliferation = "UXAssist Blueprint Proliferation";
public const string BlueprintProductionBasis = "UXAssist Blueprint Production Basis";
public const string BlueprintFinalProducts = "UXAssist Blueprint Final Products";
public const string BlueprintBottleneckIntermediate = "UXAssist Blueprint Bottleneck Intermediate";
public const string BlueprintProductionBasisTip = "UXAssist Blueprint Production Basis Tip";
public const string BlueprintBasisUnavailable = "Cannot determine a balanced intermediate throughput. Check building settings and production-chain outputs, or use final-product output.";
public const string BlueprintPower = "UXAssist Blueprint Power"; public const string BlueprintPower = "UXAssist Blueprint Power";
public const string BlueprintPowerEnglish = "Power"; public const string BlueprintPowerEnglish = "Power";
public const string BlueprintPowerChinese = "耗电"; public const string BlueprintPowerChinese = "耗电";
@@ -60,7 +53,6 @@ public static class I18NKeys
public const string KEYToggleDoNotRenderEntities = "KEYToggleDoNotRenderEntities"; public const string KEYToggleDoNotRenderEntities = "KEYToggleDoNotRenderEntities";
public const string KEYOffgridForPaths = "KEYOffgridForPaths"; public const string KEYOffgridForPaths = "KEYOffgridForPaths";
public const string KEYCutConveyorBelt = "KEYCutConveyorBelt"; public const string KEYCutConveyorBelt = "KEYCutConveyorBelt";
public const string KEYReverseConveyorBelt = "KEYReverseConveyorBelt";
public const string KEYDismantleBlueprintSelection = "KEYDismantleBlueprintSelection"; public const string KEYDismantleBlueprintSelection = "KEYDismantleBlueprintSelection";
public const string KEYSelectAllBuildingsInBlueprintCopy = "KEYSelectAllBuildingsInBlueprintCopy"; public const string KEYSelectAllBuildingsInBlueprintCopy = "KEYSelectAllBuildingsInBlueprintCopy";
public const string KEYUPSSpeedDown = "KEYUPSSpeedDown"; public const string KEYUPSSpeedDown = "KEYUPSSpeedDown";
@@ -112,7 +104,6 @@ public static class I18NKeys
public const string FastFillInToAndTakeOutFromTanks = "Fast fill in to and take out from tanks"; public const string FastFillInToAndTakeOutFromTanks = "Fast fill in to and take out from tanks";
public const string SpeedRatio = "Speed Ratio"; public const string SpeedRatio = "Speed Ratio";
public const string CutConveyorBeltWithShortcutKey = "Cut conveyor belt (with shortcut key)"; public const string CutConveyorBeltWithShortcutKey = "Cut conveyor belt (with shortcut key)";
public const string ReverseConveyorBeltWithShortcutKey = "Reverse conveyor belt (with shortcut key)";
public const string ProtectVeinsFromExhaustion = "Protect veins from exhaustion"; public const string ProtectVeinsFromExhaustion = "Protect veins from exhaustion";
public const string ProtectVeinsFromExhaustionTips = "Protect veins from exhaustion tips"; public const string ProtectVeinsFromExhaustionTips = "Protect veins from exhaustion tips";
public const string DoNotRenderFactoryEntities = "Do not render factory entities"; public const string DoNotRenderFactoryEntities = "Do not render factory entities";
@@ -202,22 +193,6 @@ public static class I18NKeys
public const string DismantleAllBuildings = "Dismantle All Buildings"; public const string DismantleAllBuildings = "Dismantle All Buildings";
public const string DismantleAllBuildingsConfirm = "Dismantle All Buildings Confirm"; public const string DismantleAllBuildingsConfirm = "Dismantle All Buildings Confirm";
public const string QuickBuildOrbitalCollectors = "Quick build Orbital Collectors"; public const string QuickBuildOrbitalCollectors = "Quick build Orbital Collectors";
public const string QuickBuildMiningMachines = "Quick build Mining Machines";
public const string QuickBuildMiningMachinesTips = "Quick build Mining Machines tips";
public const string QuickMinerAllowVeinReform = "Allow restoring/burying veins";
public const string QuickMinerCancelSearch = "Cancel miner layout search";
public const string QuickMinerSearching = "Searching for a dense miner layout";
public const string QuickMinerCancelled = "Miner layout search cancelled";
public const string QuickMinerNeedPlanet = "Land on a rocky planet to place miners";
public const string QuickMinerNoVeins = "No mineable vein group on this planet";
public const string QuickMinerNoPlacement = "No valid miner placements; move closer and check available land";
public const string QuickMinerFailed = "Miner placement stopped; check the log before retrying";
public const string QuickMinerVeinsChanged = "Veins changed during miner layout search";
public const string QuickMinerResult = "Placed {0} Mining Machines, {1} total vein coverage, {2} buried nodes";
#if DEBUG
public const string QuickMinerDebugSaved = "Miner layout debug data: {0}";
public const string QuickMinerDebugFailed = "Could not save miner layout debug data";
#endif
public const string MaximumCountToBuild = "Maximum count to build"; public const string MaximumCountToBuild = "Maximum count to build";
public const string Max = "max"; public const string Max = "max";
public const string StopEjectorsWhenAvailableNodesAreAllFilledUp = "Stop ejectors when available nodes are all filled up"; public const string StopEjectorsWhenAvailableNodesAreAllFilledUp = "Stop ejectors when available nodes are all filled up";
@@ -246,19 +221,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(BlueprintDescriptionOptions, "Auto-fill…", "自动填写…");
I18N.Add(BlueprintDescriptionOptionsTip,
"Choose production basis and proliferation, then fill the blueprint description.",
"选择产量基准和增产后,自动填写蓝图说明。");
I18N.Add(BlueprintProliferation, "Proliferation", "增产"); I18N.Add(BlueprintProliferation, "Proliferation", "增产");
I18N.Add(BlueprintProductionBasis, "Production basis", "产量基准");
I18N.Add(BlueprintFinalProducts, "Final-product output", "最终产物产量");
I18N.Add(BlueprintBottleneckIntermediate, "Lowest intermediate throughput", "最低产量中间产物");
I18N.Add(BlueprintProductionBasisTip,
"Final-product output (default): keep rated final outputs and show intermediate shortages and excess.\nLowest intermediate throughput: convert capacities through recipe ratios and scale all final outputs together to the bottleneck; complete, balanceable chains have no internal shortages. Excess shows unused intermediate capacity. Power still sizes all selected buildings at full load.\nUnknown settings or an unresolved output prevent balanced generation; the existing description is kept.",
"最终产物产量(默认):保留最终产物的额定产量,显示中间产物的缺口和余量。\n最低产量中间产物:按配方比例换算产能,以瓶颈等比例缩放各最终产物;数据完整且可平衡时没有内部缺口,「多余」表示未使用的中间产能。耗电仍按所选全部建筑满载估算。\n缺少参数或无法确定输出时,不生成平衡说明,保留原说明。");
I18N.Add(BlueprintBasisUnavailable, BlueprintBasisUnavailable,
"无法确定可平衡的中间产物产量,原说明已保留。请检查建筑参数和生产链输出,或改用最终产物产量基准。");
I18N.Add(BlueprintPower, BlueprintPowerEnglish, BlueprintPowerChinese); I18N.Add(BlueprintPower, BlueprintPowerEnglish, BlueprintPowerChinese);
I18N.Add(BlueprintInputLine, "Input: ", "输入:"); I18N.Add(BlueprintInputLine, "Input: ", "输入:");
I18N.Add(BlueprintOutputLine, "Output: ", "输出:"); I18N.Add(BlueprintOutputLine, "Output: ", "输出:");
@@ -303,7 +266,6 @@ public static class I18NKeys
I18N.Add(KEYToggleDoNotRenderEntities, "[UXA] Toggle Do Not Render Factory Entities", "[UXA] 切换不渲染工厂建筑实体"); I18N.Add(KEYToggleDoNotRenderEntities, "[UXA] Toggle Do Not Render Factory Entities", "[UXA] 切换不渲染工厂建筑实体");
I18N.Add(KEYOffgridForPaths, "[UXA] Build belts offgrid", "[UXA] 脱离网格建造传送带"); I18N.Add(KEYOffgridForPaths, "[UXA] Build belts offgrid", "[UXA] 脱离网格建造传送带");
I18N.Add(KEYCutConveyorBelt, "[UXA] Cut conveyor belt", "[UXA] 切割传送带"); I18N.Add(KEYCutConveyorBelt, "[UXA] Cut conveyor belt", "[UXA] 切割传送带");
I18N.Add(KEYReverseConveyorBelt, "[UXA] Reverse conveyor belt", "[UXA] 反转传送带");
I18N.Add(KEYDismantleBlueprintSelection, "[UXA] Dismantle blueprint selected buildings", "[UXA] 拆除蓝图选中的建筑"); I18N.Add(KEYDismantleBlueprintSelection, "[UXA] Dismantle blueprint selected buildings", "[UXA] 拆除蓝图选中的建筑");
I18N.Add(KEYSelectAllBuildingsInBlueprintCopy, "[UXA] Select all buildings in Blueprint Copy Mode", "[UXA] 蓝图复制时选择所有建筑"); I18N.Add(KEYSelectAllBuildingsInBlueprintCopy, "[UXA] Select all buildings in Blueprint Copy Mode", "[UXA] 蓝图复制时选择所有建筑");
I18N.Add(KEYUPSSpeedDown, "[UXA] Decrease logical frame rate", "[UXA] 降低逻辑帧率"); I18N.Add(KEYUPSSpeedDown, "[UXA] Decrease logical frame rate", "[UXA] 降低逻辑帧率");
@@ -373,7 +335,6 @@ Hold Ctrl/Shift/Alt to change the count rapidly.
I18N.Add(FastFillInToAndTakeOutFromTanks, "Fast fill in to and take out from tanks", "储液罐快速注入和抽取液体"); I18N.Add(FastFillInToAndTakeOutFromTanks, "Fast fill in to and take out from tanks", "储液罐快速注入和抽取液体");
I18N.Add(SpeedRatio, "Speed Ratio", "速度倍率"); I18N.Add(SpeedRatio, "Speed Ratio", "速度倍率");
I18N.Add(CutConveyorBeltWithShortcutKey, "Cut conveyor belt (with shortcut key)", "切割传送带(使用快捷键)"); I18N.Add(CutConveyorBeltWithShortcutKey, "Cut conveyor belt (with shortcut key)", "切割传送带(使用快捷键)");
I18N.Add(ReverseConveyorBeltWithShortcutKey, "Reverse conveyor belt (with shortcut key)", "反转传送带(使用快捷键)");
I18N.Add(ProtectVeinsFromExhaustion, "Protect veins from exhaustion", "保护矿脉不会耗尽"); I18N.Add(ProtectVeinsFromExhaustion, "Protect veins from exhaustion", "保护矿脉不会耗尽");
I18N.Add(ProtectVeinsFromExhaustionTips, """ I18N.Add(ProtectVeinsFromExhaustionTips, """
By default, the vein amount is protected at 100, and oil speed is protected at 1.0/s, you can set them yourself in config file. By default, the vein amount is protected at 100, and oil speed is protected at 1.0/s, you can set them yourself in config file.
@@ -461,7 +422,7 @@ Assembler buffer minimum multiplier: 2
Buffer count for assembling in labs: 6 Buffer count for assembling in labs: 6
Extra buffer count for Self-evolution Labs: 3 Extra buffer count for Self-evolution Labs: 3
Buffer count for researching in labs: 10 Buffer count for researching in labs: 10
Ray Receiver Graviton Lens buffer count: 2 Ray Receiver Graviton Lens buffer count: 20
Ejector Solar Sails buffer count: 20 Ejector Solar Sails buffer count: 20
Silo Rockets buffer count: 20 Silo Rockets buffer count: 20
""", """ """, """
@@ -471,7 +432,7 @@ Silo Rockets buffer count: 20
研究站矩阵合成模式缓存数量:6 研究站矩阵合成模式缓存数量:6
自演化研究站矩阵额外缓冲数量:3 自演化研究站矩阵额外缓冲数量:3
研究站科研模式缓存数量:10 研究站科研模式缓存数量:10
射线接收器透镜缓冲数量:2 射线接收器透镜缓冲数量:20
弹射器太阳能帆缓冲数量:20 弹射器太阳能帆缓冲数量:20
发射井火箭缓冲数量:20 发射井火箭缓冲数量:20
"""); """);
@@ -514,22 +475,6 @@ You can set 2 shortcut keys in Settings panel:
I18N.Add(DismantleAllBuildings, "Dismantle all buildings", "拆除所有建筑"); I18N.Add(DismantleAllBuildings, "Dismantle all buildings", "拆除所有建筑");
I18N.Add(DismantleAllBuildingsConfirm, "This operation will dismantle all buildings on this planet, are you sure?", "此操作将会拆除本行星上的所有建筑,确定吗?"); I18N.Add(DismantleAllBuildingsConfirm, "This operation will dismantle all buildings on this planet, are you sure?", "此操作将会拆除本行星上的所有建筑,确定吗?");
I18N.Add(QuickBuildOrbitalCollectors, "Quick build Orbital Collectors", "快速建造轨道采集器"); I18N.Add(QuickBuildOrbitalCollectors, "Quick build Orbital Collectors", "快速建造轨道采集器");
I18N.Add(QuickBuildMiningMachines, "Quick build Mining Machines", "快速铺设采矿机");
I18N.Add(QuickBuildMiningMachinesTips, "Places ordinary Mining Machine prebuilds at the nearest solid vein group. Allow restoring/burying veins is off by default: only visible nodes are used, and all restoration and burial calculations are skipped. Enable it to restore buried nodes when no building obstructs them and no Dark Fog Planetary Base is nearby, and to allow burying unused nodes to improve total coverage. Searches native collision shapes and maximizes the sum of each miner's vein count, counting shared nodes repeatedly. Every placed miner must retain at least 3 covered nodes after any planned burials. Places the full layout regardless of carried stock; missing miners remain as ghosts awaiting materials. Respects ground and construction range; does not lay belts or power poles. Option changes apply to the next calculation. Click again to cancel the search.", "在最近的固体矿脉生成普通采矿机待建造对象。「允许恢复/掩埋矿物」默认关闭:仅使用可见矿点,跳过所有恢复和掩埋计算。开启后,先恢复未被建筑阻挡且不在黑雾行星基地附近的掩埋矿点,并允许掩埋未被现有矿机使用的矿点来提高总覆盖数。按游戏实际碰撞体搜索布局,以各台矿机覆盖矿点数之和为目标,同一矿点被多台矿机覆盖时重复计数。所有计划掩埋完成后,每台矿机仍须覆盖至少 3 个矿点。布局数量不受库存限制,采矿机不足的位置保留待建造虚影,等待补充材料。遵守地面和建造范围要求,不铺设传送带和电力设施。选项变更从下次计算生效。计算期间再次点击可取消。");
I18N.Add(QuickMinerAllowVeinReform, "Allow restoring/burying veins", "允许恢复/掩埋矿物");
I18N.Add(QuickMinerCancelSearch, "Cancel miner layout search", "取消采矿机布局计算");
I18N.Add(QuickMinerSearching, "Searching for a dense miner layout... Click the button again to cancel.", "正在计算密集采矿机布局,再次点击按钮可取消。");
I18N.Add(QuickMinerCancelled, "Miner layout search cancelled", "已取消采矿机布局计算");
I18N.Add(QuickMinerNeedPlanet, "Land on a rocky planet to place miners.", "请降落到有固体矿脉的行星后再铺设采矿机。");
I18N.Add(QuickMinerNoVeins, "No mineable solid vein group on this planet.", "本行星没有可开采的固体矿脉。");
I18N.Add(QuickMinerNoPlacement, "No valid miner placements with at least 3 nodes each. Move closer to the nearest vein group and check for buildings or water, then try again.", "没有满足每台至少覆盖 3 个矿点的有效位置,请靠近最近的矿脉,并检查建筑和水面阻挡后重试。");
I18N.Add(QuickMinerFailed, "Miner placement stopped. Check the UXAssist log before retrying.", "采矿机铺设已停止,请查看 UXAssist 日志后重试。");
I18N.Add(QuickMinerVeinsChanged, "The veins changed during calculation. Click the button again to recalculate the layout.", "计算期间矿点状态已变化,请再次点击按钮重新计算布局。");
I18N.Add(QuickMinerResult, "Placed {0} Mining Machines; total vein coverage: {1} (shared nodes counted per miner); buried nodes: {2}.", "已铺设 {0} 台采矿机,总覆盖 {1} 个矿点(各台分别计数),掩埋 {2} 个矿点。");
#if DEBUG
I18N.Add(QuickMinerDebugSaved, "Debug data: {0}", "调试数据:{0}");
I18N.Add(QuickMinerDebugFailed, "Could not save debug data. Check the UXAssist log before retrying.", "调试数据保存失败,请查看 UXAssist 日志后重试。");
#endif
I18N.Add(MaximumCountToBuild, "Maximum count to build", "最大建造数量"); I18N.Add(MaximumCountToBuild, "Maximum count to build", "最大建造数量");
I18N.Add(Max, "max", "最大"); I18N.Add(Max, "max", "最大");
I18N.Add(StopEjectorsWhenAvailableNodesAreAllFilledUp, "Stop ejectors when available nodes are all filled up", "可用节点全部造完时停止弹射"); I18N.Add(StopEjectorsWhenAvailableNodesAreAllFilledUp, "Stop ejectors when available nodes are all filled up", "可用节点全部造完时停止弹射");
+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)]
@@ -1,138 +0,0 @@
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using UnityEngine;
using Box = UXAssist.Functions.Factory.MinerPlacementGeometry.Box;
using Candidate = UXAssist.Functions.Factory.MinerPlacementSolver.Candidate;
namespace UXAssist.Functions.Factory;
// Use the same serializer in game and offline checks. Unity's JsonUtility omits fields whose
// types are internal, including arrays of these nested records, without reporting an error.
internal static class MinerPlacementDebug
{
[Serializable]
internal sealed class Snapshot
{
public int schema = 4;
public string algorithm = "parallel-repack-v5-pose-exploration-min3-unlimited-stock-target-group";
public int minimumCoverage = MinerPlacementSolver.MinimumCoverage;
public string version, gameVersion, startedUtc, outcome, error;
public int planetId, veinType, veinGroup, initialStock, placedCount, totalCoverage, buriedCount;
public int logicalProcessors, workerCount;
public float planetRadius, buildRange;
public bool unlimitedRange, allowVeinReform;
public long elapsedMilliseconds;
public float[] playerPosition, center, right, forward;
public Node[] nodes;
public Collider[] buildColliders, minerColliders, obstacles;
public ExistingMiner[] existingMiners;
public CandidateData[] candidates;
public Phase[] phases;
public Placement[] placements;
public Rejections rejections = new();
}
[Serializable]
internal sealed class Node
{
public int id, type;
public bool target, visible, canBury;
public float[] originalPosition, position;
public Collider collider;
}
[Serializable]
internal sealed class Collider
{
public int idType, link;
public float[] position, extents, rotation;
public float radius;
public static Collider Capture(ColliderData value) => new()
{
idType = value.idType, link = value.link, position = Vector(value.pos),
extents = Vector(value.ext), rotation = Rotation(value.q), radius = value.radius
};
public ColliderData Restore() => new()
{
idType = idType, link = link, pos = ReadVector(position), ext = ReadVector(extents),
q = ReadRotation(rotation), radius = radius
};
}
[Serializable]
internal sealed class ExistingMiner
{
public int entityId, minerId;
public bool prebuild;
public float[] position, rotation;
public int[] veins;
}
[Serializable]
internal sealed class CandidateData
{
public float x, z, yaw, radius;
public float[] position, rotation;
public int[] covered, buried;
public static CandidateData Capture(Candidate value) => new()
{
x = value.X, z = value.Z, yaw = value.Yaw, radius = value.Radius,
position = Vector(value.Position), rotation = Rotation(value.Rotation),
covered = value.Covered, buried = value.Buried
};
public Candidate Restore(Collider[] build, Collider[] obstacles)
{
var result = new Candidate
{
X = x, Z = z, Yaw = yaw, Radius = radius, Position = ReadVector(position), Rotation = ReadRotation(rotation),
Covered = covered, Buried = buried, BuildBoxes = new Box[build.Length], ObstacleBoxes = new Box[obstacles.Length]
};
for (var i = 0; i < build.Length; i++)
result.BuildBoxes[i] = new Box(build[i].Restore().BindToObject(0, 0, EObjectType.None, result.Position, result.Rotation));
for (var i = 0; i < obstacles.Length; i++)
result.ObstacleBoxes[i] = new Box(obstacles[i].Restore().BindToObject(0, 0, EObjectType.None, result.Position, result.Rotation));
return result;
}
}
[Serializable]
internal sealed class Phase
{
public string name;
public int candidateCount, passes, score;
public long elapsedMilliseconds, searchMilliseconds;
public int[] selected;
}
[Serializable]
internal sealed class Placement
{
public int candidate, prebuildId, coverObjectId, itemRequired;
public string outcome, nativeCondition;
public int[] nativeVeins, plannedVeins, finalVeins;
}
[Serializable]
internal sealed class Rejections
{
public int attempted, range, clearance, mixedType, noCoverage, veinCollision, buildingCollision, ground;
}
public static float[] Vector(Vector3 value) => [value.x, value.y, value.z];
public static float[] Rotation(Quaternion value) => [value.x, value.y, value.z, value.w];
internal static void Write(string path, Snapshot snapshot)
{
using var stream = File.Create(path);
var serializer = new DataContractJsonSerializer(typeof(Snapshot), new DataContractJsonSerializerSettings { MaxItemsInObjectGraph = int.MaxValue });
serializer.WriteObject(stream, snapshot);
}
private static Vector3 ReadVector(float[] value) => new(value[0], value[1], value[2]);
private static Quaternion ReadRotation(float[] value) => new(value[0], value[1], value[2], value[3]);
}
@@ -1,124 +0,0 @@
using UnityEngine;
namespace UXAssist.Functions.Factory;
// Work with individual native colliders, never a bounding rectangle around the miner's feet.
internal static class MinerPlacementGeometry
{
internal readonly struct Box
{
public readonly Vector3 Center, Extents, X, Y, Z, Bounds;
public Box(ColliderData collider)
{
Center = collider.pos;
Extents = collider.ext;
X = collider.q * Vector3.right;
Y = collider.q * Vector3.up;
Z = collider.q * Vector3.forward;
Bounds = new Vector3(
Mathf.Abs(X.x) * Extents.x + Mathf.Abs(Y.x) * Extents.y + Mathf.Abs(Z.x) * Extents.z,
Mathf.Abs(X.y) * Extents.x + Mathf.Abs(Y.y) * Extents.y + Mathf.Abs(Z.y) * Extents.z,
Mathf.Abs(X.z) * Extents.x + Mathf.Abs(Y.z) * Extents.y + Mathf.Abs(Z.z) * Extents.z);
}
public Vector3 ToLocal(Vector3 point)
{
var offset = point - Center;
return new Vector3(Vector3.Dot(offset, X), Vector3.Dot(offset, Y), Vector3.Dot(offset, Z));
}
}
public static bool Intersects(in Box a, in Box b)
{
var delta = b.Center - a.Center;
// Reject distant individual colliders before the full separating-axis test. This
// does not replace the independent foot colliders with one enclosing footprint.
if (Mathf.Abs(delta.x) > a.Bounds.x + b.Bounds.x + 0.00001f ||
Mathf.Abs(delta.y) > a.Bounds.y + b.Bounds.y + 0.00001f ||
Mathf.Abs(delta.z) > a.Bounds.z + b.Bounds.z + 0.00001f) return false;
if (Separated(a.X, delta, a, b) || Separated(a.Y, delta, a, b) || Separated(a.Z, delta, a, b) ||
Separated(b.X, delta, a, b) || Separated(b.Y, delta, a, b) || Separated(b.Z, delta, a, b)) return false;
return !Separated(Vector3.Cross(a.X, b.X), delta, a, b) &&
!Separated(Vector3.Cross(a.X, b.Y), delta, a, b) &&
!Separated(Vector3.Cross(a.X, b.Z), delta, a, b) &&
!Separated(Vector3.Cross(a.Y, b.X), delta, a, b) &&
!Separated(Vector3.Cross(a.Y, b.Y), delta, a, b) &&
!Separated(Vector3.Cross(a.Y, b.Z), delta, a, b) &&
!Separated(Vector3.Cross(a.Z, b.X), delta, a, b) &&
!Separated(Vector3.Cross(a.Z, b.Y), delta, a, b) &&
!Separated(Vector3.Cross(a.Z, b.Z), delta, a, b);
}
private static bool Separated(Vector3 axis, Vector3 delta, in Box a, in Box b)
{
if (axis.sqrMagnitude < 1e-10f) return false;
var radius = a.Extents.x * Mathf.Abs(Vector3.Dot(axis, a.X)) +
a.Extents.y * Mathf.Abs(Vector3.Dot(axis, a.Y)) +
a.Extents.z * Mathf.Abs(Vector3.Dot(axis, a.Z)) +
b.Extents.x * Mathf.Abs(Vector3.Dot(axis, b.X)) +
b.Extents.y * Mathf.Abs(Vector3.Dot(axis, b.Y)) +
b.Extents.z * Mathf.Abs(Vector3.Dot(axis, b.Z));
return Mathf.Abs(Vector3.Dot(delta, axis)) > radius;
}
public static bool Intersects(in Box box, ColliderData collider)
{
switch (collider.shape)
{
case EColliderShape.Box:
return Intersects(box, new Box(collider));
case EColliderShape.Sphere:
return PointDistanceSquared(box.ToLocal(collider.pos), box.Extents) <= collider.radius * collider.radius;
case EColliderShape.Capsule:
return SegmentDistanceSquared(box.ToLocal(collider.pos - collider.ext),
box.ToLocal(collider.pos + collider.ext), box.Extents) <= collider.radius * collider.radius;
default:
return true;
}
}
private static float PointDistanceSquared(Vector3 p, Vector3 ext)
{
var x = Mathf.Max(0f, Mathf.Abs(p.x) - ext.x);
var y = Mathf.Max(0f, Mathf.Abs(p.y) - ext.y);
var z = Mathf.Max(0f, Mathf.Abs(p.z) - ext.z);
return x * x + y * y + z * z;
}
// The distance is quadratic between the segment's crossings of the six box planes.
// Minimize each interval exactly, including zero-length segments and parallel axes.
internal static float SegmentDistanceSquared(Vector3 start, Vector3 end, Vector3 ext)
{
var direction = end - start;
var best = Mathf.Min(PointDistanceSquared(start, ext), PointDistanceSquared(end, ext));
var t = 0f;
for (var interval = 0; interval < 7 && t < 1f; interval++)
{
var next = 1f;
for (var axis = 0; axis < 3; axis++)
{
var d = direction[axis];
if (Mathf.Abs(d) < 1e-10f) continue;
var low = (-ext[axis] - start[axis]) / d;
var high = (ext[axis] - start[axis]) / d;
if (low > t && low < next) next = low;
if (high > t && high < next) next = high;
}
var midpoint = start + direction * ((t + next) * 0.5f);
var a = 0f;
var b = 0f;
for (var axis = 0; axis < 3; axis++)
{
if (Mathf.Abs(midpoint[axis]) <= ext[axis]) continue;
var boundary = midpoint[axis] < 0f ? -ext[axis] : ext[axis];
a += direction[axis] * direction[axis];
b += direction[axis] * (start[axis] - boundary);
}
var closest = a > 0f ? Mathf.Clamp(-b / a, t, next) : t;
best = Mathf.Min(best, PointDistanceSquared(start + direction * closest, ext));
t = next;
}
return best;
}
}
@@ -1,552 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
namespace UXAssist.Functions.Factory;
internal sealed class MinerPlacementSolver
{
internal const int MinimumCoverage = 3;
// Coordinated repacking replaces at most this many nearby miners at once.
private const int RegionSize = 3;
public static int WorkerCount => GetWorkerCount(Environment.ProcessorCount);
internal static int GetWorkerCount(int processors) => Math.Min(4, Math.Max(0, processors / 2));
internal sealed class Candidate
{
public float X, Z, Yaw, Radius;
public Vector3 Position;
public Quaternion Rotation;
public MinerPlacementGeometry.Box[] BuildBoxes, ObstacleBoxes;
// Covered excludes this candidate's own buried nodes. Repeated coverage is intentional.
public int[] Covered, Buried;
}
private readonly List<Candidate> _candidates;
private readonly int _nodeCount;
private readonly bool _allowVeinReform;
private int _bestBuriedCount;
public List<Candidate> Best { get; private set; } = [];
public int BestScore { get; private set; }
// With reform disabled, the caller supplies only burial-free candidates.
public MinerPlacementSolver(List<Candidate> candidates, int nodeCount, bool allowVeinReform = true)
{
_candidates = candidates;
_nodeCount = nodeCount;
_allowVeinReform = allowVeinReform;
}
public IEnumerator Search(int passes) => Search(passes, 0, CancellationToken.None);
public Task SearchAsync(int passes, CancellationToken cancellationToken, int workers = 4)
{
workers = Math.Min(workers, WorkerCount);
if (workers <= 0) throw new InvalidOperationException("Use the main-thread search when no worker is available.");
// The caller must not mutate candidates until this task has completed. Workers only
// read captured geometry; no Unity physics, game objects, or factory state is accessed.
return Task.Run(() => Drain(Search(passes, workers, cancellationToken), cancellationToken), cancellationToken);
}
private IEnumerator Search(int passes, int workers, CancellationToken cancellationToken)
{
// Keep a burial-free baseline, explore different packing orders, then try individual
// replacements before the more expensive coordinated neighborhood search.
var results = new SearchResult[passes];
var work = RunBatch(passes, pass => GreedyPass(pass, null, null, -1, results, pass, cancellationToken), workers, cancellationToken);
while (work.MoveNext()) yield return null;
foreach (var result in results) Accept(result);
// Candidate indices shift when a few poses become invalid. Duplicated poses also
// get extra lottery tickets with index-based jitter. Keep the existing starts and
// add pose-based starts whose priorities survive filtering and duplicate candidates.
var keys = new uint[_candidates.Count];
for (var i = 0; i < keys.Length; i++)
{
if ((i & 127) == 0) { cancellationToken.ThrowIfCancellationRequested(); yield return null; }
keys[i] = PoseKey(_candidates[i]);
}
results = new SearchResult[Math.Max(0, passes - 2)];
work = RunBatch(results.Length, index => GreedyPass(index + 2, keys, null, -1, results, index, cancellationToken), workers, cancellationToken);
while (work.MoveNext()) yield return null;
foreach (var result in results) Accept(result);
var seeds = new SeedCollisions(_candidates.Count);
work = TrackBest(seeds, workers, cancellationToken);
while (work.MoveNext()) yield return null;
results = new SearchResult[seeds.Seeds.Count];
work = RunBatch(results.Length, index => GreedyPass(0, null, seeds, index, results, index, cancellationToken), workers, cancellationToken);
while (work.MoveNext()) yield return null;
foreach (var result in results) Accept(result);
for (var round = 0; round < 2 && Best.Count > 0; round++)
{
work = TrackBest(seeds, workers, cancellationToken);
while (work.MoveNext()) yield return null;
work = Repack(seeds, workers, cancellationToken);
while (work.MoveNext()) yield return null;
if (ReferenceEquals(seeds.Seeds, Best)) break;
}
// A local replacement can open space beyond its neighborhood. Saturate the full
// candidate set once more, preserving every selected miner's minimum coverage.
work = TrackBest(seeds, workers, cancellationToken);
while (work.MoveNext()) yield return null;
results = new SearchResult[1];
work = GreedyPass(0, null, seeds, -1, results, 0, cancellationToken);
while (work.MoveNext()) yield return null;
Accept(results[0]);
}
private static uint PoseKey(Candidate candidate)
{
// Quantize only the exploration key, never the geometry or collision tests.
var x = (int)Math.Round(candidate.X * 1000f);
var z = (int)Math.Round(candidate.Z * 1000f);
var yaw = (int)Math.Round(((candidate.Yaw % 360f + 360f) % 360f) * 10f);
return unchecked((uint)(x * 73856093 ^ z * 19349663 ^ yaw * 83492791));
}
// Without seeds, fill an empty layout in the exploration order of pass, keyed by candidate
// index or by keys. With seeds, keep every seed except removed (all when negative) and
// refill greedily.
private IEnumerator GreedyPass(int pass, uint[] keys, SeedCollisions seeds, int removed, SearchResult[] results, int resultIndex,
CancellationToken cancellationToken)
{
var layout = new Layout(_nodeCount, _allowVeinReform);
// Selected miners already proven compatible with each candidate, or -1 once it cannot
// join. Layouts and burials only grow during a pass, so every exclusion is permanent.
var verified = new int[_candidates.Count];
if (seeds != null)
{
for (var i = 0; i < seeds.Seeds.Count; i++)
if (i != removed) layout.Add(seeds.Seeds[i]);
for (var i = 0; i < verified.Length; i++)
verified[i] = (removed >= 0 && ReferenceEquals(_candidates[i], seeds.Seeds[removed])) || !seeds.AllowsWithout(i, removed)
? -1 : layout.Selected.Count;
}
else if (_allowVeinReform && pass == 0)
{
for (var i = 0; i < verified.Length; i++)
if (_candidates[i].Buried.Length != 0) verified[i] = -1;
}
while (true)
{
Candidate chosen = null;
var priority = float.NegativeInfinity;
for (var i = 0; i < _candidates.Count; i++)
{
if ((i & 127) == 0)
{
cancellationToken.ThrowIfCancellationRequested();
yield return null;
}
if (verified[i] < 0) continue;
var candidate = _candidates[i];
var gain = layout.Gain(candidate, out var coverage);
if (coverage < MinimumCoverage)
{
verified[i] = -1;
continue;
}
if (gain <= 0) continue;
var jitter = 1f;
if (seeds == null && pass > 1)
{
// Deterministic exploration without depending on the game's random stream.
var hash = (keys?[i] ?? unchecked((uint)((i + 1) * 73856093))) ^
unchecked((uint)((pass + 1) * 19349663 ^ (layout.Selected.Count + 1) * 83492791));
hash ^= hash >> 16;
hash = unchecked(hash * 0x7feb352dU);
hash ^= hash >> 15;
hash = unchecked(hash * 0x846ca68bU);
hash ^= hash >> 16;
jitter = 0.65f + (hash & 65535) / 65535f * 0.7f;
}
var value = gain * jitter;
if (_allowVeinReform) value -= candidate.Buried.Length * 0.0001f;
if (value <= priority) continue;
if (!layout.FitsFrom(candidate, verified[i]) || !layout.PreservesCoverage(candidate))
{
verified[i] = -1;
continue;
}
verified[i] = layout.Selected.Count;
chosen = candidate;
priority = value;
}
if (chosen == null) break;
layout.Add(chosen);
}
results[resultIndex] = new SearchResult(layout.Selected, layout.Score, layout.BuriedCount);
}
private static void Drain(IEnumerator work, CancellationToken cancellationToken)
{
try { while (work.MoveNext()) cancellationToken.ThrowIfCancellationRequested(); }
finally { (work as IDisposable)?.Dispose(); }
}
private static IEnumerator RunBatch(int count, Func<int, IEnumerator> create, int workers, CancellationToken cancellationToken)
{
if (workers > 0)
{
Parallel.For(0, count, new ParallelOptions { MaxDegreeOfParallelism = workers, CancellationToken = cancellationToken },
index => Drain(create(index), cancellationToken));
}
else for (var i = 0; i < count; i++)
{
var work = create(i);
try { while (work.MoveNext()) yield return null; }
finally { (work as IDisposable)?.Dispose(); }
}
}
private sealed class SearchResult(List<Candidate> selected, int score, int buriedCount)
{
public List<Candidate> Selected = selected;
public int Score = score, BuriedCount = buriedCount;
}
// Accept replaces Best with a new list only for a strictly better layout, so an unchanged
// reference means no improvement.
private void Accept(SearchResult result)
{
if (!IsBetter(result.Score, result.BuriedCount, result.Selected.Count, BestScore, _bestBuriedCount, Best.Count)) return;
Best = result.Selected;
BestScore = result.Score;
_bestBuriedCount = result.BuriedCount;
}
private static bool IsBetter(int score, int buried, int count, int bestScore, int bestBuried, int bestCount) =>
score > bestScore || score == bestScore && (buried < bestBuried || buried == bestBuried && count < bestCount);
// A legal crossing may require moving several miners together. Removing only one and
// greedily refilling cannot escape that local optimum. Repack up to three nearby miners
// with bounded, spatially diverse alternatives, enumerating their compatible combinations.
private IEnumerator Repack(SeedCollisions seeds, int workers, CancellationToken cancellationToken)
{
var regions = Regions(seeds.Seeds);
var results = new SearchResult[regions.Count];
for (var i = 0; i < results.Length; i++) results[i] = new SearchResult(Best, BestScore, _bestBuriedCount);
var work = RunBatch(regions.Count, index => RepackRegion(seeds, regions[index], results[index], cancellationToken), workers, cancellationToken);
while (work.MoveNext()) yield return null;
// Merge in the original region order, independent of worker completion order.
foreach (var result in results) Accept(result);
}
// Each miner alone, with each of its three nearest neighbors, and with each pair of them.
private static List<(int, int, int)> Regions(List<Candidate> seeds)
{
var regions = new List<(int, int, int)>();
var unique = new HashSet<(int, int, int)>();
for (var pivot = 0; pivot < seeds.Count; pivot++)
{
Add((pivot, -1, -1));
var neighbors = new List<int>();
for (var i = 0; i < seeds.Count; i++) if (i != pivot) neighbors.Add(i);
neighbors.Sort((a, b) => (seeds[a].Position - seeds[pivot].Position).sqrMagnitude.CompareTo(
(seeds[b].Position - seeds[pivot].Position).sqrMagnitude));
if (neighbors.Count > 3) neighbors.RemoveRange(3, neighbors.Count - 3);
foreach (var neighbor in neighbors) Add((Math.Min(pivot, neighbor), Math.Max(pivot, neighbor), -1));
for (var a = 0; a < neighbors.Count; a++)
for (var b = a + 1; b < neighbors.Count; b++)
{
var indices = new[] { pivot, neighbors[a], neighbors[b] };
Array.Sort(indices);
Add((indices[0], indices[1], indices[2]));
}
}
return regions;
void Add((int, int, int) region)
{
if (unique.Add(region)) regions.Add(region);
}
}
private static bool InRegion(int seed, (int, int, int) region) => seed == region.Item1 || seed == region.Item2 || seed == region.Item3;
// Seed passes, repacking regions and the final refill keep a subset of the same seeds. Find
// the seeds that block each candidate once per seed set, instead of repeating the SAT tests.
private sealed class SeedCollisions(int candidateCount)
{
public List<Candidate> Seeds;
// Counts saturate past RegionSize: no single removal can free such a candidate.
public readonly byte[] Counts = new byte[candidateCount];
public readonly int[] Blockers = new int[candidateCount * RegionSize];
// A negative seed removes nothing, so only unblocked candidates qualify.
public bool AllowsWithout(int candidate, int seed) =>
Counts[candidate] == 0 || Counts[candidate] == 1 && Blockers[candidate * RegionSize] == seed;
public bool Allows(int candidate, (int, int, int) region)
{
var count = Counts[candidate];
if (count > RegionSize) return false;
for (var i = 0; i < count; i++)
if (!InRegion(Blockers[candidate * RegionSize + i], region)) return false;
return true;
}
}
// Best is replaced, never mutated, so an unchanged reference keeps the collisions valid.
private IEnumerator TrackBest(SeedCollisions seeds, int workers, CancellationToken cancellationToken)
{
if (ReferenceEquals(seeds.Seeds, Best)) yield break;
seeds.Seeds = Best;
var chunks = Math.Max(1, workers * 4);
var size = (_candidates.Count + chunks - 1) / chunks;
var work = RunBatch(chunks, chunk => FindCollisions(seeds, chunk * size, Math.Min(_candidates.Count, (chunk + 1) * size), cancellationToken),
workers, cancellationToken);
while (work.MoveNext()) yield return null;
}
private IEnumerator FindCollisions(SeedCollisions seeds, int start, int end, CancellationToken cancellationToken)
{
for (var i = start; i < end; i++)
{
if (((i - start) & 31) == 0)
{
cancellationToken.ThrowIfCancellationRequested();
yield return null;
}
var count = 0;
for (var seed = 0; seed < seeds.Seeds.Count && count <= RegionSize; seed++)
{
if (PairFits(_candidates[i], seeds.Seeds[seed])) continue;
if (count < RegionSize) seeds.Blockers[i * RegionSize + count] = seed;
count++;
}
seeds.Counts[i] = (byte)count;
}
}
private IEnumerator RepackRegion(SeedCollisions seeds, (int, int, int) region, SearchResult result, CancellationToken cancellationToken)
{
var layout = new Layout(_nodeCount, _allowVeinReform);
var removed = new List<Candidate>();
var centerX = 0f;
var centerZ = 0f;
for (var i = 0; i < seeds.Seeds.Count; i++)
{
var seed = seeds.Seeds[i];
if (!InRegion(i, region)) layout.Add(seed);
else
{
removed.Add(seed);
centerX += seed.X;
centerZ += seed.Z;
}
}
centerX /= removed.Count;
centerZ /= removed.Count;
var buckets = new List<(Candidate Candidate, int Gain)>[8];
for (var b = 0; b < buckets.Length; b++) buckets[b] = [];
for (var i = 0; i < _candidates.Count; i++)
{
if ((i & 127) == 0)
{
cancellationToken.ThrowIfCancellationRequested();
yield return null;
}
var candidate = _candidates[i];
if (candidate.Covered.Length < MinimumCoverage) continue;
var nearby = false;
foreach (var seed in removed)
if ((candidate.Position - seed.Position).sqrMagnitude <= 36f) { nearby = true; break; }
if (!nearby || !seeds.Allows(i, region)) continue;
var angle = Math.Atan2(candidate.Z - centerZ, candidate.X - centerX) + Math.PI;
var bucket = Math.Min(7, (int)(angle * 4 / Math.PI));
buckets[bucket].Add((candidate, layout.Gain(candidate, out _)));
}
var options = new List<Candidate>(removed);
foreach (var bucket in buckets)
{
bucket.Sort((a, b) => b.Gain.CompareTo(a.Gain));
var taken = 0;
foreach (var entry in bucket)
{
var candidate = entry.Candidate;
var duplicate = false;
foreach (var option in options)
{
var yaw = Math.Abs(candidate.Yaw - option.Yaw) % 360f;
if ((candidate.Position - option.Position).sqrMagnitude < 0.45f * 0.45f && Math.Min(yaw, 360f - yaw) < 6f)
{ duplicate = true; break; }
}
if (duplicate) continue;
options.Add(candidate);
if (++taken == 12) break;
}
}
options.Sort((a, b) => b.Covered.Length.CompareTo(a.Covered.Length));
// Pruning skips most option pairs, so test their collisions only when reached.
var pairs = new sbyte[options.Count * options.Count];
var operations = 0;
for (var i = 0; i < options.Count; i++)
{
if (!layout.CanAdd(options[i])) continue;
layout.Add(options[i]);
Consider(layout, result);
for (var j = i + 1; j < options.Count; j++)
{
if ((operations++ & 127) == 0)
{
cancellationToken.ThrowIfCancellationRequested();
yield return null;
}
if (layout.RawScore + (RegionSize - 1) * options[j].Covered.Length < result.Score) break;
if (!Compatible(i, j) || !layout.CanAdd(options[j])) continue;
layout.Add(options[j]);
Consider(layout, result);
for (var k = j + 1; k < options.Count; k++)
{
if ((operations++ & 127) == 0)
{
cancellationToken.ThrowIfCancellationRequested();
yield return null;
}
if (layout.RawScore + options[k].Covered.Length < result.Score) break;
if (!Compatible(i, k) || !Compatible(j, k) || !layout.CanAdd(options[k])) continue;
layout.Add(options[k]);
Consider(layout, result);
layout.RemoveLast();
}
layout.RemoveLast();
}
layout.RemoveLast();
}
bool Compatible(int first, int second)
{
var slot = first * options.Count + second;
if (pairs[slot] == 0) pairs[slot] = PairFits(options[first], options[second]) ? (sbyte)1 : (sbyte)-1;
return pairs[slot] > 0;
}
}
// A partial layout. Score counts each visible node once per covering miner; RawScore
// ignores burials and is therefore an upper bound for pruning.
private sealed class Layout(int nodeCount, bool allowVeinReform)
{
public readonly List<Candidate> Selected = [];
private readonly int[] _buried = allowVeinReform ? new int[nodeCount] : null,
_uses = allowVeinReform ? new int[nodeCount] : null;
public int Score, RawScore, BuriedCount;
public int Gain(Candidate candidate, out int coverage)
{
coverage = Coverage(candidate);
if (_buried == null) return coverage;
var gain = coverage;
foreach (var index in candidate.Buried) if (_buried[index] == 0) gain -= _uses[index];
return gain;
}
private int Coverage(Candidate candidate)
{
if (_buried == null) return candidate.Covered.Length;
var coverage = 0;
foreach (var index in candidate.Covered) if (_buried[index] == 0) coverage++;
return coverage;
}
public bool CanAdd(Candidate candidate) => Coverage(candidate) >= MinimumCoverage && PreservesCoverage(candidate);
public bool FitsFrom(Candidate candidate, int start)
{
for (var i = start; i < Selected.Count; i++)
if (!PairFits(candidate, Selected[i])) return false;
return true;
}
// A placement must not invalidate an earlier miner, even if the total gain is positive.
// Every selected miner already keeps the minimum, so only newly buried used nodes matter.
public bool PreservesCoverage(Candidate candidate)
{
if (_buried == null) return true;
var affected = false;
foreach (var index in candidate.Buried)
if (_buried[index] == 0 && _uses[index] > 0) { affected = true; break; }
if (!affected) return true;
foreach (var other in Selected)
{
var visible = 0;
foreach (var index in other.Covered)
if (_buried[index] == 0 && Array.IndexOf(candidate.Buried, index) < 0 && ++visible >= MinimumCoverage) break;
if (visible < MinimumCoverage) return false;
}
return true;
}
public void Add(Candidate candidate)
{
RawScore += candidate.Covered.Length;
if (_buried == null)
{
Score = RawScore;
Selected.Add(candidate);
return;
}
foreach (var index in candidate.Buried)
if (_buried[index]++ == 0) { Score -= _uses[index]; BuriedCount++; }
foreach (var index in candidate.Covered)
{
if (_buried[index] == 0) Score++;
_uses[index]++;
}
Selected.Add(candidate);
}
public void RemoveLast()
{
var candidate = Selected[Selected.Count - 1];
Selected.RemoveAt(Selected.Count - 1);
RawScore -= candidate.Covered.Length;
if (_buried == null)
{
Score = RawScore;
return;
}
foreach (var index in candidate.Covered)
{
if (_buried[index] == 0) Score--;
_uses[index]--;
}
foreach (var index in candidate.Buried)
if (--_buried[index] == 0) { Score += _uses[index]; BuriedCount--; }
}
}
private static void Consider(Layout layout, SearchResult result)
{
if (!IsBetter(layout.Score, layout.BuriedCount, layout.Selected.Count, result.Score, result.BuriedCount, result.Selected.Count)) return;
result.Selected = new List<Candidate>(layout.Selected);
result.Score = layout.Score;
result.BuriedCount = layout.BuriedCount;
}
public static bool Fits(Candidate candidate, List<Candidate> selected)
{
foreach (var other in selected)
{
if (!PairFits(candidate, other)) return false;
}
return true;
}
private static bool PairFits(Candidate candidate, Candidate other)
{
var radius = candidate.Radius + other.Radius;
return (candidate.Position - other.Position).sqrMagnitude > radius * radius ||
!Intersects(candidate.BuildBoxes, other.ObstacleBoxes) && !Intersects(other.BuildBoxes, candidate.ObstacleBoxes);
}
private static bool Intersects(MinerPlacementGeometry.Box[] a, MinerPlacementGeometry.Box[] b)
{
for (var i = 0; i < a.Length; i++)
for (var j = 0; j < b.Length; j++)
if (MinerPlacementGeometry.Intersects(in a[i], in b[j])) return true;
return false;
}
}
File diff suppressed because it is too large. Load diff
+18 -37
View File
@@ -24,43 +24,6 @@ public static class FactoryFunctions
cargoTraffic.AlterBeltConnections(beltId, 0, i0, i1, i2); cargoTraffic.AlterBeltConnections(beltId, 0, i0, i1, i2);
} }
public static void ReverseConveyorBelt(PlanetFactory factory, int beltId)
{
var traffic = factory?.cargoTraffic;
var player = GameMain.mainPlayer;
var window = UIRoot.instance?.uiGame?.beltWindow;
if (traffic == null || player == null || window == null || beltId <= 0 || beltId >= traffic.beltPool.Length) return;
ref var belt = ref traffic.beltPool[beltId];
if (belt.id != beltId) return;
var path = traffic.GetCargoPath(belt.segPathId);
// Match the native reverse button's limit of 2 to 1023 belts in one path.
const int maxBeltCount = 1023;
if (path == null || path.belts.Count < 2 || path.belts.Count > maxBeltCount) return;
var oldFactory = window.factory;
var oldTraffic = window.traffic;
var oldPlayer = window.player;
var oldBeltId = window._beltId;
try
{
window.factory = factory;
window.traffic = traffic;
window.player = player;
// The beltId setter refreshes the visible inspector, so bind the backing field directly.
window._beltId = beltId;
// Nebula intercepts this native entry point to synchronize reversals.
window.OnReverseButtonClick(0);
}
finally
{
window._beltId = oldBeltId;
window.factory = oldFactory;
window.traffic = oldTraffic;
window.player = oldPlayer;
}
}
public static bool ObjectIsBeltOrInserter(PlanetFactory factory, int objId) public static bool ObjectIsBeltOrInserter(PlanetFactory factory, int objId)
{ {
if (objId == 0) return false; if (objId == 0) return false;
@@ -129,8 +92,26 @@ public static class FactoryFunctions
buildPreviewsToRemove.Insert(~index, connObjId); buildPreviewsToRemove.Insert(~index, connObjId);
} }
} }
var entityPool = factory.entityPool;
var stationPool = factory.transport.stationPool;
foreach (var objId in buildPreviewsToRemove) foreach (var objId in buildPreviewsToRemove)
{ {
if (objId > 0)
{
int stationId = entityPool[objId].stationId;
if (stationId > 0)
{
StationComponent sc = stationPool[stationId];
if (sc is null || sc.id != stationId) continue;
for (int i = 0; i < sc.storage.Length; i++)
{
int added = player.TryAddItemToPackage(sc.storage[i].itemId, sc.storage[i].count, sc.storage[i].inc, true, objId);
if (added > 0) UIItemup.Up(sc.storage[i].itemId, added);
}
sc.storage = new StationStore[sc.storage.Length];
sc.needs = new int[sc.needs.Length];
}
}
build.DoDismantleObject(objId); build.DoDismantleObject(objId);
} }
blueprintCopyTool.ClearSelection(); blueprintCopyTool.ClearSelection();
+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
+54 -110
View File
@@ -25,25 +25,25 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
Inspectors.Clear(); Inspectors.Clear();
} }
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnCreate))] [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnCreate")]
private static void OnCreate(UIBlueprintInspector __instance) private static void OnCreate(UIBlueprintInspector __instance)
{ {
GetControls(__instance); GetControls(__instance);
} }
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnOpen))] [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnOpen")]
private static void OnOpen(UIBlueprintInspector __instance) private static void OnOpen(UIBlueprintInspector __instance)
{ {
GetControls(__instance)?.ResetSession(); GetControls(__instance)?.ResetSession();
} }
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnClose))] [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnClose")]
private static void OnClose(UIBlueprintInspector __instance) private static void OnClose(UIBlueprintInspector __instance)
{ {
if (Inspectors.TryGetValue(__instance, out var controls)) controls.ResetSession(); if (Inspectors.TryGetValue(__instance, out var controls)) controls.ResetSession();
} }
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnFree))] [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnFree")]
private static void OnFree(UIBlueprintInspector __instance) private static void OnFree(UIBlueprintInspector __instance)
{ {
if (!Inspectors.TryGetValue(__instance, out var controls)) return; if (!Inspectors.TryGetValue(__instance, out var controls)) return;
@@ -51,7 +51,7 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
Inspectors.Remove(__instance); Inspectors.Remove(__instance);
} }
[HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), nameof(UIBlueprintInspector._OnDestroy))] [HarmonyPostfix, HarmonyPatch(typeof(UIBlueprintInspector), "_OnDestroy")]
private static void OnDestroy(UIBlueprintInspector __instance) private static void OnDestroy(UIBlueprintInspector __instance)
{ {
OnFree(__instance); OnFree(__instance);
@@ -102,81 +102,38 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
private sealed class InspectorControls private sealed class InspectorControls
{ {
private const float Left = 12f; private const float Left = 22f;
private const float ControlsGap = 12f; private const float ControlsGap = 12f;
private readonly UIBlueprintInspector _inspector; private readonly UIBlueprintInspector _inspector;
private RectTransform _panel; private readonly float _controlsHeight;
private UIButton _entry;
private Text _entryText;
private UIButton _button; private UIButton _button;
private Text _buttonText; private Text _buttonText;
private UIButton _cancelButton;
private Text _cancelText;
private MyCheckBox _checkbox; private MyCheckBox _checkbox;
private MyCornerComboBox _basisCombo;
private Text _basisLabel;
private UIButton _basisHelp;
private BlueprintData _currentBlueprint; private BlueprintData _currentBlueprint;
private bool _manualProliferation; private bool _manualProliferation;
private bool _layoutApplied;
public InspectorControls(UIBlueprintInspector inspector) public InspectorControls(UIBlueprintInspector inspector)
{ {
_inspector = inspector; _inspector = inspector;
try try
{ {
// The native description has a 22px title row above its editable text. _button = LayoutHelper.AddButton(Left, 0, inspector.group1,
_entry = LayoutHelper.AddButton(0, 0, inspector.descGroupTrans,
I18NKeys.BlueprintDescriptionOptions, 13, "blueprint-description-options", ToggleOptions);
_entryText = _entry.transform.Find("button-text").GetComponent<Text>();
_entry.tips = inspector.tipButton2.tips;
_entry.tips.topLevel = true;
Util.NormalizeRectWithTopRight(_entry, 0, 0, inspector.descGroupTrans);
// 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>();
_panel = UnityEngine.Object.Instantiate(source, inspector.rectTrans).rectTransform;
_panel.gameObject.name = "uxassist-blueprint-description-options";
for (var i = _panel.childCount - 1; i >= 0; i--)
{
var child = _panel.GetChild(i).gameObject;
child.SetActive(false);
UnityEngine.Object.Destroy(child);
}
_panel.anchorMin = new Vector2(0, 1);
_panel.anchorMax = Vector2.one;
_panel.pivot = new Vector2(0, 1);
_panel.anchoredPosition = new Vector2(Left, -Left);
_panel.sizeDelta = new Vector2(-Left * 2, 152);
_button = LayoutHelper.AddButton(Left, 12, _panel,
I18NKeys.BlueprintAutoFillDescription, 15, "blueprint-auto-fill-description", Generate); I18NKeys.BlueprintAutoFillDescription, 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, _checkbox = MyCheckBox.CreateCheckBox(Left, 0, inspector.group1, false,
I18NKeys.Cancel, 14, "blueprint-description-cancel", CloseOptions);
_cancelText = _cancelButton.transform.Find("button-text").GetComponent<Text>();
Util.NormalizeRectWithTopRight(_cancelButton, Left, 14, _panel);
_checkbox = MyCheckBox.CreateCheckBox(Left, 52, _panel, false,
I18NKeys.BlueprintProliferation.Translate(), 15).WithSmallerBox(22f); I18NKeys.BlueprintProliferation.Translate(), 15).WithSmallerBox(22f);
_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);
_basisCombo = MyCornerComboBox.CreateComboBox(Left, 108, _panel).WithFontSize(14)
.WithItems(I18NKeys.BlueprintFinalProducts, I18NKeys.BlueprintBottleneckIntermediate)
.WithIndex(0);
var combo = _basisCombo.GetComponent<UIComboBox>();
combo.CanInput = false;
combo.autoWidth = false;
var comboRect = (RectTransform)_basisCombo.transform;
comboRect.anchorMax = Vector2.one;
comboRect.sizeDelta = new Vector2(-Left * 2, 28);
_basisHelp = LayoutHelper.AddTipsButton(Left, 80, _panel,
I18NKeys.BlueprintProductionBasis.Translate(), I18NKeys.BlueprintProductionBasisTip.Translate(), "");
UpdateLabels(); UpdateLabels();
_panel.gameObject.SetActive(false); _controlsHeight = Math.Max(_button.transform.GetComponent<RectTransform>().rect.height,
_checkbox.rectTrans.rect.height) + 10f;
} }
catch catch
{ {
Destroy(); if (_button) UnityEngine.Object.Destroy(_button.gameObject);
if (_checkbox) UnityEngine.Object.Destroy(_checkbox.gameObject);
throw; throw;
} }
} }
@@ -185,72 +142,65 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
{ {
_currentBlueprint = null; _currentBlueprint = null;
_manualProliferation = false; _manualProliferation = false;
_basisCombo.SetIndex(0);
if (_inspector.blueprint != null) SyncDefault(); if (_inspector.blueprint != null) SyncDefault();
else _checkbox.Checked = false; else _checkbox.Checked = false;
CloseOptions();
_entry.gameObject.SetActive(_inspector.blueprint != null);
} }
public void Refresh() public void Refresh()
{ {
SyncDefault(); SyncDefault();
_entry.gameObject.SetActive(_inspector.blueprint != null); if (!_layoutApplied)
_inspector.group1.anchoredPosition += new Vector2(0, -_controlsHeight);
PositionControls();
_inspector.group2.anchoredPosition += new Vector2(0, -_controlsHeight);
_inspector.group3.anchoredPosition += new Vector2(0, -_controlsHeight);
_inspector.group4.anchoredPosition += new Vector2(0, -_controlsHeight);
_inspector.contentTrans.sizeDelta += new Vector2(0, _controlsHeight);
_layoutApplied = true;
} }
private void ToggleOptions()
{
_panel.SetAsLastSibling();
_panel.gameObject.SetActive(!_panel.gameObject.activeSelf);
}
private void CloseOptions() => _panel.gameObject.SetActive(false);
public void UpdateLabels() public void UpdateLabels()
{ {
_entryText.text = I18NKeys.BlueprintDescriptionOptions.Translate();
((RectTransform)_entry.transform).sizeDelta =
new Vector2(Util.GetPreferredWidth(_entryText) + 16, 20);
_entry.tips.tipTitle = I18NKeys.BlueprintAutoFillDescription.Translate();
_entry.tips.tipText = I18NKeys.BlueprintDescriptionOptionsTip.Translate();
_entry.UpdateTip();
_buttonText.text = I18NKeys.BlueprintAutoFillDescription.Translate(); _buttonText.text = I18NKeys.BlueprintAutoFillDescription.Translate();
_cancelText.text = I18NKeys.Cancel.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();
var combo = _basisCombo.GetComponent<UIComboBox>();
var index = combo.itemIndex;
_basisCombo.SetItems(I18NKeys.BlueprintFinalProducts, I18NKeys.BlueprintBottleneckIntermediate);
_basisCombo.SetIndex(index);
_basisHelp.tips.tipTitle = I18NKeys.BlueprintProductionBasis.Translate();
_basisHelp.tips.tipText = I18NKeys.BlueprintProductionBasisTip.Translate();
_basisHelp.UpdateTip();
var width = Math.Max(160f, Util.GetPreferredWidth(_buttonText) + 26f); var width = Math.Max(160f, Util.GetPreferredWidth(_buttonText) + 26f);
_button.transform.GetComponent<RectTransform>().sizeDelta = _button.transform.GetComponent<RectTransform>().sizeDelta =
new Vector2(width, _button.transform.GetComponent<RectTransform>().sizeDelta.y); new Vector2(width, _button.transform.GetComponent<RectTransform>().sizeDelta.y);
var labelWidth = Util.GetPreferredWidth(_basisLabel); if (_layoutApplied) PositionControls();
_basisLabel.rectTransform.sizeDelta = new Vector2(labelWidth, _basisLabel.rectTransform.sizeDelta.y);
Util.NormalizeRectWithTopLeft(_basisHelp, Left + labelWidth + ControlsGap, 80, _panel);
} }
public void Destroy() public void Destroy()
{ {
if (_entry) if (_layoutApplied && _inspector)
{ {
_entry.button.onClick.RemoveListener(ToggleOptions); _inspector.group1.anchoredPosition += new Vector2(0, _controlsHeight);
UnityEngine.Object.Destroy(_entry.gameObject); _inspector.group2.anchoredPosition += new Vector2(0, _controlsHeight);
_inspector.group3.anchoredPosition += new Vector2(0, _controlsHeight);
_inspector.group4.anchoredPosition += new Vector2(0, _controlsHeight);
_inspector.contentTrans.sizeDelta += new Vector2(0, -_controlsHeight);
_layoutApplied = false;
} }
if (_button) if (_button)
{
_button.button.onClick.RemoveListener(Generate); _button.button.onClick.RemoveListener(Generate);
if (_cancelButton) UnityEngine.Object.Destroy(_button.gameObject);
_cancelButton.button.onClick.RemoveListener(CloseOptions); }
if (_checkbox) if (_checkbox)
{
_checkbox.OnChecked -= OnProliferationChecked; _checkbox.OnChecked -= OnProliferationChecked;
if (!_panel) return; UnityEngine.Object.Destroy(_checkbox.gameObject);
_panel.gameObject.SetActive(false); }
UnityEngine.Object.Destroy(_panel.gameObject); }
private void PositionControls()
{
var buttonRect = _button.transform.GetComponent<RectTransform>();
var top = 4f - _controlsHeight;
Util.NormalizeRectWithTopLeft(_button, Left, top, _inspector.group1);
Util.NormalizeRectWithTopLeft(_checkbox, Left + buttonRect.rect.width + ControlsGap,
top + (buttonRect.rect.height - _checkbox.rectTrans.rect.height) / 2f, _inspector.group1);
} }
private void SyncDefault() private void SyncDefault()
@@ -258,7 +208,6 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
var blueprint = _inspector.blueprint; var blueprint = _inspector.blueprint;
if (!ReferenceEquals(blueprint, _currentBlueprint)) if (!ReferenceEquals(blueprint, _currentBlueprint))
{ {
CloseOptions();
_currentBlueprint = blueprint; _currentBlueprint = blueprint;
_manualProliferation = false; _manualProliferation = false;
} }
@@ -317,14 +266,7 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
return; return;
} }
var request = capture.CreateRequest(_checkbox.Checked); var report = new FactoryBlackBoxAnalyzer(catalog).Analyze(capture.CreateRequest(_checkbox.Checked));
request.ProductionBasis = (BlueprintProductionBasis)_basisCombo.GetComponent<UIComboBox>().itemIndex;
var report = new FactoryBlackBoxAnalyzer(catalog).Analyze(request);
if (report.Diagnostics.Any(diagnostic => diagnostic.Code == ProductionDiagnosticCode.BlueprintBasisUnavailable))
{
UIRealtimeTip.Popup(I18NKeys.BlueprintBasisUnavailable.Translate());
return;
}
if (report.Status == ProductionStatus.Failed || report.Status == ProductionStatus.DataNotReady) if (report.Status == ProductionStatus.Failed || report.Status == ProductionStatus.DataNotReady)
{ {
UIRealtimeTip.Popup((report.Status == ProductionStatus.DataNotReady UIRealtimeTip.Popup((report.Status == ProductionStatus.DataNotReady
@@ -345,10 +287,13 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
return; return;
} }
var powerField = new BlueprintDescriptionField(I18NKeys.BlueprintPower.Translate(), var fields = new[]
{
new BlueprintDescriptionField(I18NKeys.BlueprintPower.Translate(),
description.Power.Length > 0 ? description.Power : null, description.Power.Length > 0 ? description.Power : null,
I18NKeys.BlueprintPowerEnglish, I18NKeys.BlueprintPowerChinese); I18NKeys.BlueprintPowerEnglish, I18NKeys.BlueprintPowerChinese)
var result = BlueprintDescriptionFields.TryUpdate(blueprint.externalFields, powerField, };
var result = BlueprintDescriptionFields.TryUpdate(blueprint.externalFields, fields,
UIBlueprintInspector.kMaxFieldCount, UIBlueprintInspector.kMaxFieldCount,
value => BlueprintData.Validate(blueprint.ExternalFieldEscape(value)), value => BlueprintData.Validate(blueprint.ExternalFieldEscape(value)),
blueprint.ExternalFieldUnescape, out var updated); blueprint.ExternalFieldUnescape, out var updated);
@@ -378,7 +323,6 @@ public class BlueprintDescriptionPatch : PatchImpl<BlueprintDescriptionPatch>
throw; throw;
} }
CloseOptions();
if (!report.MaterialComplete || !report.PowerBreakdown.FactoryComplete || if (!report.MaterialComplete || !report.PowerBreakdown.FactoryComplete ||
!report.PowerBreakdown.LogisticsComplete) !report.PowerBreakdown.LogisticsComplete)
UIRealtimeTip.Popup(I18NKeys.BlueprintPartial.Translate()); UIRealtimeTip.Popup(I18NKeys.BlueprintPartial.Translate());
@@ -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
+30 -8
View File
@@ -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();
@@ -57,12 +63,12 @@ internal static class BeltSignalPatch
// A belt selects one material, so its equivalent single-material rate is 30. // A belt selects one material, so its equivalent single-material rate is 30.
private static readonly (int ItemId, int ExchangeRate, string NameKey, string IconPath)[] DarkFogBuyOutDefinitions = private static readonly (int ItemId, int ExchangeRate, string NameKey, string IconPath)[] DarkFogBuyOutDefinitions =
[ [
(ItemIds.DarkFogMatrix, 20, I18NKeys.MemoryUnit, "assets/signal/dark-fog-matrix.png"), (ItemIds.DarkFogMemoryUnit, 20, I18NKeys.MemoryUnit, "assets/signal/dark-fog-matrix.png"),
(ItemIds.DarkFogEnergyShard, 60, I18NKeys.EnergyFragment, "assets/signal/energy-shard.png"), (ItemIds.DarkFogEnergyFragment, 60, I18NKeys.EnergyFragment, "assets/signal/energy-shard.png"),
(ItemIds.DarkFogSiliconNeuron, 30, I18NKeys.SiliconNeuron, "assets/signal/silicon-based-neuron.png"), (ItemIds.DarkFogSiliconNeuron, 30, I18NKeys.SiliconNeuron, "assets/signal/silicon-based-neuron.png"),
(ItemIds.DarkFogNegentropySingularity, 30, I18NKeys.NegentropySingularity, "assets/signal/negentropy-singularity.png"), (ItemIds.DarkFogNegentropySingularity, 30, I18NKeys.NegentropySingularity, "assets/signal/negentropy-singularity.png"),
(ItemIds.DarkFogMatterRecombinator, 30, I18NKeys.MatterReassembler, "assets/signal/matter-recombinator.png"), (ItemIds.DarkFogMatterReassembler, 30, I18NKeys.MatterReassembler, "assets/signal/matter-recombinator.png"),
(ItemIds.DarkFogCoreElement, 10, I18NKeys.VirtualParticle, "assets/signal/core-element.png") (ItemIds.DarkFogVirtualParticle, 10, I18NKeys.VirtualParticle, "assets/signal/core-element.png")
]; ];
public static readonly int[] DarkFogItemsInVoid = [0, 0, 0, 0, 0, 0]; public static readonly int[] DarkFogItemsInVoid = [0, 0, 0, 0, 0, 0];
private static Dictionary<int, uint>[] _signalBelts = new Dictionary<int, uint>[64]; private static Dictionary<int, uint>[] _signalBelts = new Dictionary<int, uint>[64];
@@ -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;
@@ -304,14 +327,13 @@ internal static class BeltSignalPatch
var consume = (byte)Math.Min(DarkFogItemsInVoid[itemIdx], 4); var consume = (byte)Math.Min(DarkFogItemsInVoid[itemIdx], 4);
if (consume < 4) if (consume < 4)
{ {
// Metaverse is the metadata of the Universe Matrix. var metaverseLong = propertySystem.GetItemAvaliableProperty(_clusterSeedKey, ItemIds.Metaverse);
var metaverseLong = propertySystem.GetItemAvaliableProperty(_clusterSeedKey, ItemIds.UniverseMatrix);
if (metaverseLong > 0L) if (metaverseLong > 0L)
{ {
var metaverse = metaverseLong > 10 ? 10 : (int)metaverseLong; var metaverse = metaverseLong > 10 ? 10 : (int)metaverseLong;
propertySystem.AddItemConsumption(_clusterSeedKey, ItemIds.UniverseMatrix, metaverse); propertySystem.AddItemConsumption(_clusterSeedKey, ItemIds.Metaverse, metaverse);
var mainPlayer = GameMain.mainPlayer; var mainPlayer = GameMain.mainPlayer;
GameMain.history.AddPropertyItemConsumption(ItemIds.UniverseMatrix, metaverse, true); GameMain.history.AddPropertyItemConsumption(ItemIds.Metaverse, metaverse, true);
var count = definition.ExchangeRate * metaverse; var count = definition.ExchangeRate * metaverse;
DarkFogItemsInVoid[itemIdx] += count; DarkFogItemsInVoid[itemIdx] += count;
consume = (byte)Math.Min(DarkFogItemsInVoid[itemIdx], 4); consume = (byte)Math.Min(DarkFogItemsInVoid[itemIdx], 4);
+61 -10
View File
@@ -6,7 +6,6 @@ using HarmonyLib;
using UnityEngine; using UnityEngine;
using UnityEngine.UI; using UnityEngine.UI;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.GameConstants;
using GameLogicProc = UXAssist.Common.GameLogic; using GameLogicProc = UXAssist.Common.GameLogic;
namespace UXAssist.Patches.Factory; namespace UXAssist.Patches.Factory;
@@ -79,6 +78,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 +291,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>
@@ -326,8 +383,7 @@ internal static class BuildToolPatch
{ {
GameLogicProc.OnGameBegin += OnGameBegin; GameLogicProc.OnGameBegin += OnGameBegin;
GameLogicProc.OnGameEnd += OnGameEnd; GameLogicProc.OnGameEnd += OnGameEnd;
GameLogicProc.OnDataLoaded += OnGameBegin; FixProto();
OnGameBegin();
} }
protected override void OnDisable() protected override void OnDisable()
@@ -335,7 +391,6 @@ internal static class BuildToolPatch
UnfixProto(); UnfixProto();
GameLogicProc.OnGameEnd -= OnGameEnd; GameLogicProc.OnGameEnd -= OnGameEnd;
GameLogicProc.OnGameBegin -= OnGameBegin; GameLogicProc.OnGameBegin -= OnGameBegin;
GameLogicProc.OnDataLoaded -= OnGameBegin;
} }
public static void AlternatelyChanged() public static void AlternatelyChanged()
@@ -351,11 +406,7 @@ internal static class BuildToolPatch
private static void FixProto() private static void FixProto()
{ {
if (DSPGame.IsMenuDemo || _powerPoleProto == null || OldDragBuild.Count > 0) return; if (DSPGame.IsMenuDemo) return;
foreach (var id in PowerPoleIds)
{
if (LDB.items?.Select(id)?.prefabDesc == null) return;
}
OldDragBuild.Clear(); OldDragBuild.Clear();
OldDragBuildDist.Clear(); OldDragBuildDist.Clear();
foreach (var id in PowerPoleIds) foreach (var id in PowerPoleIds)
@@ -392,7 +443,7 @@ internal static class BuildToolPatch
private static void OnGameBegin() private static void OnGameBegin()
{ {
_powerPoleProto ??= LDB.items?.Select(ItemIds.TeslaTower); _powerPoleProto ??= LDB.items.Select(2201);
FixProto(); FixProto();
} }
@@ -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()
@@ -74,12 +79,13 @@ internal static class BuildingBufferPatch
matcher.MatchForward(false, matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0), new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.catalystCount))), new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(PowerGeneratorComponent), nameof(PowerGeneratorComponent.catalystCount))),
new CodeMatch(ci => ci.LoadsConstant(2)), new CodeMatch(OpCodes.Conv_R4),
new CodeMatch(OpCodes.Ldc_R4, 20f),
new CodeMatch(OpCodes.Clt) new CodeMatch(OpCodes.Clt)
); );
if (matcher.IsInvalid) if (matcher.IsInvalid)
return matcher.Finish(instructions, UXAssist.Logger, nameof(PowerGeneratorComponent_GameTick_Gamma_Transpiler)); return matcher.Finish(instructions, UXAssist.Logger, nameof(PowerGeneratorComponent_GameTick_Gamma_Transpiler));
matcher.Advance(2).Set(OpCodes.Ldc_I4, FactoryPatch.ReceiverBufferCount.Value); matcher.Advance(2).RemoveInstructions(2).Insert(new CodeInstruction(OpCodes.Ldc_I4, FactoryPatch.ReceiverBufferCount.Value));
return matcher.InstructionEnumeration(); return matcher.InstructionEnumeration();
} }
// Harmony transpiler: AssemblerComponent_UpdateNeeds_Transpiler // Harmony transpiler: AssemblerComponent_UpdateNeeds_Transpiler
+2 -22
View File
@@ -1,6 +1,5 @@
using System; using System;
using System.IO; using System.IO;
using System.Runtime.CompilerServices;
using BepInEx.Configuration; using BepInEx.Configuration;
using CommonAPI.Systems; using CommonAPI.Systems;
using UnityEngine; using UnityEngine;
@@ -13,10 +12,6 @@ namespace UXAssist.Patches.Factory;
[ModFeature("Factory", Order = 10)] [ModFeature("Factory", Order = 10)]
public static class FactoryPatch public static class FactoryPatch
{ {
/// <summary>Returns the mining cost rate shared by vein-protection display calculations.</summary>
[MethodImpl(MethodImplOptions.NoInlining)]
public static float GetMiningCostRate(GameHistoryData history) => history.miningCostRate;
public static ConfigEntry<bool> UnlimitInteractiveEnabled; public static ConfigEntry<bool> UnlimitInteractiveEnabled;
public static ConfigEntry<bool> RemoveSomeConditionEnabled; public static ConfigEntry<bool> RemoveSomeConditionEnabled;
public static ConfigEntry<bool> NightLightEnabled; public static ConfigEntry<bool> NightLightEnabled;
@@ -39,7 +34,6 @@ public static class FactoryPatch
public static ConfigEntry<bool> TankFastFillInAndTakeOutEnabled; public static ConfigEntry<bool> TankFastFillInAndTakeOutEnabled;
public static ConfigEntry<int> TankFastFillInAndTakeOutMultiplier; public static ConfigEntry<int> TankFastFillInAndTakeOutMultiplier;
public static ConfigEntry<bool> CutConveyorBeltEnabled; public static ConfigEntry<bool> CutConveyorBeltEnabled;
public static ConfigEntry<bool> ReverseConveyorBeltEnabled;
public static ConfigEntry<bool> TweakBuildingBufferEnabled; public static ConfigEntry<bool> TweakBuildingBufferEnabled;
public static ConfigEntry<int> AssemblerBufferTimeMultiplier; public static ConfigEntry<int> AssemblerBufferTimeMultiplier;
public static ConfigEntry<int> AssemblerBufferMininumMultiplier; public static ConfigEntry<int> AssemblerBufferMininumMultiplier;
@@ -57,7 +51,6 @@ public static class FactoryPatch
internal static PressKeyBind _doNotRenderEntitiesKey; internal static PressKeyBind _doNotRenderEntitiesKey;
internal static PressKeyBind _offgridfForPathsKey; internal static PressKeyBind _offgridfForPathsKey;
internal static PressKeyBind _cutConveyorBeltKey; internal static PressKeyBind _cutConveyorBeltKey;
internal static PressKeyBind _reverseConveyorBeltKey;
internal static PressKeyBind _dismantleBlueprintSelectionKey; internal static PressKeyBind _dismantleBlueprintSelectionKey;
internal static PressKeyBind _selectAllBuildingsInBlueprintCopyKey; internal static PressKeyBind _selectAllBuildingsInBlueprintCopyKey;
@@ -88,14 +81,6 @@ public static class FactoryPatch
name = "CutConveyorBelt", name = "CutConveyorBelt",
canOverride = true canOverride = true
} }
);
_reverseConveyorBeltKey = KeyBindings.RegisterKeyBinding(new BuiltinKey
{
key = new CombineKey((int)KeyCode.R, CombineKey.ALT_COMB, ECombineKeyAction.OnceClick, false),
conflictGroup = KeyBindConflict.MOVEMENT | KeyBindConflict.FLYING | KeyBindConflict.SAILING | KeyBindConflict.BUILD_MODE_1 | KeyBindConflict.KEYBOARD_KEYBIND,
name = "ReverseConveyorBelt",
canOverride = true
}
); );
_dismantleBlueprintSelectionKey = KeyBindings.RegisterKeyBinding(new BuiltinKey _dismantleBlueprintSelectionKey = KeyBindings.RegisterKeyBinding(new BuiltinKey
{ {
@@ -118,6 +103,8 @@ public static class FactoryPatch
UnlimitInteractiveEnabled.SettingChanged += (_, _) => ArchitectModePatch.UnlimitInteractive.Enable(UnlimitInteractiveEnabled.Value); UnlimitInteractiveEnabled.SettingChanged += (_, _) => ArchitectModePatch.UnlimitInteractive.Enable(UnlimitInteractiveEnabled.Value);
RemoveSomeConditionEnabled.SettingChanged += (_, _) => ArchitectModePatch.RemoveSomeConditionBuild.Enable(RemoveSomeConditionEnabled.Value); RemoveSomeConditionEnabled.SettingChanged += (_, _) => ArchitectModePatch.RemoveSomeConditionBuild.Enable(RemoveSomeConditionEnabled.Value);
NightLightEnabled.SettingChanged += (_, _) => RenderingPatch.NightLight.Enable(NightLightEnabled.Value); NightLightEnabled.SettingChanged += (_, _) => RenderingPatch.NightLight.Enable(NightLightEnabled.Value);
NightLightAngleX.SettingChanged += (_, _) => RenderingPatch.NightLight.UpdateSunlightAngle();
NightLightAngleY.SettingChanged += (_, _) => RenderingPatch.NightLight.UpdateSunlightAngle();
RemoveBuildRangeLimitEnabled.SettingChanged += (_, _) => ArchitectModePatch.RemoveBuildRangeLimit.Enable(RemoveBuildRangeLimitEnabled.Value); RemoveBuildRangeLimitEnabled.SettingChanged += (_, _) => ArchitectModePatch.RemoveBuildRangeLimit.Enable(RemoveBuildRangeLimitEnabled.Value);
LargerAreaForUpgradeAndDismantleEnabled.SettingChanged += (_, _) => ArchitectModePatch.LargerAreaForUpgradeAndDismantle.Enable(LargerAreaForUpgradeAndDismantleEnabled.Value); LargerAreaForUpgradeAndDismantleEnabled.SettingChanged += (_, _) => ArchitectModePatch.LargerAreaForUpgradeAndDismantle.Enable(LargerAreaForUpgradeAndDismantleEnabled.Value);
LargerAreaForTerraformEnabled.SettingChanged += (_, _) => ArchitectModePatch.LargerAreaForTerraform.Enable(LargerAreaForTerraformEnabled.Value); LargerAreaForTerraformEnabled.SettingChanged += (_, _) => ArchitectModePatch.LargerAreaForTerraform.Enable(LargerAreaForTerraformEnabled.Value);
@@ -225,13 +212,6 @@ public static class FactoryPatch
Functions.FactoryFunctions.CutConveyorBelt(cargoTraffic, beltId); Functions.FactoryFunctions.CutConveyorBelt(cargoTraffic, beltId);
} }
} }
if (ReverseConveyorBeltEnabled.Value && _reverseConveyorBeltKey.keyValue
&& GameMain.isRunning && !GameMain.isPaused && !VFInput.onGUI)
{
var raycast = GameMain.mainPlayer?.controller?.cmd.raycast;
if (raycast != null && raycast.castEntity.id > 0 && raycast.castEntity.beltId > 0)
Functions.FactoryFunctions.ReverseConveyorBelt(raycast.planet?.factory, raycast.castEntity.beltId);
}
if (ShortcutKeysForBlueprintCopyEnabled.Value) if (ShortcutKeysForBlueprintCopyEnabled.Value)
{ {
if (_dismantleBlueprintSelectionKey.keyValue) if (_dismantleBlueprintSelectionKey.keyValue)
+111 -138
View File
@@ -12,6 +12,12 @@ namespace UXAssist.Patches.Factory;
internal static class RenderingPatch internal static class RenderingPatch
{ {
public static void Enable(bool enable)
{
DoNotRenderEntities.Enable(enable);
NightLight.Enable(enable);
}
internal class DoNotRenderEntities : PatchImpl<DoNotRenderEntities> internal class DoNotRenderEntities : PatchImpl<DoNotRenderEntities>
{ {
public static bool HideSorters; public static bool HideSorters;
@@ -86,173 +92,140 @@ internal static class RenderingPatch
internal class NightLight : PatchImpl<NightLight> internal class NightLight : PatchImpl<NightLight>
{ {
private static bool _nightlightInitialized;
private static bool _mechaOnEarth;
private static AnimationState _sail;
private static Light _sunlight; private static Light _sunlight;
private static Quaternion _sunlightLocalRotation;
private static PlanetSimulator _planetSimulator;
private static int _sunDirectionId;
private static int _globalSunDirectionId;
protected override void OnEnable() protected override void OnEnable()
{ {
_sunDirectionId = Shader.PropertyToID("_SunDir"); GameLogicProc.OnGameEnd += OnGameEnd;
_globalSunDirectionId = Shader.PropertyToID("_Global_SunDir");
GameLogicProc.OnGameEnd += RestoreSunlight;
} }
protected override void OnDisable() protected override void OnDisable()
{ {
GameLogicProc.OnGameEnd -= RestoreSunlight; GameLogicProc.OnGameEnd -= OnGameEnd;
RestoreSunlight(); if (_sunlight)
}
private static void RestoreSunlight()
{ {
var sunlight = _sunlight; _sunlight.transform.localEulerAngles = new Vector3(0f, 180f);
if (sunlight)
sunlight.transform.localRotation = _sunlightLocalRotation;
var planetSimulator = _planetSimulator;
_sunlight = null; _sunlight = null;
_planetSimulator = null;
if ((!sunlight && !planetSimulator) || !GameMain.instance || !GameMain.instance._running || GameMain.instance.isMenuDemo || FactoryModel.whiteMode0) return;
var starSimulator = GameMain.universeSimulator?.LocalStarSimulator();
if (starSimulator)
Shader.SetGlobalVector(_globalSunDirectionId, starSimulator.transform.forward);
if (planetSimulator && planetSimulator.isActiveAndEnabled && planetSimulator.planetData != null)
{
var rotation = GameMain.localPlanet?.runtimeRotation ?? Quaternion.identity;
var planet = planetSimulator.planetData;
Vector3 direction = Quaternion.Inverse(rotation) * (planet.star.uPosition - planet.uPosition).normalized;
ApplyPlanetSunlightDirection(planetSimulator, direction);
} }
_sail = null;
_mechaOnEarth = false;
_nightlightInitialized = false;
} }
internal static Vector3 CalculateSunlightDirection(Vector3 surfaceUp, Vector3 cameraForward, Vector3 cameraUp, float angleX, float angleY) private static void OnGameEnd()
{ {
surfaceUp.Normalize(); if (_sunlight)
// Screen-right stays stable when the native globe camera's offset crosses its viewing axis. {
var right = Vector3.ProjectOnPlane(Vector3.Cross(cameraUp, cameraForward), surfaceUp); _sunlight.transform.localEulerAngles = new Vector3(0f, 180f);
if (right.sqrMagnitude < 0.000001f) _sunlight = null;
right = Vector3.Cross(-cameraForward, surfaceUp); }
right.Normalize(); _sail = null;
var towardCamera = Vector3.Cross(surfaceUp, right); _mechaOnEarth = false;
return (surfaceUp - towardCamera * (angleX / 10f) - right * (angleY / 10f)).normalized; _nightlightInitialized = false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void UpdateSunlightAngle()
{
if (!_sunlight) return;
_sunlight.transform.rotation =
Quaternion.LookRotation(-GameMain.mainPlayer.transform.up + GameMain.mainPlayer.transform.forward * FactoryPatch.NightLightAngleX.Value / 10f +
GameMain.mainPlayer.transform.right * FactoryPatch.NightLightAngleY.Value / 10f);
} }
[HarmonyPostfix] [HarmonyPostfix]
[HarmonyPatch(typeof(GameCamera), nameof(GameCamera.FrameLogic))] [HarmonyPatch(typeof(GameMain), nameof(GameMain.LateUpdate))]
private static void UpdateLighting() public static void GameMain_LateUpdate_Postfix(GameMain __instance)
{ {
var camera = GameCamera.main; if (__instance.isMenuDemo || !__instance._running) return;
if (!camera) return;
var game = GameMain.instance; if (!_nightlightInitialized)
var player = GameMain.mainPlayer;
var planet = GameMain.localPlanet;
if (!game || !game._running || game.isMenuDemo || player == null || planet == null ||
player.movementState == EMovementState.Sail || FactoryModel.whiteMode0)
{ {
RestoreSunlight(); if (!GameMain.mainPlayer.controller.model.gameObject.activeInHierarchy) return;
if (_sail == null) _sail = GameMain.mainPlayer.animator.sails[GameMain.mainPlayer.animator.sailAnimIndex];
_nightlightInitialized = true;
}
var sailing = _sail && _sail.enabled;
if (_mechaOnEarth)
{
if (!sailing)
{
UpdateSunlightAngle();
return;
}
_mechaOnEarth = false;
if (!_sunlight) return;
_sunlight.transform.localEulerAngles = new Vector3(0f, 180f);
_sunlight = null;
return; return;
} }
var universe = GameMain.universeSimulator; if (sailing) return;
var sunlight = universe?.LocalStarSimulator()?.sunLight; _mechaOnEarth = true;
var planetSimulator = universe?.FindPlanetSimulator(planet); if (_sunlight == null)
if (!sunlight || !planetSimulator)
{ {
RestoreSunlight(); _sunlight = GameMain.universeSimulator?.LocalStarSimulator()?.sunLight;
return;
} }
var cameraTransform = camera.transform;
var target = GameCamera.generalTarget;
var surfaceUp = GameCamera.instance && GameCamera.instance.isPlanetMode
? cameraTransform.position
: target ? target.position : player.position;
if (surfaceUp.sqrMagnitude < 0.000001f)
{
RestoreSunlight();
return;
} }
// Harmony transpiler: StarSimulator_LateUpdate_Transpiler
if (_sunlight != sunlight || _planetSimulator != planetSimulator) // Target: StarSimulator.LateUpdate
{ // Fallback: None — patch will fail loudly if the target method body changes.
RestoreSunlight();
_sunlight = sunlight;
_sunlightLocalRotation = sunlight.transform.localRotation;
_planetSimulator = planetSimulator;
}
var direction = CalculateSunlightDirection(surfaceUp, cameraTransform.forward, cameraTransform.up,
FactoryPatch.NightLightAngleX.Value, FactoryPatch.NightLightAngleY.Value);
// Native camera updates run after the star and planet callbacks.
sunlight.transform.rotation = Quaternion.FromToRotation(Vector3.forward, -direction);
Shader.SetGlobalVector(_globalSunDirectionId, direction);
ApplyPlanetSunlightDirection(planetSimulator, direction);
}
private static void ApplyPlanetSunlightDirection(PlanetSimulator planetSimulator, Vector3 direction)
{
if (planetSimulator.surfaceRenderer != null && planetSimulator.surfaceRenderer.Length > 0 && planetSimulator.surfaceRenderer[0])
SetSunlightDirection(planetSimulator.surfaceRenderer[0].sharedMaterial, direction);
SetSunlightDirection(planetSimulator.reformMat0, direction);
SetSunlightDirection(planetSimulator.reformMat1, direction);
SetSunlightDirection(planetSimulator.atmoMat, direction);
SetSunlightDirection(planetSimulator.atmoMatLate, direction);
}
private static void SetSunlightDirection(Material material, Vector3 direction)
{
if (material) material.SetVector(_sunDirectionId, direction);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void SetNativeGlobalSunDirection(string _, Vector4 direction, StarSimulator simulator)
{
if (_sunlight && simulator.sunLight == _sunlight && !FactoryModel.whiteMode0) return;
Shader.SetGlobalVector(_globalSunDirectionId, direction);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void SetNativePlanetSunDirection(Material material, string _, Vector4 direction, PlanetSimulator simulator)
{
if (simulator == _planetSimulator && simulator.planetData == GameMain.localPlanet && !FactoryModel.whiteMode0 && _sunlight) return;
material.SetVector(_sunDirectionId, direction);
}
// Harmony transpiler: DeferNativeSunDirectionWrites
// Targets: StarSimulator.LateUpdate and PlanetSimulator.LateRefresh sun-direction setters.
// Fallback: TranspilerGuard returns original instructions when a sun-direction setter is not found.
[HarmonyTranspiler] [HarmonyTranspiler]
[HarmonyPatch(typeof(StarSimulator), nameof(StarSimulator.LateUpdate))] [HarmonyPatch(typeof(StarSimulator), nameof(StarSimulator.LateUpdate))]
private static IEnumerable<CodeInstruction> StarSimulator_LateUpdate_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{
var matcher = new CodeMatcher(instructions, generator);
var label1 = generator.DefineLabel();
var label2 = generator.DefineLabel();
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldarg_0),
new CodeMatch(OpCodes.Call, AccessTools.PropertyGetter(typeof(Component), nameof(Component.transform)))
).InsertAndAdvance(
new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(NightLight), nameof(_mechaOnEarth))),
new CodeInstruction(OpCodes.Brfalse_S, label1),
new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(GameMain), nameof(GameMain.mainPlayer))),
new CodeInstruction(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.transform))),
new CodeInstruction(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Transform), nameof(Transform.up))),
new CodeInstruction(OpCodes.Stloc_0),
new CodeInstruction(OpCodes.Br_S, label2)
);
matcher.Labels.Add(label1);
matcher.MatchForward(false,
new CodeMatch(OpCodes.Stloc_0)
).Advance(1).Labels.Add(label2);
return matcher.InstructionEnumeration();
}
// Harmony transpiler: PlanetSimulator_LateRefresh_Transpiler
// Target: PlanetSimulator.LateRefresh
// Fallback: None — patch will fail loudly if the target method body changes.
[HarmonyTranspiler]
[HarmonyPatch(typeof(PlanetSimulator), nameof(PlanetSimulator.LateRefresh))] [HarmonyPatch(typeof(PlanetSimulator), nameof(PlanetSimulator.LateRefresh))]
private static IEnumerable<CodeInstruction> DeferNativeSunDirectionWrites(IEnumerable<CodeInstruction> instructions, MethodBase original) private static IEnumerable<CodeInstruction> PlanetSimulator_LateRefresh_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{ {
var isPlanet = original.DeclaringType == typeof(PlanetSimulator); // var vec = (NightlightEnabled ? GameMain.mainPlayer.transform.up : (Quaternion.Inverse(localPlanet.runtimeRotation) * (__instance.planetData.star.uPosition - __instance.planetData.uPosition).normalized));
var property = isPlanet ? "_SunDir" : "_Global_SunDir"; var matcher = new CodeMatcher(instructions, generator);
var setter = isPlanet var label1 = generator.DefineLabel();
? AccessTools.Method(typeof(Material), nameof(Material.SetVector), [typeof(string), typeof(Vector4)]) var label2 = generator.DefineLabel();
: AccessTools.Method(typeof(Shader), nameof(Shader.SetGlobalVector), [typeof(string), typeof(Vector4)]); matcher.MatchForward(false,
var replacement = AccessTools.Method(typeof(NightLight), isPlanet ? nameof(SetNativePlanetSunDirection) : nameof(SetNativeGlobalSunDirection)); new CodeMatch(OpCodes.Stloc_1)
var matcher = new CodeMatcher(instructions); ).Advance(1).InsertAndAdvance(
var matched = false; new CodeInstruction(OpCodes.Ldsfld, AccessTools.Field(typeof(NightLight), nameof(_mechaOnEarth))),
while (true) new CodeInstruction(OpCodes.Brfalse_S, label1),
{ new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(GameMain), nameof(GameMain.mainPlayer))),
matcher.MatchForward(false, new CodeMatch(OpCodes.Ldstr, property)); new CodeInstruction(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Player), nameof(Player.transform))),
if (matcher.IsInvalid) break; new CodeInstruction(OpCodes.Callvirt, AccessTools.PropertyGetter(typeof(Transform), nameof(Transform.up))),
matcher.Advance(1).MatchForward(false, new CodeMatch(instruction => instruction.Calls(setter) || instruction.opcode == OpCodes.Ldstr)); new CodeInstruction(OpCodes.Stloc_2),
if (matcher.IsInvalid) new CodeInstruction(OpCodes.Br_S, label2)
return matcher.Finish(instructions, UXAssist.Logger, nameof(DeferNativeSunDirectionWrites)); );
if (!matcher.Instruction.Calls(setter)) matcher.Labels.Add(label1);
{ matcher.MatchForward(false,
UXAssist.Logger?.LogWarning($"Transpiler '{nameof(DeferNativeSunDirectionWrites)}' found an unexpected sun-direction write; returning original instructions."); new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(typeof(FactoryModel), nameof(FactoryModel.whiteMode0)))
return instructions; ).Labels.Add(label2);
} return matcher.InstructionEnumeration();
matcher.InsertAndAdvance(new CodeInstruction(OpCodes.Ldarg_0).MoveLabelsFrom(matcher.Instruction));
matcher.Set(OpCodes.Call, replacement).Advance(1);
matched = true;
}
return matched ? matcher.InstructionEnumeration() : matcher.Finish(instructions, UXAssist.Logger, nameof(DeferNativeSunDirectionWrites));
} }
} }
} }
@@ -8,8 +8,13 @@ using GameLogicProc = UXAssist.Common.GameLogic;
namespace UXAssist.Patches.Factory; namespace UXAssist.Patches.Factory;
[ModFeature("VeinProtection")] [ModFeature("VeinProtection")]
internal static partial class VeinProtectionPatch internal static class VeinProtectionPatch
{ {
public static void Enable(bool enable)
{
ProtectVeinsFromExhaustion.Enable(enable);
}
public static void InitConfig() public static void InitConfig()
{ {
ProtectVeinsFromExhaustion.InitConfig(); ProtectVeinsFromExhaustion.InitConfig();
@@ -25,7 +30,7 @@ internal static partial class VeinProtectionPatch
GameLogicProc.OnGameEnd -= ProtectVeinsFromExhaustion.ResetState; GameLogicProc.OnGameEnd -= ProtectVeinsFromExhaustion.ResetState;
} }
internal partial class ProtectVeinsFromExhaustion : PatchImpl<ProtectVeinsFromExhaustion> internal class ProtectVeinsFromExhaustion : PatchImpl<ProtectVeinsFromExhaustion>
{ {
public static int KeepVeinAmount = 100; public static int KeepVeinAmount = 100;
public static float KeepOilSpeed = 1f; public static float KeepOilSpeed = 1f;
@@ -1,198 +0,0 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using UXAssist.Common.Patching;
namespace UXAssist.Patches.Factory;
internal static partial class VeinProtectionPatch
{
internal partial class ProtectVeinsFromExhaustion
{
private static bool IsProtectedVein(ref VeinData vein, float miningRate)
{
if (miningRate <= 0f || vein.id <= 0 || vein.amount <= 0) return false;
return vein.type == EVeinType.Oil
? _keepOilAmount > 2500 && vein.amount <= _keepOilAmount
: vein.amount <= KeepVeinAmount;
}
private static int GetMiningVeinCount(ref MinerComponent miner, PlanetFactory factory)
{
var miningRate = FactoryPatch.GetMiningCostRate(factory.gameData.history);
var count = 0;
for (var i = 0; i < miner.veinCount; i++)
{
ref var vein = ref factory.veinPool[miner.veins[i]];
if (vein.id > 0 && vein.amount > 0 && !IsProtectedVein(ref vein, miningRate)) count++;
}
return count;
}
private static int GetMiningVeinCountForWindow(MinerComponent miner, PlanetFactory factory)
{
return GetMiningVeinCount(ref miner, factory);
}
private static int GetMiningVeinAmount(ref VeinData vein, PlanetFactory factory)
{
return IsProtectedVein(ref vein, FactoryPatch.GetMiningCostRate(factory.gameData.history)) ? 0 : vein.amount;
}
// Harmony transpiler: MiningSpeed_Transpiler
// Target: ProductionExtraInfoCalculator.CalculateFactory, UIReferenceSpeedTip.AddEntryDataWithFactory, UIMinerWindow._OnUpdate
// Fallback: Return the original instructions if the native mining-speed multiplications cannot be found.
[HarmonyTranspiler]
[HarmonyPatch(typeof(ProductionExtraInfoCalculator), nameof(ProductionExtraInfoCalculator.CalculateFactory))]
[HarmonyPatch(typeof(UIReferenceSpeedTip), nameof(UIReferenceSpeedTip.AddEntryDataWithFactory))]
[HarmonyPatch(typeof(UIMinerWindow), nameof(UIMinerWindow._OnUpdate))]
private static IEnumerable<CodeInstruction> MiningSpeed_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator, MethodBase __originalMethod)
{
var original = instructions.ToList();
var matcher = new CodeMatcher(original, generator);
var factoryParameter = __originalMethod.GetParameters().Select((p, i) => (p, i)).FirstOrDefault(v => v.p.ParameterType == typeof(PlanetFactory));
var factoryLoad = factoryParameter.p != null
? new[] { new CodeInstruction(OpCodes.Ldarg, factoryParameter.i + (__originalMethod.IsStatic ? 0 : 1)) }
: new[] { new CodeInstruction(OpCodes.Ldarg_0), new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(UIMinerWindow), nameof(UIMinerWindow.factory))) };
matcher.MatchForward(false,
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(MinerComponent), nameof(MinerComponent.veinCount))),
new CodeMatch(ci => ci.opcode == OpCodes.Conv_R8 || ci.opcode == OpCodes.Conv_R4));
if (matcher.IsInvalid) return matcher.Finish(original, UXAssist.Logger, nameof(MiningSpeed_Transpiler));
// The window loads a struct value; the statistics paths load managed references.
var veinCountHelper = __originalMethod.DeclaringType == typeof(UIMinerWindow)
? nameof(GetMiningVeinCountForWindow)
: nameof(GetMiningVeinCount);
matcher.Repeat(m => ReplaceRead(m, factoryLoad, veinCountHelper));
matcher.Start().MatchForward(false,
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(VeinData), nameof(VeinData.amount))),
new CodeMatch(OpCodes.Conv_R8),
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(typeof(VeinData), nameof(VeinData.oilSpeedMultiplier))));
var oilMatched = matcher.IsValid;
if (oilMatched) matcher.Repeat(m => ReplaceRead(m, factoryLoad, nameof(GetMiningVeinAmount)));
matcher.Start().MatchForward(false,
new CodeMatch(OpCodes.Ldfld, AccessTools.Field(typeof(VeinData), nameof(VeinData.amount))),
new CodeMatch(OpCodes.Conv_R8),
new CodeMatch(OpCodes.Mul),
new CodeMatch(OpCodes.Ldsfld, AccessTools.Field(typeof(VeinData), nameof(VeinData.oilSpeedMultiplier))));
if (matcher.IsValid)
{
oilMatched = true;
matcher.Repeat(m => ReplaceRead(m, factoryLoad, nameof(GetMiningVeinAmount)));
}
if (!oilMatched) return matcher.Finish(original, UXAssist.Logger, nameof(MiningSpeed_Transpiler));
return matcher.InstructionEnumeration();
}
private static void ReplaceRead(CodeMatcher matcher, CodeInstruction[] factoryLoad, string helper)
{
var labels = matcher.Labels.ToArray();
var blocks = matcher.Instruction.blocks.ToArray();
matcher.RemoveInstruction();
var replacement = factoryLoad.Select(ci => ci.Clone()).Append(new CodeInstruction(OpCodes.Call,
AccessTools.Method(typeof(ProtectVeinsFromExhaustion), helper))).ToArray();
replacement[0].labels.AddRange(labels);
replacement[0].blocks.AddRange(blocks);
matcher.InsertAndAdvance(replacement);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(EntityBriefInfo), nameof(EntityBriefInfo.SetBriefInfo))]
private static void EntityBriefInfo_SetBriefInfo_Postfix(EntityBriefInfo __instance, PlanetFactory _factory, int _entityId)
{
if (_factory == null || _entityId <= 0) return;
var minerId = _factory.entityPool[_entityId].minerId;
if (minerId <= 0) return;
ref var miner = ref _factory.factorySystem.minerPool[minerId];
if (miner.type == EMinerType.Water) return;
var miningRate = FactoryPatch.GetMiningCostRate(_factory.gameData.history);
for (var i = 0; i < miner.veinCount; i++)
{
ref var vein = ref _factory.veinPool[miner.veins[i]];
if (IsProtectedVein(ref vein, miningRate)) __instance.equipment.Add((int)vein.type, -1, 0);
}
}
[HarmonyPostfix]
[HarmonyPatch(typeof(AstroResourceStatPlan), nameof(AstroResourceStatPlan.AddPlanetResources))]
private static void AstroResourceStatPlan_AddPlanetResources_Postfix(AstroResourceStatPlan __instance, PlanetData planet, int veinAmountDisplayFilter)
{
var factory = planet?.factory;
if (factory == null || planet.type == EPlanetType.Gas || veinAmountDisplayFilter is not (1 or 2)) return;
var miningRate = FactoryPatch.GetMiningCostRate(factory.gameData.history);
if (miningRate <= 0f) return;
var miners = factory.factorySystem.minerPool;
var consumers = factory.powerSystem.consumerPool;
var seen = AstroResourceStatPlan.hashes;
seen.Clear();
var sign = veinAmountDisplayFilter == 1 ? -1 : 1;
for (var i = 1; i < factory.factorySystem.minerCursor; i++)
{
ref var miner = ref miners[i];
if (miner.id != i || miner.type == EMinerType.Water || consumers[miner.pcId].networkId <= 0) continue;
for (var j = 0; j < miner.veinCount; j++)
{
var veinId = miner.veins[j];
ref var vein = ref factory.veinPool[veinId];
if (!IsProtectedVein(ref vein, miningRate) || !seen.Add(veinId)) continue;
var type = vein.type == EVeinType.Oil ? AstroResourceStatPlan.EAstroResourceType.Oil : AstroResourceStatPlan.EAstroResourceType.Vein;
double amount = vein.amount;
if (vein.type == EVeinType.Oil)
{
amount = (float)vein.amount * VeinData.oilSpeedMultiplier;
if (veinAmountDisplayFilter == 1) amount *= __instance.gameData.history.miningSpeedScale;
}
__instance.AddStatData(type, (int)vein.type, sign, sign * amount);
}
}
seen.Clear();
}
[HarmonyPrefix]
[HarmonyPatch(typeof(AstroResourceStatPlan), nameof(AstroResourceStatPlan.AddPlanetDetailedResources))]
private static bool AstroResourceStatPlan_AddPlanetDetailedResources_Prefix(AstroResourceStatPlan __instance, PlanetData planet, int veinAmountDisplayFilter, ref bool __result)
{
var factory = planet?.factory;
if (factory == null || planet.type == EPlanetType.Gas || veinAmountDisplayFilter is not (1 or 2)) return true;
var miningRate = FactoryPatch.GetMiningCostRate(factory.gameData.history);
var veins = planet.runtimeVeinPool;
if (miningRate <= 0f || veins == null) return true;
var seen = AstroResourceStatPlan.hashes;
seen.Clear();
var miners = factory.factorySystem.minerPool;
var consumers = factory.powerSystem.consumerPool;
__result = true;
for (var i = 1; i < factory.factorySystem.minerCursor; i++)
{
ref var miner = ref miners[i];
if (miner.id != i || miner.type != EMinerType.Vein || consumers[miner.pcId].networkId <= 0) continue;
for (var j = 0; j < miner.veinCount; j++)
{
var id = miner.veins[j];
if (id <= 0) continue;
ref var vein = ref veins[id];
if (vein.id != id || vein.type == EVeinType.Oil || IsProtectedVein(ref vein, miningRate) || !seen.Add(id)) continue;
if (veinAmountDisplayFilter == 1 && !__instance.AddDetailedStatData(planet.astroId, (int)vein.type, vein.groupIndex, vein.amount))
{
__result = false;
return false;
}
}
}
if (veinAmountDisplayFilter == 2)
{
for (var i = 1; i < planet.runtimeVeinCursor; i++)
{
ref var vein = ref veins[i];
if (vein.id != i || vein.type == EVeinType.Oil || seen.Contains(i)) continue;
if (__instance.AddDetailedStatData(planet.astroId, (int)vein.type, vein.groupIndex, vein.amount)) continue;
__result = false;
break;
}
}
return false;
}
}
}
+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;
+16 -23
View File
@@ -8,7 +8,6 @@ using UnityEngine.EventSystems;
using UnityEngine.UI; using UnityEngine.UI;
using UXAssist.Common; using UXAssist.Common;
using UXAssist.Common.GameConstants; using UXAssist.Common.GameConstants;
using UXAssist.Common.Patching;
namespace UXAssist.Patches.Logistics; namespace UXAssist.Patches.Logistics;
@@ -361,38 +360,32 @@ internal class GreaterPowerUsageInLogistics : PatchImpl<GreaterPowerUsageInLogis
} }
// Harmony transpiler: UIStationWindow_OnMaxMiningSpeedChange_Transpiler // Harmony transpiler: UIStationWindow_OnMaxMiningSpeedChange_Transpiler
// Target: UIStationWindow.OnMaxMiningSpeedChange // Target: UIStationWindow.OnMaxMiningSpeedChange
// Fallback: Return the original instructions if the native mining-speed calculation is not found. // Fallback: None — patch will fail loudly if the target method body changes.
[HarmonyTranspiler] [HarmonyTranspiler]
[HarmonyPatch(typeof(UIStationWindow), nameof(UIStationWindow.OnMaxMiningSpeedChange))] [HarmonyPatch(typeof(UIStationWindow), nameof(UIStationWindow.OnMaxMiningSpeedChange))]
private static IEnumerable<CodeInstruction> UIStationWindow_OnMaxMiningSpeedChange_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator) private static IEnumerable<CodeInstruction> UIStationWindow_OnMaxMiningSpeedChange_Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
{ {
var original = instructions.ToList(); var matcher = new CodeMatcher(instructions, generator);
var matcher = new CodeMatcher(original, generator);
matcher.MatchForward(false, matcher.MatchForward(false,
new CodeMatch(ci => ci.LoadsConstant(LogisticsConstants.MinMiningSpeedBase)), new CodeMatch(ci => ci.opcode == OpCodes.Ldc_I4 && ci.OperandIs(LogisticsConstants.MinMiningSpeedBase)),
new CodeMatch(OpCodes.Ldarg_1), new CodeMatch(OpCodes.Ldarg_1)
new CodeMatch(OpCodes.Ldc_R4, 0.5f),
new CodeMatch(OpCodes.Add),
new CodeMatch(OpCodes.Conv_I4),
new CodeMatch(ci => ci.LoadsConstant(LogisticsConstants.MiningSpeedFineStep)),
new CodeMatch(OpCodes.Mul),
new CodeMatch(OpCodes.Add),
new CodeMatch(ci => ci.IsStloc())
); );
if (matcher.IsInvalid) var pos = matcher.Pos;
return matcher.Finish(original, UXAssist.Logger, nameof(UIStationWindow_OnMaxMiningSpeedChange_Transpiler)); matcher.MatchForward(false,
var loadValue = new CodeInstruction(OpCodes.Ldarg_1).WithLabels(matcher.Labels); new CodeMatch(OpCodes.Stloc_1)
loadValue.blocks.AddRange(matcher.Instruction.blocks); );
matcher.RemoveInstructions(8); var pos2 = matcher.Pos;
matcher.Start().Advance(pos);
var labels = matcher.Labels;
matcher.RemoveInstructions(pos2 - pos);
matcher.Insert( matcher.Insert(
loadValue, new CodeInstruction(OpCodes.Ldarg_1).WithLabels(labels),
Transpilers.EmitDelegate<Func<float, int>>(value => Transpilers.EmitDelegate((float value) =>
{ {
var intval = (int)(value + 0.5f); var intval = (int)(value + 0.5f);
var defaultMax = (int)LogisticsConstants.MiningSpeedSliderMaxDefault; if (intval <= LogisticsConstants.MiningSpeedSliderMaxDefault)
if (intval <= defaultMax)
return intval * LogisticsConstants.MiningSpeedFineStep + LogisticsConstants.MinMiningSpeedBase; return intval * LogisticsConstants.MiningSpeedFineStep + LogisticsConstants.MinMiningSpeedBase;
return (intval - defaultMax) * LogisticsConstants.MiningSpeedCoarseStep + LogisticsConstants.MaxMiningSpeedBase; return (intval - LogisticsConstants.MiningSpeedSliderMaxDefault) * LogisticsConstants.MiningSpeedCoarseStep + LogisticsConstants.MaxMiningSpeedBase;
}) })
); );
return matcher.InstructionEnumeration(); return matcher.InstructionEnumeration();
@@ -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;
+107 -41
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();
}
*/
} }
@@ -654,19 +758,6 @@ public class PlayerPatch : PatchImpl<PlayerPatch>
return default; return default;
VectorLF3 baseDir = toTarget.normalized; VectorLF3 baseDir = toTarget.normalized;
// The mecha can be inside several path radii at once. Stars and planets keep priority over
// hives: a hive's range is wide enough to cover a whole planet, and leaving the hive first
// can steer a mecha that has just taken off back into the ground.
// Among stars and planets, a moon close to its gas giant puts a mecha on the moon inside both
// ranges, and the giant comes first in the list. Leaving only the giant sends a mecha that
// takes off from the moon's giant-facing side back into the ground, because "away from the
// giant" points down there. Leave all of them together, each weighted by how deep the mecha
// is inside its range: their safety margins are equal, so the nearest surface dominates.
VectorLF3 bodiesInward = default;
VectorLF3 hiveInward = default;
bool insideBody = false;
bool insideHive = false;
foreach (Obstacle obstacle in obstacles) foreach (Obstacle obstacle in obstacles)
{ {
double pathRadius = GetReachablePathRadius(obstacle); double pathRadius = GetReachablePathRadius(obstacle);
@@ -675,34 +766,10 @@ public class PlayerPatch : PatchImpl<PlayerPatch>
VectorLF3 toObstacle = obstacle.Position - playerPos; VectorLF3 toObstacle = obstacle.Position - playerPos;
double obstacleDistance = toObstacle.magnitude; double obstacleDistance = toObstacle.magnitude;
if (obstacleDistance >= pathRadius) if (obstacleDistance < pathRadius)
continue; return ComputeEscapeDirection(currentDirection, toObstacle, baseDir);
if (obstacle.HasSurface)
{
bodiesInward += SafeNorm(toObstacle, baseDir) * (pathRadius - obstacleDistance);
insideBody = true;
}
else if (!insideHive)
{
hiveInward = toObstacle;
insideHive = true;
}
}
if (insideBody)
return ComputeEscapeDirection(currentDirection, bodiesInward, baseDir);
if (insideHive)
return ComputeEscapeDirection(currentDirection, hiveInward, baseDir);
foreach (Obstacle obstacle in obstacles)
{
double pathRadius = GetReachablePathRadius(obstacle);
if (pathRadius <= 0.0)
continue;
if (IsSegmentBlocked(playerPos, _targetUniversePosition, obstacle.Position, pathRadius)) if (IsSegmentBlocked(playerPos, _targetUniversePosition, obstacle.Position, pathRadius))
return ComputeTangentDirection(currentDirection, obstacle.Position - playerPos, pathRadius, baseDir); return ComputeTangentDirection(currentDirection, toObstacle, pathRadius, baseDir);
} }
return baseDir; return baseDir;
@@ -1162,7 +1229,6 @@ public class PlayerPatch : PatchImpl<PlayerPatch>
{ {
public VectorLF3 Position { get; } = position; public VectorLF3 Position { get; } = position;
public double PathRadius { get; } = radius + safetyMargin; public double PathRadius { get; } = radius + safetyMargin;
public bool HasSurface { get; } = radius > 0.0;
} }
#endregion #endregion
+1 -12
View File
@@ -222,22 +222,11 @@ public static class TechPatch
foreach (var item in nodes) foreach (var item in nodes)
{ {
var node = item.Value; var node = item.Value;
var postTechArray = node.techProto.postTechArray;
// A new session can initialize nodes while the peace-mode graph is still filtered.
var arrowCount = node.arrows.Length;
if (arrowCount < postTechArray.Length)
{
System.Array.Resize(ref node.arrows, postTechArray.Length);
for (var i = arrowCount; i < postTechArray.Length; i++)
{
node.arrows[i] = UnityEngine.Object.Instantiate(node.arrowPrefab, node.arrowPrefab.parent);
node.arrows[i].SetAsFirstSibling();
}
}
foreach (var arrow in node.arrows) foreach (var arrow in node.arrows)
{ {
arrow.gameObject.SetActive(false); arrow.gameObject.SetActive(false);
} }
var postTechArray = node.techProto.postTechArray;
var active = postTechArray.Length > 0; var active = postTechArray.Length > 0;
node.connGroup.gameObject.SetActive(active); node.connGroup.gameObject.SetActive(active);
node.connImages = active ? node.connGroup.GetComponentsInChildren<Image>(true) : []; node.connImages = active ? node.connGroup.GetComponentsInChildren<Image>(true) : [];
+5 -8
View File
@@ -35,14 +35,6 @@ public class UIPatch : PatchImpl<UIPatch>
GameLogicProc.OnGameBegin -= PlanetVeinUtilization.OnGameBegin; GameLogicProc.OnGameBegin -= PlanetVeinUtilization.OnGameBegin;
} }
[HarmonyPostfix]
[HarmonyPatch(typeof(UIEscMenu), nameof(UIEscMenu._OnOpen))]
private static void UIEscMenu__OnOpen_Postfix()
{
// Pausing stops general-tip updates before they can dismiss the hovered entity.
UIGeneralTips.instance?.entityBriefInfo?.SetInfo(null, 0);
}
private class PlanetVeinUtilization : PatchImpl<PlanetVeinUtilization> private class PlanetVeinUtilization : PatchImpl<PlanetVeinUtilization>
{ {
private const float CountLabelGap = 4f; private const float CountLabelGap = 4f;
@@ -106,6 +98,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)
@@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production; namespace UXAssist.Production;
@@ -69,7 +68,8 @@ public sealed class AccumulatorExchangeAdapter : IProductionProcessAdapter
} }
else if (operatingParameters == null || else if (operatingParameters == null ||
!operatingParameters.TryGetValue("Mode0", out var selectedMode) || !operatingParameters.TryGetValue("Mode0", out var selectedMode) ||
!Finite(selectedMode) || selectedMode != Math.Truncate(selectedMode) || double.IsNaN(selectedMode) || double.IsInfinity(selectedMode) ||
selectedMode != Math.Truncate(selectedMode) ||
selectedMode < -1 || selectedMode > 1) selectedMode < -1 || selectedMode > 1)
{ {
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
@@ -126,4 +126,9 @@ public sealed class AccumulatorExchangeAdapter : IProductionProcessAdapter
? Array.Empty<KeyValuePair<int, double>>() : outputs); ? Array.Empty<KeyValuePair<int, double>>() : outputs);
return true; return true;
} }
private static bool FinitePositive(double value)
{
return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
}
} }
@@ -42,15 +42,17 @@ internal sealed class BlackBoxItemClassification
{ {
public bool IsFinalProduct { get; } public bool IsFinalProduct { get; }
public bool IsResearchProduct { get; } public bool IsResearchProduct { get; }
public bool IsIntermediate { get; }
public double IntermediateShortage { get; } public double IntermediateShortage { get; }
public double? OverbuildSurplus { get; } public double? OverbuildSurplus { get; }
public double? CoproductSurplus { get; } public double? CoproductSurplus { get; }
public BlackBoxItemClassification(bool isFinalProduct, bool isResearchProduct, double intermediateShortage, public BlackBoxItemClassification(bool isFinalProduct, bool isResearchProduct, bool isIntermediate,
double? overbuildSurplus, double? coproductSurplus) double intermediateShortage, double? overbuildSurplus, double? coproductSurplus)
{ {
IsFinalProduct = isFinalProduct; IsFinalProduct = isFinalProduct;
IsResearchProduct = isResearchProduct; IsResearchProduct = isResearchProduct;
IsIntermediate = isIntermediate;
IntermediateShortage = intermediateShortage; IntermediateShortage = intermediateShortage;
OverbuildSurplus = overbuildSurplus; OverbuildSurplus = overbuildSurplus;
CoproductSurplus = coproductSurplus; CoproductSurplus = coproductSurplus;
@@ -60,7 +62,6 @@ internal sealed class BlackBoxItemClassification
internal static class BlackBoxMaterialClassifier internal static class BlackBoxMaterialClassifier
{ {
internal const double Tolerance = 1e-9; internal const double Tolerance = 1e-9;
private const int MaximumSteadyStatePasses = 10000;
private sealed class ReductionGroup private sealed class ReductionGroup
{ {
@@ -147,7 +148,7 @@ internal static class BlackBoxMaterialClassifier
overbuild = Math.Min(Math.Max(0, originalNet), overbuild = Math.Min(Math.Max(0, originalNet),
Math.Max(0, originalNet - remainingBalance[itemId])); Math.Max(0, originalNet - remainingBalance[itemId]));
var necessaryJointProduction = groups.Sum(group => NecessaryJointProduction(group, itemId, var necessaryJointProduction = groups.Sum(group => NecessaryJointProduction(group, itemId,
originalBalance, remainingBalance, protectedItems)); originalBalance, remainingBalance, protectedItems, intermediateItems));
var internalConsumption = groups.Sum(group => var internalConsumption = groups.Sum(group =>
group.Source.NetPerBuilding.TryGetValue(itemId, out var amount) && amount < -Tolerance group.Source.NetPerBuilding.TryGetValue(itemId, out var amount) && amount < -Tolerance
? -amount * (group.Count - group.Removed) : 0); ? -amount * (group.Count - group.Removed) : 0);
@@ -160,17 +161,17 @@ internal static class BlackBoxMaterialClassifier
var isResearchProduct = finalKnown && researchMatrixSinks.Contains(itemId) && originalNet > Tolerance; var isResearchProduct = finalKnown && researchMatrixSinks.Contains(itemId) && originalNet > Tolerance;
classification[itemId] = new BlackBoxItemClassification( classification[itemId] = new BlackBoxItemClassification(
finalKnown && finalItems.Contains(itemId) || isResearchProduct, isResearchProduct, finalKnown && finalItems.Contains(itemId) || isResearchProduct, isResearchProduct,
isIntermediate ? Math.Max(0, -originalNet) : 0, overbuild, coproduct); isIntermediate, isIntermediate ? Math.Max(0, -originalNet) : 0, overbuild, coproduct);
} }
steadyStateBalance = CalculateSteadyStateBalance(groups, originalBalance, remainingBalance, steadyStateBalance = CalculateSteadyStateBalance(groups, originalBalance, remainingBalance,
protectedItems); protectedItems, intermediateItems);
return classification; return classification;
} }
private static double NecessaryJointProduction(ReductionGroup group, int itemId, private static double NecessaryJointProduction(ReductionGroup group, int itemId,
IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance, IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance,
ISet<int> protectedItems) ISet<int> protectedItems, ISet<int> intermediateItems)
{ {
var retained = group.Count - group.Removed; var retained = group.Count - group.Removed;
if (retained == 0 || !group.Source.HasJointProducts || if (retained == 0 || !group.Source.HasJointProducts ||
@@ -181,7 +182,10 @@ internal static class BlackBoxMaterialClassifier
foreach (var flow in group.Source.NetPerBuilding) foreach (var flow in group.Source.NetPerBuilding)
{ {
if (flow.Key == itemId || flow.Value <= Tolerance) continue; if (flow.Key == itemId || flow.Value <= Tolerance) continue;
var minimum = MinimumBalance(flow.Key, originalBalance, protectedItems); double minimum;
if (protectedItems.Contains(flow.Key)) minimum = originalBalance[flow.Key];
else if (intermediateItems.Contains(flow.Key)) minimum = Math.Min(0, originalBalance[flow.Key]);
else continue;
var available = Math.Floor((remainingBalance[flow.Key] - minimum + Tolerance) / flow.Value); var available = Math.Floor((remainingBalance[flow.Key] - minimum + Tolerance) / flow.Value);
removable = Math.Min(removable, Math.Max(0, available)); removable = Math.Min(removable, Math.Max(0, available));
} }
@@ -191,15 +195,14 @@ internal static class BlackBoxMaterialClassifier
private static IReadOnlyDictionary<int, double> CalculateSteadyStateBalance( private static IReadOnlyDictionary<int, double> CalculateSteadyStateBalance(
IReadOnlyList<ReductionGroup> groups, IReadOnlyDictionary<int, double> originalBalance, IReadOnlyList<ReductionGroup> groups, IReadOnlyDictionary<int, double> originalBalance,
IReadOnlyDictionary<int, double> remainingBalance, ISet<int> protectedItems) IReadOnlyDictionary<int, double> remainingBalance, ISet<int> protectedItems, ISet<int> intermediateItems)
{ {
var balance = remainingBalance.ToDictionary(entry => entry.Key, entry => entry.Value); var balance = remainingBalance.ToDictionary(entry => entry.Key, entry => entry.Value);
var available = groups.ToDictionary(group => group, group => (double)(group.Count - group.Removed)); var available = groups.ToDictionary(group => group, group => (double)(group.Count - group.Removed));
// A lossless cycle, such as charging and discharging accumulators, can pass a tiny leftover around bool changed;
// indefinitely; stopping early only leaves the input estimate conservative. do
for (var pass = 0; pass < MaximumSteadyStatePasses; pass++)
{ {
var changed = false; changed = false;
foreach (var group in groups) foreach (var group in groups)
{ {
if (!group.Source.NetPerBuilding.Values.Any(value => value > Tolerance)) continue; if (!group.Source.NetPerBuilding.Values.Any(value => value > Tolerance)) continue;
@@ -207,7 +210,10 @@ internal static class BlackBoxMaterialClassifier
foreach (var flow in group.Source.NetPerBuilding) foreach (var flow in group.Source.NetPerBuilding)
{ {
if (flow.Value <= Tolerance) continue; if (flow.Value <= Tolerance) continue;
var minimum = MinimumBalance(flow.Key, originalBalance, protectedItems); double minimum;
if (protectedItems.Contains(flow.Key)) minimum = originalBalance[flow.Key];
else if (intermediateItems.Contains(flow.Key)) minimum = Math.Min(0, originalBalance[flow.Key]);
else continue;
reducible = Math.Min(reducible, Math.Max(0, (balance[flow.Key] - minimum) / flow.Value)); reducible = Math.Min(reducible, Math.Max(0, (balance[flow.Key] - minimum) / flow.Value));
} }
@@ -217,21 +223,11 @@ internal static class BlackBoxMaterialClassifier
available[group] -= reducible; available[group] -= reducible;
changed = true; changed = true;
} }
} while (changed);
if (!changed) break;
}
return balance; return balance;
} }
// Every positive process output is a protected or intermediate item. Protected balances may not fall below
// their full-load value, and intermediates may not gain a new or larger shortage.
private static double MinimumBalance(int itemId, IReadOnlyDictionary<int, double> originalBalance,
ISet<int> protectedItems)
{
return protectedItems.Contains(itemId) ? originalBalance[itemId] : Math.Min(0, originalBalance[itemId]);
}
private static bool CanRemove(IReadOnlyDictionary<int, double> netPerBuilding, private static bool CanRemove(IReadOnlyDictionary<int, double> netPerBuilding,
IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance, IReadOnlyDictionary<int, double> originalBalance, IReadOnlyDictionary<int, double> remainingBalance,
ISet<int> protectedItems, ISet<int> intermediateItems) ISet<int> protectedItems, ISet<int> intermediateItems)
@@ -1,148 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production;
internal static class BlueprintBottleneckBalance
{
private const double Tolerance = 1e-7;
internal static bool TryCalculate(IReadOnlyList<BlackBoxProcessGroup> processes,
IReadOnlyDictionary<int, double> production, IReadOnlyDictionary<int, double> consumption,
ISet<int> researchMatrixSinks,
out SortedDictionary<int, double> balancedProduction, out SortedDictionary<int, double> balancedConsumption,
out IReadOnlyDictionary<int, BlackBoxItemClassification> balancedClassifications,
out IReadOnlyDictionary<int, double> balancedNet)
{
balancedProduction = null;
balancedConsumption = null;
balancedClassifications = null;
balancedNet = null;
if (production.Count == 0 && consumption.Count == 0)
{
balancedProduction = new SortedDictionary<int, double>();
balancedConsumption = new SortedDictionary<int, double>();
balancedClassifications = new Dictionary<int, BlackBoxItemClassification>();
balancedNet = new Dictionary<int, double>();
return true;
}
var groups = processes.GroupBy(process => process.StableKey, StringComparer.Ordinal)
.OrderBy(group => group.Key, StringComparer.Ordinal)
.Select(group => (source: group.First(), count: group.Sum(process => process.Count))).ToArray();
var produced = new HashSet<int>(groups.SelectMany(group => group.source.NetPerBuilding)
.Where(flow => flow.Value > BlackBoxMaterialClassifier.Tolerance).Select(flow => flow.Key));
var consumed = new HashSet<int>(groups.SelectMany(group => group.source.NetPerBuilding)
.Where(flow => flow.Value < -BlackBoxMaterialClassifier.Tolerance).Select(flow => flow.Key));
var items = produced.OrderBy(itemId => itemId).ToArray();
// Normalize only the scale variable; the solver still resolves shared demand, recipe ratios, and cycles together.
var commonScale = items.Where(consumed.Contains).Select(itemId => production[itemId] / consumption[itemId])
.Aggregate(1.0, Math.Min);
var targets = items.Where(itemId => !consumed.Contains(itemId) || researchMatrixSinks.Contains(itemId))
.ToDictionary(itemId => itemId, itemId => Math.Max(0, production[itemId] -
(consumption.TryGetValue(itemId, out var amount) ? amount : 0)));
// Launchers, generators, and precise research can terminate a chain without an item output.
var sinks = Enumerable.Range(0, groups.Length).Where(index =>
groups[index].source.NetPerBuilding.Values.Any(value => value < -BlackBoxMaterialClassifier.Tolerance) &&
!groups[index].source.NetPerBuilding.Values.Any(value => value > BlackBoxMaterialClassifier.Tolerance))
.ToArray();
if (!targets.Values.Any(FinitePositive) && sinks.Length == 0) return false;
var scaleColumn = groups.Length;
var surplusStart = scaleColumn + 1;
var capacitySlackStart = surplusStart + items.Length;
var columnCount = capacitySlackStart + groups.Length + 1;
var matrix = new double[items.Length + groups.Length + 1 + sinks.Length, columnCount];
var rhs = new double[matrix.GetLength(0)];
var maximizeOutput = new double[columnCount];
var minimizeUse = new double[columnCount];
var minimizeSurplus = new double[columnCount];
maximizeOutput[scaleColumn] = -1;
for (var row = 0; row < items.Length; row++)
{
var itemId = items[row];
var rowScale = Math.Max(production[itemId], consumption.TryGetValue(itemId, out var amount) ? amount : 0);
for (var index = 0; index < groups.Length; index++)
if (groups[index].source.NetPerBuilding.TryGetValue(itemId, out var net))
matrix[row, index] = net * groups[index].count / rowScale;
if (targets.TryGetValue(itemId, out var target)) matrix[row, scaleColumn] = -target / rowScale * commonScale;
matrix[row, surplusStart + row] = -1;
minimizeSurplus[surplusStart + row] = 1;
}
for (var index = 0; index <= groups.Length; index++)
{
var row = items.Length + index;
matrix[row, index] = index < groups.Length ? 1 : commonScale;
matrix[row, capacitySlackStart + index] = 1;
rhs[row] = 1;
if (index < groups.Length) minimizeUse[index] = groups[index].count;
}
for (var index = 0; index < sinks.Length; index++)
{
var row = items.Length + groups.Length + 1 + index;
matrix[row, sinks[index]] = 1;
matrix[row, scaleColumn] = -commonScale;
}
var solution = TwoPhaseSimplex.Solve(matrix, rhs,
new[] { maximizeOutput, minimizeUse, minimizeSurplus }, 20000, CancellationToken.None);
if (solution.Status != LinearSolveStatus.Optimal || !FinitePositive(solution.Values[scaleColumn])) return false;
for (var row = 0; row < rhs.Length; row++)
{
var residual = -rhs[row];
for (var column = 0; column < columnCount; column++) residual += matrix[row, column] * solution.Values[column];
if (Math.Abs(residual) > Tolerance) return false;
}
balancedProduction = new SortedDictionary<int, double>(production.ToDictionary(flow => flow.Key, _ => 0.0));
balancedConsumption = new SortedDictionary<int, double>(consumption.ToDictionary(flow => flow.Key, _ => 0.0));
var unusedProduction = new Dictionary<int, double>();
for (var index = 0; index < groups.Length; index++)
{
var group = groups[index];
var utilized = Math.Min(1, solution.Values[index]) * group.count;
var executions = group.source.Process.CyclesPerBuildingPerMinute * utilized;
foreach (var flow in group.source.Process.OutputsPerCycle)
AddFlow(balancedProduction, flow.Key, flow.Value * executions);
foreach (var flow in group.source.Process.InputsPerCycle)
AddFlow(balancedConsumption, flow.Key, flow.Value * executions);
foreach (var flow in group.source.NetPerBuilding)
if (flow.Value > 0) AddFlow(unusedProduction, flow.Key, flow.Value * (group.count - utilized));
}
var netFlows = new Dictionary<int, double>();
var result = new Dictionary<int, BlackBoxItemClassification>();
var allItems = new SortedSet<int>(production.Keys);
allItems.UnionWith(consumption.Keys);
foreach (var itemId in allItems)
{
var grossProduced = balancedProduction.TryGetValue(itemId, out var p) ? p : 0;
var grossConsumed = balancedConsumption.TryGetValue(itemId, out var c) ? c : 0;
var net = grossProduced - grossConsumed;
if (targets.TryGetValue(itemId, out var target))
{
var required = target * solution.Values[scaleColumn] * commonScale;
if (net < required - Tolerance * Math.Max(1, required)) return false;
}
if (Math.Abs(net) <= Tolerance * Math.Max(1, Math.Max(grossProduced, grossConsumed))) net = 0;
netFlows[itemId] = net;
var intermediate = produced.Contains(itemId) && consumed.Contains(itemId);
if (intermediate && net < 0) return false;
var research = researchMatrixSinks.Contains(itemId);
var researchProduct = research && net > 0;
result[itemId] = new BlackBoxItemClassification(produced.Contains(itemId) && !consumed.Contains(itemId) || researchProduct,
researchProduct, 0,
intermediate && !research && unusedProduction.TryGetValue(itemId, out var unused) ? unused : 0,
intermediate && !research ? Math.Max(0, net) : 0);
}
balancedClassifications = result;
balancedNet = netFlows;
return true;
}
}
+63 -56
View File
@@ -2,7 +2,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization; using System.Globalization;
using System.Linq; using System.Linq;
using static UXAssist.Production.ProductionMath; using System.Text;
namespace UXAssist.Production; namespace UXAssist.Production;
@@ -64,8 +64,6 @@ public sealed class BlueprintDescriptionText
public static class BlueprintDescriptionFormatter public static class BlueprintDescriptionFormatter
{ {
private const double Tolerance = 1e-9; private const double Tolerance = 1e-9;
private static readonly string[] RateUnits = { "K", "M", "G" };
private static readonly string[] PowerUnits = { "W", "kW", "MW", "GW", "TW" };
public static BlueprintDescriptionText Format(ProductionReport report, Func<int, string> itemTag, public static BlueprintDescriptionText Format(ProductionReport report, Func<int, string> itemTag,
BlueprintDescriptionLabels labels) BlueprintDescriptionLabels labels)
@@ -88,8 +86,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 +96,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)
@@ -149,50 +146,27 @@ public static class BlueprintDescriptionFormatter
var tag = itemTag(itemId); var tag = itemTag(itemId);
if (string.IsNullOrEmpty(tag)) if (string.IsNullOrEmpty(tag))
throw new InvalidOperationException("An item in the blueprint report has no native icon tag."); throw new InvalidOperationException("An item in the blueprint report has no native icon tag.");
return tag + " x" + FormatRate(rate); return tag + " x" + FormatNumber(rate);
}
private static string FormatRate(double value)
{
var rounded = RoundForDisplay(value);
for (var unit = RateUnits.Length - 1; unit >= 0; unit--)
{
var scale = Math.Pow(1000, unit + 1);
// Keep the existing display precision; abbreviate only exact tenths of a unit.
if (rounded >= scale && rounded % (scale / 10) == 0)
return (rounded / scale).ToString("#,##0.#", CultureInfo.InvariantCulture) + RateUnits[unit];
}
return FormatNumber(value);
} }
private static string FormatPower(double? watts, BlueprintDescriptionLabels labels) private static string FormatPower(double? watts, BlueprintDescriptionLabels labels)
{ {
if (!watts.HasValue) return labels.Unknown; if (!watts.HasValue) return labels.Unknown;
var value = watts.Value; var value = watts.Value;
var unit = 0; if (value >= 1e12) return FormatNumber(value / 1e12) + "TW";
// Choose the unit after rounding so that 999.999 W displays as 1kW rather than 1000W. if (value >= 1e9) return FormatNumber(value / 1e9) + "GW";
while (unit < PowerUnits.Length - 1 && RoundForDisplay(value) >= 1000) if (value >= 1e6) return FormatNumber(value / 1e6) + "MW";
{ if (value >= 1e3) return FormatNumber(value / 1e3) + "kW";
value /= 1000; return FormatNumber(value) + "W";
unit++;
}
return FormatNumber(value) + PowerUnits[unit];
}
private static double RoundForDisplay(double value)
{
return Math.Round(value, value < 1 ? 3 : 2, MidpointRounding.AwayFromZero);
} }
private static string FormatNumber(double value) private static string FormatNumber(double value)
{ {
if (!FiniteNonnegative(value)) if (double.IsNaN(value) || double.IsInfinity(value) || value < 0)
throw new InvalidOperationException("A blueprint report contains an invalid rate or power value."); throw new InvalidOperationException("A blueprint report contains an invalid rate or power value.");
var rounded = RoundForDisplay(value); var rounded = Math.Round(value, value < 1 ? 3 : 2, MidpointRounding.AwayFromZero);
if (rounded > 0 || value == 0) if (rounded > 0 || value == 0)
return rounded.ToString(value < 1 ? "0.###" : "#,##0.##", CultureInfo.InvariantCulture); return rounded.ToString(value < 1 ? "0.###" : "0.##", CultureInfo.InvariantCulture);
var precise = value.ToString("0.######", CultureInfo.InvariantCulture); var precise = value.ToString("0.######", CultureInfo.InvariantCulture);
return precise != "0" ? precise : value.ToString("0.###E+0", CultureInfo.InvariantCulture); return precise != "0" ? precise : value.ToString("0.###E+0", CultureInfo.InvariantCulture);
} }
@@ -241,41 +215,74 @@ public static class BlueprintDescriptionFields
return true; return true;
} }
// Updates the first matching field in place and drops other matches; a null value removes them all. A new field public static BlueprintFieldUpdateResult TryUpdate(string existing, IReadOnlyList<BlueprintDescriptionField> fields,
// is appended only when it fits, so other fields are never removed to make room.
public static BlueprintFieldUpdateResult TryUpdate(string existing, BlueprintDescriptionField field,
int maximumFields, Func<string, string> escape, Func<string, string> unescape, out string updated) int maximumFields, Func<string, string> escape, Func<string, string> unescape, out string updated)
{ {
updated = existing; updated = existing;
if (field == null || escape == null || unescape == null) if (fields == null || escape == null || unescape == null)
throw new ArgumentNullException(field == null ? nameof(field) : escape == null ? nameof(escape) : nameof(unescape)); throw new ArgumentNullException(fields == null ? nameof(fields) : escape == null ? nameof(escape) : nameof(unescape));
if (maximumFields < 0 || !IsNativeFormatValid(existing)) if (maximumFields < 0 || !IsNativeFormatValid(existing))
return BlueprintFieldUpdateResult.InvalidFields; return BlueprintFieldUpdateResult.InvalidFields;
var generated = field.Value == null ? null : escape(field.Title) + ":" + escape(field.Value);
var parts = (existing ?? "").Split(';'); var parts = (existing ?? "").Split(';');
var entries = new List<string>(); var matches = new int[parts.Length];
var replaced = false; var found = new bool[fields.Count];
var nativeCount = 0;
var removedCount = 0;
for (var index = 0; index < parts.Length - 1; index++) for (var index = 0; index < parts.Length - 1; index++)
{ {
if (!field.Matches(unescape(parts[index].Substring(0, parts[index].IndexOf(':'))))) var delimiter = parts[index].IndexOf(':');
nativeCount++;
var name = unescape(parts[index].Substring(0, delimiter));
for (var fieldIndex = 0; fieldIndex < fields.Count; fieldIndex++)
{ {
entries.Add(parts[index]); if (!fields[fieldIndex].Matches(name)) continue;
if (fields[fieldIndex].Value == null || found[fieldIndex])
{
matches[index] = -1;
removedCount++;
} }
else if (generated != null && !replaced) else
{ {
entries.Add(generated); matches[index] = fieldIndex + 1;
replaced = true; found[fieldIndex] = true;
}
break;
} }
} }
if (generated != null && !replaced) var missingCount = 0;
for (var index = 0; index < fields.Count; index++)
if (!found[index] && fields[index].Value != null) missingCount++;
if (nativeCount - removedCount + missingCount > maximumFields)
return BlueprintFieldUpdateResult.CapacityExceeded;
var serialized = new StringBuilder();
for (var index = 0; index < parts.Length - 1; index++)
{ {
if (entries.Count >= maximumFields) return BlueprintFieldUpdateResult.CapacityExceeded; var match = matches[index];
entries.Add(generated); if (match < 0) continue;
if (match > 0)
{
var field = fields[match - 1];
serialized.Append(escape(field.Title)).Append(':').Append(escape(field.Value));
}
else
{
serialized.Append(parts[index]);
} }
updated = string.Concat(entries.Select(entry => entry + ";")); serialized.Append(';');
}
for (var index = 0; index < fields.Count; index++)
{
if (!found[index] && fields[index].Value != null)
serialized.Append(escape(fields[index].Title)).Append(':').Append(escape(fields[index].Value))
.Append(';');
}
updated = serialized.ToString();
return BlueprintFieldUpdateResult.Updated; return BlueprintFieldUpdateResult.Updated;
} }
} }
+14 -23
View File
@@ -35,11 +35,13 @@ public sealed class BlueprintSelectionCapture
public static class BlueprintSelectionReader public static class BlueprintSelectionReader
{ {
// Native station parameters store charging power at this index, followed by other station settings. public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable<int> selectedObjectIds)
private const int StationSettingsIndex = 320; {
return Capture(factory, selectedObjectIds, null);
}
public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable<int> selectedObjectIds, public static BlueprintSelectionCapture Capture(PlanetFactory factory, IEnumerable<int> selectedObjectIds,
BlueprintSelectionContext context = null) BlueprintSelectionContext context)
{ {
var catalog = ProductionCatalogService.Current; var catalog = ProductionCatalogService.Current;
if (factory == null || catalog == null) if (factory == null || catalog == null)
@@ -79,18 +81,21 @@ public static class BlueprintSelectionReader
var operation = new Dictionary<string, double>(); var operation = new Dictionary<string, double>();
var speedFactor = GetLiveSpeed(factory, objectId, parameters.type, operation); var speedFactor = GetLiveSpeed(factory, objectId, parameters.type, operation);
AddSettings(parameters, operation); AddSettings(parameters, operation);
var storedParameters = objectId < 0 ? factory.prebuildPool[-objectId].parameters : null;
if (building.Kind == ProductionBuildingKind.Logistics) if (building.Kind == ProductionBuildingKind.Logistics)
{ {
if (objectId > 0) CaptureLiveChargePower(factory, objectId, operation); if (objectId > 0)
else CaptureStoredChargePower(building, parameters, storedParameters, operation); CaptureLiveChargePower(factory, objectId, operation);
else
{
ref var prebuild = ref factory.prebuildPool[-objectId];
CaptureStoredChargePower(building, parameters, prebuild.parameters, operation);
}
} }
if (operation.ContainsKey("ResearchMode")) CaptureResearchSettings(factory, operation); if (operation.ContainsKey("ResearchMode")) CaptureResearchSettings(factory, operation);
switch (building.Kind) switch (building.Kind)
{ {
case ProductionBuildingKind.Miner: case ProductionBuildingKind.Miner:
CaptureMiningSettings(factory, objectId, building, operation); CaptureMiningSettings(factory, objectId, building, operation);
if (objectId < 0) CaptureStoredMinerSpeed(parameters, storedParameters, operation);
break; break;
case ProductionBuildingKind.Collector: case ProductionBuildingKind.Collector:
CaptureCollectionSettings(factory, operation); CaptureCollectionSettings(factory, operation);
@@ -172,8 +177,6 @@ public static class BlueprintSelectionReader
operation["ResearchMatrixSink"] = 1; operation["ResearchMatrixSink"] = 1;
if (building.Kind == ProductionBuildingKind.Logistics) if (building.Kind == ProductionBuildingKind.Logistics)
CaptureStoredChargePower(building, parameters, blueprint.parameters, operation); CaptureStoredChargePower(building, parameters, blueprint.parameters, operation);
else if (building.Kind == ProductionBuildingKind.Miner)
CaptureStoredMinerSpeed(parameters, blueprint.parameters, operation);
ApplySupplied(context?.OperatingParametersByIndex, blueprint.index, operation); ApplySupplied(context?.OperatingParametersByIndex, blueprint.index, operation);
snapshots.Add(CreateSnapshot(catalog, building, 0, parameters, parameters.recipeId, null, operation, snapshots.Add(CreateSnapshot(catalog, building, 0, parameters, parameters.recipeId, null, operation,
diagnostics)); diagnostics));
@@ -228,9 +231,8 @@ public static class BlueprintSelectionReader
{ {
case BuildingType.Station: case BuildingType.Station:
if (storedParameters != null && if (storedParameters != null &&
storedParameters.Length >= BuildingParameters.kStationParamsLength && storedParameters.Length >= BuildingParameters.kStationParamsLength && storedParameters[320] > 0)
storedParameters[StationSettingsIndex] > 0) watts = storedParameters[320] * ProductionUnits.TicksPerSecond;
watts = storedParameters[StationSettingsIndex] * ProductionUnits.TicksPerSecond;
break; break;
case BuildingType.Dispenser: case BuildingType.Dispenser:
if (storedParameters != null && storedParameters.Length >= BuildingParameters.kAddonParamsLength) if (storedParameters != null && storedParameters.Length >= BuildingParameters.kAddonParamsLength)
@@ -248,17 +250,6 @@ public static class BlueprintSelectionReader
operation["ChargePowerWatts"] = watts; operation["ChargePowerWatts"] = watts;
} }
// Advanced Mining Machines store their speed with the station settings; native construction restores it.
private static void CaptureStoredMinerSpeed(BuildingParameters parameters, int[] storedParameters,
IDictionary<string, double> operation)
{
if (parameters.type == BuildingType.Station && storedParameters != null &&
storedParameters.Length >= BuildingParameters.kStationParamsLength &&
storedParameters[StationSettingsIndex] > 0 && storedParameters[StationSettingsIndex + 9] > 0)
operation["MachineSpeedFactor"] =
storedParameters[StationSettingsIndex + 9] / ProductionUnits.FixedPointScale;
}
private static ProductionBuildingSnapshot CreateSnapshot(ProductionCatalog catalog, ProductionBuilding building, private static ProductionBuildingSnapshot CreateSnapshot(ProductionCatalog catalog, ProductionBuilding building,
int objectId, BuildingParameters parameters, int recipeId, double? speedFactor, int objectId, BuildingParameters parameters, int recipeId, double? speedFactor,
Dictionary<string, double> operation, ICollection<ProductionDiagnostic> diagnostics) Dictionary<string, double> operation, ICollection<ProductionDiagnostic> diagnostics)
+63 -51
View File
@@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production; namespace UXAssist.Production;
@@ -31,18 +30,11 @@ public sealed class ProductionBuildingSnapshot
} }
} }
public enum BlueprintProductionBasis
{
FinalProducts,
BottleneckIntermediate
}
public sealed class FactoryBlackBoxRequest public sealed class FactoryBlackBoxRequest
{ {
public List<ProductionBuildingSnapshot> Buildings { get; } = new List<ProductionBuildingSnapshot>(); public List<ProductionBuildingSnapshot> Buildings { get; } = new List<ProductionBuildingSnapshot>();
public List<ProductionDiagnostic> CaptureDiagnostics { get; } = new List<ProductionDiagnostic>(); public List<ProductionDiagnostic> CaptureDiagnostics { get; } = new List<ProductionDiagnostic>();
public bool ProliferationEnabled { get; set; } public bool ProliferationEnabled { get; set; }
public BlueprintProductionBasis ProductionBasis { get; set; }
} }
public sealed class FactoryBlackBoxAnalyzer public sealed class FactoryBlackBoxAnalyzer
@@ -72,6 +64,7 @@ public sealed class FactoryBlackBoxAnalyzer
var grossConsumption = new SortedDictionary<int, double>(); var grossConsumption = new SortedDictionary<int, double>();
var producers = new Dictionary<int, List<int>>(); var producers = new Dictionary<int, List<int>>();
var consumers = new Dictionary<int, List<int>>(); var consumers = new Dictionary<int, List<int>>();
var smallestProducer = new Dictionary<int, double>();
var hasResearchMatrixSink = false; var hasResearchMatrixSink = false;
var uncertainDemandItems = new HashSet<int>(); var uncertainDemandItems = new HashSet<int>();
var selectedIds = new HashSet<int>(); var selectedIds = new HashSet<int>();
@@ -144,7 +137,8 @@ public sealed class FactoryBlackBoxAnalyzer
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter, diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.MissingOperatingParameter,
"The selected logistics facility needs its configured charging power.", "The selected logistics facility needs its configured charging power.",
buildingItemId: snapshot.BuildingItemId)); buildingItemId: snapshot.BuildingItemId));
else if (!FiniteNonnegative(chargePowerWatts * snapshot.Count)) else if (chargePowerWatts < 0 || double.IsNaN(chargePowerWatts) ||
double.IsInfinity(chargePowerWatts * snapshot.Count))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected logistics charging power must be finite and nonnegative.", "The selected logistics charging power must be finite and nonnegative.",
buildingItemId: snapshot.BuildingItemId)); buildingItemId: snapshot.BuildingItemId));
@@ -153,7 +147,9 @@ public sealed class FactoryBlackBoxAnalyzer
if (logisticsWatts.HasValue) logisticsConsumptionWatts += logisticsWatts.Value; if (logisticsWatts.HasValue) logisticsConsumptionWatts += logisticsWatts.Value;
else logisticsPowerComplete = false; else logisticsPowerComplete = false;
groups.Add(PowerOnlyGroup(snapshot.Count, logisticsWatts)); groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
logisticsWatts, logisticsWatts, Array.Empty<KeyValuePair<int, double>>(),
Array.Empty<KeyValuePair<int, double>>()));
continue; continue;
} }
@@ -167,7 +163,9 @@ public sealed class FactoryBlackBoxAnalyzer
var idleWatts = (building.Kind == ProductionBuildingKind.Auxiliary var idleWatts = (building.Kind == ProductionBuildingKind.Auxiliary
? building.WorkingPowerWatts : building.IdlePowerWatts) * snapshot.Count; ? building.WorkingPowerWatts : building.IdlePowerWatts) * snapshot.Count;
factoryConsumptionWatts += idleWatts; factoryConsumptionWatts += idleWatts;
groups.Add(PowerOnlyGroup(snapshot.Count, idleWatts)); groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
idleWatts, idleWatts, Array.Empty<KeyValuePair<int, double>>(),
Array.Empty<KeyValuePair<int, double>>()));
continue; continue;
} }
} }
@@ -210,7 +208,9 @@ public sealed class FactoryBlackBoxAnalyzer
{ {
if (!IsResearchModeLab(building, snapshot)) totalPowerKnown = false; if (!IsResearchModeLab(building, snapshot)) totalPowerKnown = false;
factoryConsumptionWatts += knownWatts; factoryConsumptionWatts += knownWatts;
groups.Add(PowerOnlyGroup(snapshot.Count, knownWatts)); groups.Add(new ProductionGroupFlow(null, snapshot.Count, 0, snapshot.Count, snapshot.Count,
knownWatts, knownWatts, Array.Empty<KeyValuePair<int, double>>(),
Array.Empty<KeyValuePair<int, double>>()));
} }
else else
{ {
@@ -222,20 +222,26 @@ public sealed class FactoryBlackBoxAnalyzer
if (diagnostic != null) diagnostics.Add(diagnostic); if (diagnostic != null) diagnostics.Add(diagnostic);
if (!process.PowerKnown) totalPowerKnown = false; if (!process.PowerKnown) totalPowerKnown = false;
if (!FiniteNonnegative(process.WorkingPowerWatts * snapshot.Count)) factoryPowerComplete = false; if (process.WorkingPowerWatts < 0 || double.IsNaN(process.WorkingPowerWatts) ||
double.IsInfinity(process.WorkingPowerWatts * snapshot.Count)) factoryPowerComplete = false;
var cycleRate = process.CyclesPerBuildingPerMinute; var cycleRate = process.CyclesPerBuildingPerMinute;
var output = ScaleFlows(process.OutputsPerCycle, cycleRate * snapshot.Count); var output = Scale(process.OutputsPerCycle, cycleRate * snapshot.Count);
var input = ScaleFlows(process.InputsPerCycle, cycleRate * snapshot.Count); var input = Scale(process.InputsPerCycle, cycleRate * snapshot.Count);
var groupIndex = groups.Count; var groupIndex = groups.Count;
foreach (var flow in output) foreach (var flow in output)
{ {
AddFlow(grossProduction, flow.Key, flow.Value); Add(grossProduction, flow.Key, flow.Value);
AddGroup(producers, flow.Key, groupIndex); AddGroup(producers, flow.Key, groupIndex);
var perBuildingNet = (process.OutputsPerCycle[flow.Key] -
(process.InputsPerCycle.TryGetValue(flow.Key, out var consumed) ? consumed : 0)) * cycleRate;
if (perBuildingNet > 1e-9 &&
(!smallestProducer.TryGetValue(flow.Key, out var previous) || perBuildingNet < previous))
smallestProducer[flow.Key] = perBuildingNet;
} }
foreach (var flow in input) foreach (var flow in input)
{ {
AddFlow(grossConsumption, flow.Key, flow.Value); Add(grossConsumption, flow.Key, flow.Value);
AddGroup(consumers, flow.Key, groupIndex); AddGroup(consumers, flow.Key, groupIndex);
} }
@@ -257,27 +263,8 @@ public sealed class FactoryBlackBoxAnalyzer
var matrixSinkItems = hasResearchMatrixSink var matrixSinkItems = hasResearchMatrixSink
? new HashSet<int>(_catalog.ResearchMatrixItemIds) : new HashSet<int>(); ? new HashSet<int>(_catalog.ResearchMatrixItemIds) : new HashSet<int>();
IReadOnlyDictionary<int, BlackBoxItemClassification> classifications = null; var classifications = BlackBoxMaterialClassifier.Classify(processGroups, grossProduction, grossConsumption,
IReadOnlyDictionary<int, double> steadyStateBalance = null; materialComplete, uncertainDemandItems, unknownDemand, matrixSinkItems, out var steadyStateBalance);
if (request.ProductionBasis == BlueprintProductionBasis.BottleneckIntermediate)
{
if (!materialComplete || !BlueprintBottleneckBalance.TryCalculate(processGroups,
grossProduction, grossConsumption, matrixSinkItems,
out var balancedProduction, out var balancedConsumption, out var balancedClassifications,
out var balancedNet))
diagnostics.Add(new ProductionDiagnostic(ProductionDiagnosticCode.BlueprintBasisUnavailable,
"A complete material selection with a feasible final output is required for the bottleneck basis."));
else
{
grossProduction = balancedProduction;
grossConsumption = balancedConsumption;
classifications = balancedClassifications;
steadyStateBalance = balancedNet;
}
}
if (classifications == null)
classifications = BlackBoxMaterialClassifier.Classify(processGroups, grossProduction, grossConsumption,
materialComplete, uncertainDemandItems, unknownDemand, matrixSinkItems, out steadyStateBalance);
var flows = new List<ProductionItemFlow>(); var flows = new List<ProductionItemFlow>();
var allItems = new SortedSet<int>(grossProduction.Keys); var allItems = new SortedSet<int>(grossProduction.Keys);
allItems.UnionWith(grossConsumption.Keys); allItems.UnionWith(grossConsumption.Keys);
@@ -286,13 +273,19 @@ public sealed class FactoryBlackBoxAnalyzer
var produced = grossProduction.TryGetValue(itemId, out var p) ? p : 0; var produced = grossProduction.TryGetValue(itemId, out var p) ? p : 0;
var consumed = grossConsumption.TryGetValue(itemId, out var c) ? c : 0; var consumed = grossConsumption.TryGetValue(itemId, out var c) ? c : 0;
var net = produced - consumed; var net = produced - consumed;
var threshold = smallestProducer.TryGetValue(itemId, out var single) ? single : 0;
var classification = classifications[itemId]; var classification = classifications[itemId];
var isFinalProduct = classification.IsFinalProduct;
flows.Add(new ProductionItemFlow(itemId, produced, consumed, 0, 0, 0, flows.Add(new ProductionItemFlow(itemId, produced, consumed, 0, 0, 0,
Math.Max(0, net), Math.Max(0, -net), classification.IsFinalProduct, Math.Max(0, net), Math.Max(0, -net), isFinalProduct,
producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty<int>(), classification.IsIntermediate && !matrixSinkItems.Contains(itemId) &&
net > 1e-9 && threshold > 0 &&
net + 1e-9 >= threshold,
threshold, producers.TryGetValue(itemId, out var producing) ? producing : Array.Empty<int>(),
consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty<int>(), consumers.TryGetValue(itemId, out var usingItem) ? usingItem : Array.Empty<int>(),
classification.IntermediateShortage, classification.OverbuildSurplus, classification.IntermediateShortage, classification.OverbuildSurplus,
classification.CoproductSurplus, Math.Max(0, -steadyStateBalance[itemId]), classification.CoproductSurplus,
steadyStateBalance == null ? null : Math.Max(0, -steadyStateBalance[itemId]),
classification.IsResearchProduct)); classification.IsResearchProduct));
} }
@@ -342,13 +335,17 @@ public sealed class FactoryBlackBoxAnalyzer
watts = 0; watts = 0;
if (IsResearchModeLab(building, snapshot)) if (IsResearchModeLab(building, snapshot))
{ {
// Research-mode labs only receive extra products, and only when a proliferation level exists.
var multiplier = 1.0; var multiplier = 1.0;
if (mode != ProliferationMode.None && if (mode != ProliferationMode.None)
!_catalog.TryGetProliferation(_catalog.MaximumProliferationLevel, out _, out _, out multiplier)) {
return false; if (mode != ProliferationMode.ExtraProducts) return false;
if (_catalog.MaximumProliferationLevel > 0 &&
!_catalog.TryGetProliferation(_catalog.MaximumProliferationLevel,
out _, out _, out multiplier)) return false;
}
watts = building.WorkingPowerWatts * multiplier * snapshot.Count; watts = building.WorkingPowerWatts * multiplier * snapshot.Count;
return FinitePositive(watts); return watts > 0 && !double.IsNaN(watts) && !double.IsInfinity(watts);
} }
if (diagnostic?.Code != ProductionDiagnosticCode.MissingOperatingParameter) return false; if (diagnostic?.Code != ProductionDiagnosticCode.MissingOperatingParameter) return false;
@@ -357,10 +354,10 @@ public sealed class FactoryBlackBoxAnalyzer
var speed = snapshot.OperatingParameters.TryGetValue("MachineSpeedFactor", out var capturedSpeed) var speed = snapshot.OperatingParameters.TryGetValue("MachineSpeedFactor", out var capturedSpeed)
? capturedSpeed : 1; ? capturedSpeed : 1;
if (!FinitePositive(speed)) return false; if (speed <= 0 || double.IsNaN(speed) || double.IsInfinity(speed)) return false;
var ratio = speed * speed; var ratio = speed * speed;
watts = (building.WorkingPowerWatts * ratio + building.IdlePowerWatts * (1 - ratio)) * snapshot.Count; watts = (building.WorkingPowerWatts * ratio + building.IdlePowerWatts * (1 - ratio)) * snapshot.Count;
return FiniteNonnegative(watts); return watts >= 0 && !double.IsNaN(watts) && !double.IsInfinity(watts);
} }
private static bool IsResearchModeLab(ProductionBuilding building, ProductionBuildingSnapshot snapshot) private static bool IsResearchModeLab(ProductionBuilding building, ProductionBuildingSnapshot snapshot)
@@ -370,9 +367,24 @@ public sealed class FactoryBlackBoxAnalyzer
snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchMode) && researchMode == 1; snapshot.OperatingParameters.TryGetValue("ResearchMode", out var researchMode) && researchMode == 1;
} }
private static ProductionGroupFlow PowerOnlyGroup(int count, double? watts) private static Dictionary<int, double> Scale(IReadOnlyDictionary<int, double> flows, double factor)
{ {
return new ProductionGroupFlow(null, count, 0, count, count, watts, watts, return flows.ToDictionary(entry => entry.Key, entry => entry.Value * factor);
Array.Empty<KeyValuePair<int, double>>(), Array.Empty<KeyValuePair<int, double>>()); }
private static void Add(IDictionary<int, double> flows, int itemId, double count)
{
flows[itemId] = (flows.TryGetValue(itemId, out var previous) ? previous : 0) + count;
}
private static void AddGroup(IDictionary<int, List<int>> groups, int itemId, int index)
{
if (!groups.TryGetValue(itemId, out var indices))
{
indices = new List<int>();
groups[itemId] = indices;
}
indices.Add(index);
} }
} }
@@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production; namespace UXAssist.Production;
@@ -76,4 +75,9 @@ public sealed class FractionationProcessAdapter : IProductionProcessAdapter
throughput, watts, building != null, throughput); throughput, watts, building != null, throughput);
return true; return true;
} }
private static bool FinitePositive(double value)
{
return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
}
} }
+6 -4
View File
@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production; namespace UXAssist.Production;
@@ -18,7 +17,8 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
process = null; process = null;
diagnostic = null; diagnostic = null;
if (operatingParameters == null || if (operatingParameters == null ||
!operatingParameters.TryGetValue("FuelItemId", out var fuelId) || !PositiveId(fuelId) || !operatingParameters.TryGetValue("FuelItemId", out var fuelId) ||
fuelId <= 0 || fuelId > int.MaxValue || fuelId != Math.Truncate(fuelId) ||
!catalog.Items.TryGetValue((int)fuelId, out var fuel) || !catalog.Items.TryGetValue((int)fuelId, out var fuel) ||
fuel.HeatValueJoules <= 0 || (fuel.FuelTypeMask & building.FuelMask) == 0) fuel.HeatValueJoules <= 0 || (fuel.FuelTypeMask & building.FuelMask) == 0)
{ {
@@ -37,7 +37,8 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
return false; return false;
} }
if (!FinitePositive(building.FuelUseWatts) || !FinitePositive(building.RatedGenerationWatts)) if (building.FuelUseWatts <= 0 || building.RatedGenerationWatts <= 0 ||
double.IsNaN(building.FuelUseWatts) || double.IsNaN(building.RatedGenerationWatts))
{ {
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The generator's fuel consumption or power rating is unavailable.", "The generator's fuel consumption or power rating is unavailable.",
@@ -72,7 +73,8 @@ public sealed class FuelGenerationAdapter : IProductionProcessAdapter
var generation = building.RatedGenerationWatts * proliferationFactor * boostFactor; var generation = building.RatedGenerationWatts * proliferationFactor * boostFactor;
var burnedFuel = building.FuelUseWatts * (fuel.ProductiveFuel ? 1 : proliferationFactor) * var burnedFuel = building.FuelUseWatts * (fuel.ProductiveFuel ? 1 : proliferationFactor) *
boostFactor * 60 / fuel.HeatValueJoules; boostFactor * 60 / fuel.HeatValueJoules;
if (!Finite(generation) || !FinitePositive(burnedFuel)) if (double.IsInfinity(generation) || double.IsInfinity(burnedFuel) || burnedFuel <= 0 ||
double.IsNaN(generation) || double.IsNaN(burnedFuel))
{ {
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The selected fuel produces an invalid generation rate.", buildingItemId: building.ItemId); "The selected fuel produces an invalid generation rate.", buildingItemId: building.ItemId);
+12 -2
View File
@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production; namespace UXAssist.Production;
@@ -56,7 +55,8 @@ public sealed class GasCollectionAdapter : IProductionProcessAdapter
var outputs = new List<KeyValuePair<int, double>>(); var outputs = new List<KeyValuePair<int, double>>();
for (var index = 0; index < (int)gasCount; index++) for (var index = 0; index < (int)gasCount; index++)
{ {
if (!operatingParameters.TryGetValue($"GasItemId{index}", out var itemId) || !PositiveId(itemId) || if (!operatingParameters.TryGetValue($"GasItemId{index}", out var itemId) ||
itemId <= 0 || itemId > int.MaxValue || itemId != Math.Truncate(itemId) ||
!catalog.Items.ContainsKey((int)itemId) || !catalog.Items.ContainsKey((int)itemId) ||
!operatingParameters.TryGetValue($"GasSpeedPerSecond{index}", out var gasSpeed) || !operatingParameters.TryGetValue($"GasSpeedPerSecond{index}", out var gasSpeed) ||
!FiniteNonnegative(gasSpeed)) !FiniteNonnegative(gasSpeed))
@@ -85,4 +85,14 @@ public sealed class GasCollectionAdapter : IProductionProcessAdapter
1, 0, true); 1, 0, true);
return true; return true;
} }
private static bool FiniteNonnegative(double value)
{
return value >= 0 && !double.IsNaN(value) && !double.IsInfinity(value);
}
private static bool FinitePositive(double value)
{
return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
}
} }
+3 -3
View File
@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production; namespace UXAssist.Production;
@@ -75,7 +74,7 @@ public sealed class LaunchProcessAdapter : IProductionProcessAdapter
} }
var nativeStep = Math.Truncate(10000 * (1 + speedBonus) + 0.1) * (boosted ? 10 : 1); var nativeStep = Math.Truncate(10000 * (1 + speedBonus) + 0.1) * (boosted ? 10 : 1);
if (!FinitePositive(nativeStep)) if (nativeStep <= 0 || double.IsInfinity(nativeStep) || double.IsNaN(nativeStep))
{ {
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The launcher's native speed is outside the supported range.", buildingItemId: building.ItemId); "The launcher's native speed is outside the supported range.", buildingItemId: building.ItemId);
@@ -85,7 +84,8 @@ public sealed class LaunchProcessAdapter : IProductionProcessAdapter
var cycleTicks = Math.Ceiling(building.LaunchChargeTicks * 10000.0 / nativeStep) + var cycleTicks = Math.Ceiling(building.LaunchChargeTicks * 10000.0 / nativeStep) +
Math.Ceiling(building.LaunchCooldownTicks * 10000.0 / nativeStep); Math.Ceiling(building.LaunchCooldownTicks * 10000.0 / nativeStep);
var launchesPerMinute = 3600.0 / cycleTicks; var launchesPerMinute = 3600.0 / cycleTicks;
if (!FinitePositive(launchesPerMinute)) if (launchesPerMinute <= 0 || double.IsInfinity(launchesPerMinute) ||
double.IsNaN(launchesPerMinute))
{ {
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The launcher cycle is outside the supported range.", buildingItemId: building.ItemId); "The launcher cycle is outside the supported range.", buildingItemId: building.ItemId);
+13 -3
View File
@@ -1,6 +1,5 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production; namespace UXAssist.Production;
@@ -26,7 +25,7 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
if (operatingParameters == null || if (operatingParameters == null ||
!operatingParameters.TryGetValue("ResourceItemId", out var outputId) || !operatingParameters.TryGetValue("ResourceItemId", out var outputId) ||
!PositiveId(outputId) || !catalog.Items.ContainsKey((int)outputId) || !ValidItemId(outputId) || !catalog.Items.ContainsKey((int)outputId) ||
!operatingParameters.TryGetValue("MiningSpeedMultiplier", out var miningSpeed) || !operatingParameters.TryGetValue("MiningSpeedMultiplier", out var miningSpeed) ||
!FinitePositive(miningSpeed)) !FinitePositive(miningSpeed))
{ {
@@ -73,7 +72,8 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
var powerRatio = machineSpeed * machineSpeed; var powerRatio = machineSpeed * machineSpeed;
var workingWatts = building.WorkingPowerWatts * powerRatio + var workingWatts = building.WorkingPowerWatts * powerRatio +
building.IdlePowerWatts * (1 - powerRatio); building.IdlePowerWatts * (1 - powerRatio);
if (!FinitePositive(perMinute) || !FiniteNonnegative(workingWatts)) if (!FinitePositive(perMinute) || workingWatts < 0 ||
double.IsNaN(workingWatts) || double.IsInfinity(workingWatts))
{ {
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest, diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.InvalidRequest,
"The mineral output rate or power demand is outside the supported range.", "The mineral output rate or power demand is outside the supported range.",
@@ -87,4 +87,14 @@ public sealed class MiningProcessAdapter : IProductionProcessAdapter
perMinute, workingWatts, true); perMinute, workingWatts, true);
return true; return true;
} }
private static bool ValidItemId(double value)
{
return value > 0 && value <= int.MaxValue && value == Math.Truncate(value);
}
private static bool FinitePositive(double value)
{
return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
}
} }
+13 -5
View File
@@ -1,7 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using static UXAssist.Production.ProductionMath;
namespace UXAssist.Production; namespace UXAssist.Production;
@@ -53,9 +52,7 @@ public sealed class ProcessEvaluator
return false; return false;
} }
// Recipe types unknown to the catalog, such as ones added by other mods, keep their material flows only if (!IsOrdinary(recipe.Category))
// while no building is selected.
if (!IsOrdinary(recipe.Category) && (recipe.Category != ProductionRecipeCategory.None || building != null))
{ {
diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess, diagnostic = new ProductionDiagnostic(ProductionDiagnosticCode.UnsupportedProcess,
"The recipe requires a special-process adapter.", recipeId: recipe.Id, "The recipe requires a special-process adapter.", recipeId: recipe.Id,
@@ -117,6 +114,17 @@ public sealed class ProcessEvaluator
private static bool ValidFlows(IReadOnlyDictionary<int, double> flows) private static bool ValidFlows(IReadOnlyDictionary<int, double> flows)
{ {
return flows.All(flow => flow.Key > 0 && FinitePositive(flow.Value)); return flows.All(flow => flow.Key > 0 && flow.Value > 0 && !double.IsNaN(flow.Value) &&
!double.IsInfinity(flow.Value));
}
private static bool FinitePositive(double value)
{
return value > 0 && !double.IsNaN(value) && !double.IsInfinity(value);
}
private static bool FiniteNonnegative(double value)
{
return value >= 0 && !double.IsNaN(value) && !double.IsInfinity(value);
} }
} }
+7 -12
View File
@@ -39,10 +39,8 @@ public static class ProductionCatalogReader
var kind = ClassifyBuilding(prefab); var kind = ClassifyBuilding(prefab);
if (category == ProductionRecipeCategory.None && kind == ProductionBuildingKind.Ordinary) continue; if (category == ProductionRecipeCategory.None && kind == ProductionBuildingKind.Ordinary) continue;
var speed = prefab.isLab ? prefab.labAssembleSpeed : prefab.assemblerSpeed; var speed = prefab.isLab ? prefab.labAssembleSpeed : prefab.assemblerSpeed;
// Charging power nodes draw idle power except while charging a mecha, which production power excludes.
var workEnergyPerTick = prefab.isPowerCharger ? prefab.idleEnergyPerTick : prefab.workEnergyPerTick;
buildings.Add(new ProductionBuilding(item.ID, category, speed / 10000.0, buildings.Add(new ProductionBuilding(item.ID, category, speed / 10000.0,
workEnergyPerTick * 60.0, prefab.idleEnergyPerTick * 60.0, kind, prefab.workEnergyPerTick * 60.0, prefab.idleEnergyPerTick * 60.0, kind,
prefab.genEnergyPerTick * 60.0, prefab.exchangeEnergyPerTick * 60.0, prefab.genEnergyPerTick * 60.0, prefab.exchangeEnergyPerTick * 60.0,
prefab.maxExcEnergy, prefab.emptyId, prefab.fullId, prefab.maxExcEnergy, prefab.emptyId, prefab.fullId,
prefab.windForcedPower ? RenewablePowerSource.Wind : prefab.windForcedPower ? RenewablePowerSource.Wind :
@@ -69,14 +67,10 @@ public static class ProductionCatalogReader
recipe.Results.Length != recipe.ResultCounts.Length) continue; recipe.Results.Length != recipe.ResultCounts.Length) continue;
recipes.Add(new ProductionRecipe(recipe.ID, MapCategory(recipe.Type), recipe.TimeSpend, recipe.productive, recipes.Add(new ProductionRecipe(recipe.ID, MapCategory(recipe.Type), recipe.TimeSpend, recipe.productive,
PairFlows(recipe.Items, recipe.ItemCounts), PairFlows(recipe.Results, recipe.ResultCounts), PairFlows(recipe.Items, recipe.ItemCounts), PairFlows(recipe.Results, recipe.ResultCounts)));
recipe.Explicit));
// Follow native maincraft selection (lowest result index, then recipe order), but skip recipes such as
// Reforming Refine that consume their own product and so cannot start its production chain.
for (var resultIndex = 0; resultIndex < recipe.Results.Length; resultIndex++) for (var resultIndex = 0; resultIndex < recipe.Results.Length; resultIndex++)
{ {
var productId = recipe.Results[resultIndex]; var productId = recipe.Results[resultIndex];
if (Array.IndexOf(recipe.Items, productId) >= 0) continue;
if (!defaultRecipes.TryGetValue(productId, out var old) || resultIndex < old.resultIndex) if (!defaultRecipes.TryGetValue(productId, out var old) || resultIndex < old.resultIndex)
defaultRecipes[productId] = (recipe.ID, resultIndex); defaultRecipes[productId] = (recipe.ID, resultIndex);
} }
@@ -88,8 +82,8 @@ public static class ProductionCatalogReader
foreach (var item in itemProtos) foreach (var item in itemProtos)
{ {
if (item == null) continue; if (item == null) continue;
var defaultRecipeId = defaultRecipes.TryGetValue(item.ID, out var defaultRecipe) var defaultRecipeId = item.maincraft?.ID ??
? defaultRecipe.recipeId : 0; (defaultRecipes.TryGetValue(item.ID, out var fallback) ? fallback.recipeId : 0);
var isProliferator = proliferators.Contains(item.ID); var isProliferator = proliferators.Contains(item.ID);
items.Add(new ProductionItem(item.ID, defaultRecipeId, items.Add(new ProductionItem(item.ID, defaultRecipeId,
naturalItems.Contains(item.ID) || !string.IsNullOrEmpty(item.MiningFrom), naturalItems.Contains(item.ID) || !string.IsNullOrEmpty(item.MiningFrom),
@@ -119,7 +113,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,
@@ -197,7 +192,7 @@ public static class ProductionCatalogReader
? ProductionBuildingKind.RenewableGenerator : ProductionBuildingKind.FuelGenerator; ? ProductionBuildingKind.RenewableGenerator : ProductionBuildingKind.FuelGenerator;
if (prefab.isStation || prefab.isDispenser || prefab.isBattleBase) if (prefab.isStation || prefab.isDispenser || prefab.isBattleBase)
return ProductionBuildingKind.Logistics; return ProductionBuildingKind.Logistics;
if (prefab.isPowerConsumer || prefab.isPowerCharger) if (prefab.isPowerConsumer && !prefab.isStation && !prefab.isDispenser)
return ProductionBuildingKind.Auxiliary; return ProductionBuildingKind.Auxiliary;
return ProductionBuildingKind.Ordinary; return ProductionBuildingKind.Ordinary;
} }
+2 -41
View File
@@ -27,40 +27,6 @@ internal static class ProductionUnits
internal const double FixedPointScale = 10000; internal const double FixedPointScale = 10000;
} }
internal static class ProductionMath
{
internal static bool Finite(double value) => !double.IsNaN(value) && !double.IsInfinity(value);
internal static bool FinitePositive(double value) => value > 0 && Finite(value);
internal static bool FiniteNonnegative(double value) => value >= 0 && Finite(value);
// Item and technology IDs arrive as double operating parameters.
internal static bool PositiveId(double value) =>
value > 0 && value <= int.MaxValue && value == Math.Truncate(value);
internal static void AddFlow(IDictionary<int, double> flows, int itemId, double amount)
{
flows[itemId] = (flows.TryGetValue(itemId, out var previous) ? previous : 0) + amount;
}
internal static Dictionary<int, double> ScaleFlows(IReadOnlyDictionary<int, double> flows, double factor)
{
return flows.ToDictionary(flow => flow.Key, flow => flow.Value * factor);
}
internal static void AddGroup(IDictionary<int, List<int>> groups, int itemId, int groupIndex)
{
if (!groups.TryGetValue(itemId, out var indices))
{
indices = new List<int>();
groups[itemId] = indices;
}
indices.Add(groupIndex);
}
}
public enum ProliferationMode public enum ProliferationMode
{ {
None, None,
@@ -116,8 +82,7 @@ public enum ProductionDiagnosticCode
Unbounded, Unbounded,
IterationLimit, IterationLimit,
Cancelled, Cancelled,
ConservationFailure, ConservationFailure
BlueprintBasisUnavailable
} }
public sealed class ProductionDiagnostic public sealed class ProductionDiagnostic
@@ -181,20 +146,16 @@ public sealed class ProductionRecipe
public ProductionRecipeCategory Category { get; } public ProductionRecipeCategory Category { get; }
public int TimeTicks { get; } public int TimeTicks { get; }
public bool Productive { get; } public bool Productive { get; }
// Native RecipeProto.Explicit, set for named recipes such as the rare-resource alternatives.
public bool Explicit { get; }
public IReadOnlyDictionary<int, double> Inputs { get; } public IReadOnlyDictionary<int, double> Inputs { get; }
public IReadOnlyDictionary<int, double> Outputs { get; } public IReadOnlyDictionary<int, double> Outputs { get; }
public ProductionRecipe(int id, ProductionRecipeCategory category, int timeTicks, bool productive, public ProductionRecipe(int id, ProductionRecipeCategory category, int timeTicks, bool productive,
IEnumerable<KeyValuePair<int, double>> inputs, IEnumerable<KeyValuePair<int, double>> outputs, IEnumerable<KeyValuePair<int, double>> inputs, IEnumerable<KeyValuePair<int, double>> outputs)
bool explicitRecipe = false)
{ {
Id = id; Id = id;
Category = category; Category = category;
TimeTicks = timeTicks; TimeTicks = timeTicks;
Productive = productive; Productive = productive;
Explicit = explicitRecipe;
Inputs = CopyFlows(inputs); Inputs = CopyFlows(inputs);
Outputs = CopyFlows(outputs); Outputs = CopyFlows(outputs);
} }
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff. Show more