mirror of
https://github.com/soarqin/DSP_Mods.git
synced 2026-11-19 17:05:20 +08:00
fix(livestreamassist): refresh theoretical item rates
Queue the native production extra-info calculator on factory reads so production and consumption reference speeds update without the stats UI. Deduplicate and throttle refreshes, let active batches finish, and clear pending work at session boundaries. Add refresh scheduling regressions and document the initial cache warm-up.
This commit is contained in:
1 parent
f03d6c758e
commit
63a6a6ec6c
7 files changed
+155
-2
No files matched your search
@@ -35,6 +35,7 @@
|
||||
- `PatchImpl<T>.Enable(true)` must remain fail-soft: log, unpatch, and leave the patch unset if Harmony application fails so config delegate chains remain consistent.
|
||||
- Overlay UI state must converge from actual game state on periodic updates, not depend only on one-shot event or patch callbacks. Cloned controls must reset runtime state while retaining source styles; use `UXAssist.UI.Util.GetPreferredWidth` for dynamic text and `ResetButton` for cloned buttons.
|
||||
- LiveStreamAssist browser overlays must use single-flight polling and discard stale work after connection changes. Compound queries must reject mixed session IDs; cache only positive production indices so newly tracked items remain discoverable.
|
||||
- LiveStreamAssist production reads must schedule the native extra-info calculator for queried factories independently of the statistics UI. Deduplicate and throttle refreshes, let active native batches finish, and clear pending factory indices and deadlines at session boundaries.
|
||||
|
||||
## Automation Architecture
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace LiveStreamAssist.Api;
|
||||
|
||||
internal sealed class ProductionExtraInfoRefresh
|
||||
{
|
||||
const int RefreshIntervalMs = 2000;
|
||||
readonly Dictionary<int, long> _nextRefreshMs = new Dictionary<int, long>();
|
||||
readonly HashSet<int> _pendingFactories = new HashSet<int>();
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
_nextRefreshMs.Clear();
|
||||
_pendingFactories.Clear();
|
||||
}
|
||||
|
||||
public void OnRead(DataCall call, int factoryCount, bool calculating, long nowMs, Action<int> addFactory)
|
||||
{
|
||||
var factoryIndex = GetFactoryIndex(call);
|
||||
if (factoryIndex < 0 || factoryIndex >= factoryCount) return;
|
||||
|
||||
if (!_nextRefreshMs.TryGetValue(factoryIndex, out var next) || nowMs >= next)
|
||||
_pendingFactories.Add(factoryIndex);
|
||||
|
||||
// Let the native batch finish before requeuing factories it has already processed.
|
||||
if (calculating) return;
|
||||
foreach (var index in _pendingFactories)
|
||||
{
|
||||
if (index >= factoryCount) continue;
|
||||
addFactory(index);
|
||||
_nextRefreshMs[index] = nowMs + RefreshIntervalMs;
|
||||
}
|
||||
_pendingFactories.Clear();
|
||||
}
|
||||
|
||||
static int GetFactoryIndex(DataCall call)
|
||||
{
|
||||
if (call.Method != DataMethod.Read || call.Path == null) return -1;
|
||||
var path = call.Path;
|
||||
var offset = 0;
|
||||
if (call.Root == "game")
|
||||
{
|
||||
if (path.Length == 0 || path[0].Kind != PathKind.Member || path[0].Name != "statistics")
|
||||
return -1;
|
||||
offset = 1;
|
||||
}
|
||||
else if (call.Root != "statistics")
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (path.Length < offset + 3 ||
|
||||
path[offset].Kind != PathKind.Member || path[offset].Name != "production" ||
|
||||
path[offset + 1].Kind != PathKind.Member || path[offset + 1].Name != "factoryStatPool" ||
|
||||
path[offset + 2].Kind != PathKind.Index)
|
||||
return -1;
|
||||
return path[offset + 2].Index;
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@ internal static class WebSocketApiFeature
|
||||
};
|
||||
|
||||
static readonly object Gate = new object();
|
||||
static readonly ProductionExtraInfoRefresh ProductionRefresh = new ProductionExtraInfoRefresh();
|
||||
static object _ownerToken;
|
||||
static WebSocketApiServer _server;
|
||||
static MainThreadDispatcher _dispatcher;
|
||||
@@ -48,6 +49,7 @@ internal static class WebSocketApiFeature
|
||||
public static void Init()
|
||||
{
|
||||
_reader = new ReflectionReader();
|
||||
ProductionRefresh.Reset();
|
||||
ReflectionReader.Warn = msg => LiveStreamAssist.Logger.LogWarning(msg);
|
||||
_version = GameVersionSnapshot.Empty;
|
||||
_session = new SessionSnapshot(0, null);
|
||||
@@ -144,6 +146,7 @@ internal static class WebSocketApiFeature
|
||||
try { server?.Stop(); }
|
||||
catch (Exception ex) { LiveStreamAssist.Logger.LogWarning($"WebSocket API server stop failed: {ex.Message}"); }
|
||||
_reader?.ClearCache();
|
||||
ProductionRefresh.Reset();
|
||||
ReflectionReader.Warn = null;
|
||||
}
|
||||
|
||||
@@ -182,6 +185,7 @@ internal static class WebSocketApiFeature
|
||||
|
||||
static void BeginSession()
|
||||
{
|
||||
ProductionRefresh.Reset();
|
||||
MainThreadDispatcher dispatcher;
|
||||
int oldGeneration;
|
||||
lock (Gate)
|
||||
@@ -196,6 +200,7 @@ internal static class WebSocketApiFeature
|
||||
|
||||
static void EndSession()
|
||||
{
|
||||
ProductionRefresh.Reset();
|
||||
MainThreadDispatcher dispatcher;
|
||||
lock (Gate)
|
||||
{
|
||||
@@ -262,6 +267,17 @@ internal static class WebSocketApiFeature
|
||||
return walked.Error;
|
||||
if (_session.Generation != work.Generation)
|
||||
return ApiErrors.SessionChanged();
|
||||
if (call.Method == DataMethod.Read)
|
||||
{
|
||||
var production = GameMain.statistics?.production;
|
||||
var calculator = production?.extraInfoCalculator;
|
||||
if (calculator != null)
|
||||
{
|
||||
// Native GameTickCharts refreshes derived statistics without opening the statistics UI.
|
||||
ProductionRefresh.OnRead(call, GameMain.data.factoryCount, calculator.calculating,
|
||||
_server.NowMs, calculator.AddFactory);
|
||||
}
|
||||
}
|
||||
var tick = GameMain.gameTick.ToString(CultureInfo.InvariantCulture);
|
||||
if (call.Method == DataMethod.Describe)
|
||||
return BuildDescribe(walked, session.SessionId, tick);
|
||||
|
||||
@@ -291,6 +291,8 @@ Use `data.describe` to discover the permitted surface. If inheritance hides a na
|
||||
|
||||
Reflected values use DSP's native units and member names. The API does not localize member names, convert values to UI display units, or calculate aggregate gameplay statistics.
|
||||
|
||||
Successful reads beneath `statistics.production.factoryStatPool[index]` (also reachable through `game.statistics`) request a refresh of that factory's native production extra info. The game calculates these derived caches in its normal chart ticks; no statistics window needs to be open. Requests are deduplicated and throttled to once per factory every two seconds, and work requested during an active batch is queued on a later production read after the batch finishes. Reads still return the current cached values: `refProductSpeed` and `refConsumeSpeed` can initially be zero or remain stale until that factory is processed. Descriptions do not request a refresh.
|
||||
|
||||
### `data.describe`
|
||||
|
||||
Parameters: `root` and optional `path` only.
|
||||
|
||||
@@ -80,7 +80,7 @@ Compound queries reject with `SESSION_CHANGED` instead of combining reads from d
|
||||
|
||||
- `window`: `1min` (default), `10min`, `1hour`, `10hour`, `100hour`, `total`. The default 1-minute window matches the statistics panel's shortest rate view: `ProductStat.total[1]` production and `total[8]` consumption, already items/min.
|
||||
- `scope`: omitted/`'cluster'` sums every factory; `'localPlanet'` uses `localPlanet.factoryIndex`; `{ factoryIndex }` reads one factory.
|
||||
- Result fields: `production`, `consumption`, `theoreticalProduction`, `theoreticalConsumption`. Theoretical values are `refProductSpeed` / `refConsumeSpeed`, which the game stores in items/min after the production extra-info calculator runs. They stay 0 until the statistics window refreshes that extra info (LiveStreamAssist's Ctrl+F8 assist helps keep that window open).
|
||||
- Result fields: `production`, `consumption`, `theoreticalProduction`, `theoreticalConsumption`. Theoretical values are the game's `refProductSpeed` / `refConsumeSpeed` in items/min. The server queues queried factories for the native production extra-info calculator without requiring the statistics window or Ctrl+F8 assist. Refresh requests are deduplicated and limited to once per factory every two seconds; an active calculation batch finishes before more factories are queued. Initial polls can return zero, and later polls can return the previous values until the native batch reaches that factory.
|
||||
|
||||
Pass an array of positive integer item ids to share the factory scan; duplicates do not multiply totals. Only existing product indices are cached, so newly produced items become visible on later polls. An unbuilt local planet returns zero rates; an unavailable local planet during space travel still raises `ROOT_UNAVAILABLE`.
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace WebSocketTransportCheck;
|
||||
|
||||
static class ProductionChecks
|
||||
static partial class ProductionChecks
|
||||
{
|
||||
static int _failed;
|
||||
[ThreadStatic] static bool _producing;
|
||||
@@ -25,6 +25,7 @@ static class ProductionChecks
|
||||
await QueueOverflowReleasesAdmission();
|
||||
await StopBeforeStart();
|
||||
NullParameters();
|
||||
ProductionStatisticsRefresh();
|
||||
await ActiveSendRetainsAdmission();
|
||||
await SendDeadlineIncludesQueueTime();
|
||||
await ExecutingWorkTimesOut();
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
using System.Collections.Generic;
|
||||
using LiveStreamAssist.Api;
|
||||
|
||||
namespace WebSocketTransportCheck;
|
||||
|
||||
static partial class ProductionChecks
|
||||
{
|
||||
static DataCall FactoryRead(int index, string member = "productIndices") => new DataCall
|
||||
{
|
||||
Method = DataMethod.Read,
|
||||
Root = "statistics",
|
||||
Path = new[] { new PathSeg("production"), new PathSeg("factoryStatPool"), new PathSeg(index), new PathSeg(member) }
|
||||
};
|
||||
|
||||
static void ProductionStatisticsRefresh()
|
||||
{
|
||||
var refresh = new ProductionExtraInfoRefresh();
|
||||
var queued = new List<int>();
|
||||
var indices = FactoryRead(0);
|
||||
refresh.OnRead(indices, 3, false, 0, queued.Add);
|
||||
Check(queued.Count == 1 && queued[0] == 0,
|
||||
"product-index reads request native extra info even before an item has production history");
|
||||
|
||||
refresh.OnRead(FactoryRead(0, "productPool"), 3, false, 0, queued.Add);
|
||||
refresh.OnRead(indices, 3, false, 1999, queued.Add);
|
||||
Check(queued.Count == 1, "repeated item reads share the per-factory refresh interval");
|
||||
refresh.OnRead(FactoryRead(1), 3, false, 1999, queued.Add);
|
||||
Check(queued.Count == 2 && queued[1] == 1, "new factory queries do not wait for another factory's refresh interval");
|
||||
|
||||
queued.Clear();
|
||||
refresh.OnRead(indices, 3, true, 2000, queued.Add);
|
||||
refresh.OnRead(FactoryRead(2), 3, true, 2500, queued.Add);
|
||||
refresh.OnRead(FactoryRead(2), 3, true, 2501, queued.Add);
|
||||
Check(queued.Count == 0, "reads do not extend an active native calculation batch");
|
||||
refresh.OnRead(FactoryRead(1), 3, false, 3000, queued.Add);
|
||||
Check(queued.Count == 2 && new HashSet<int>(queued).SetEquals(new[] { 0, 2 }),
|
||||
"the next idle read flushes deferred factories once, including when its own cache is fresh");
|
||||
|
||||
refresh.OnRead(FactoryRead(2), 3, true, 5000, queued.Add);
|
||||
refresh.Reset();
|
||||
queued.Clear();
|
||||
refresh.OnRead(indices, 3, false, 0, queued.Add);
|
||||
Check(queued.Count == 1 && queued[0] == 0, "a new session clears pending work and refresh deadlines");
|
||||
|
||||
refresh.Reset();
|
||||
queued.Clear();
|
||||
var gameRead = FactoryRead(2, "productPool");
|
||||
gameRead.Root = "game";
|
||||
var gamePath = new List<PathSeg> { new PathSeg("statistics") };
|
||||
gamePath.AddRange(gameRead.Path);
|
||||
gameRead.Path = gamePath.ToArray();
|
||||
refresh.OnRead(gameRead, 3, false, 0, queued.Add);
|
||||
Check(queued.Count == 1 && queued[0] == 2, "the game.statistics alias refreshes the same native factory data");
|
||||
|
||||
refresh.Reset();
|
||||
queued.Clear();
|
||||
var describe = FactoryRead(0);
|
||||
describe.Method = DataMethod.Describe;
|
||||
refresh.OnRead(describe, 3, false, 0, queued.Add);
|
||||
refresh.OnRead(FactoryRead(-1), 3, false, 0, queued.Add);
|
||||
refresh.OnRead(FactoryRead(3), 3, false, 0, queued.Add);
|
||||
refresh.OnRead(indices, 0, false, 0, queued.Add);
|
||||
foreach (var unrelated in new[]
|
||||
{
|
||||
new DataCall { Method = DataMethod.Read, Root = "statistics", Path = new[] { new PathSeg("production") } },
|
||||
new DataCall { Method = DataMethod.Read, Root = "statistics", Path = new[] { new PathSeg("production"), new PathSeg("factoryStatPool") } },
|
||||
new DataCall { Method = DataMethod.Read, Root = "history", Path = indices.Path },
|
||||
new DataCall { Method = DataMethod.Read, Root = "game", Path = indices.Path }
|
||||
})
|
||||
refresh.OnRead(unrelated, 3, false, 0, queued.Add);
|
||||
Check(queued.Count == 0, "metadata, unrelated reads, and invalid factory indices do not request calculations");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user