using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json.Linq;
using Sandbox;
using Sandbox.Engine.Physics;
using Sandbox.Engine.Utils;
using Sandbox.Game.World;
using VRage;
using VRageRender.ExternalApp;
using XFE.SeAgent.Plugin.Performance;
namespace XFE.SeAgent.Plugin.Game
{
public sealed partial class GameDebugApi
{
private PerformanceTuning performanceTuning;
private EngineStages measuredStages;
private readonly FrameSeries renderFrames = new FrameSeries(), updateFrames = new FrameSeries();
private readonly List<JObject> performanceSamples = new List<JObject>();
private MyRenderThread measuredRenderThread;
private volatile bool performanceCapturing;
private bool originalSimpleProfiler;
private double performanceStarted, performanceUntil, nextPerformanceSample;
private string performanceLabel;
private double performanceCpuStart;
private JObject performanceReport;
private static readonly FieldInfo ProfilingBlocks = typeof(MySimpleProfiler).GetField("m_profilingBlocks", BindingFlags.Static | BindingFlags.NonPublic);
private static readonly FieldInfo ProfilingAverage = typeof(MySimpleProfiler.MySimpleProfilingBlock).GetField("m_avgTickTime", BindingFlags.Instance | BindingFlags.NonPublic);
private static double ClockMs => Stopwatch.GetTimestamp() * (1000.0 / Stopwatch.Frequency);
private JObject PerformanceStatus()
{
var session = MySession.Static;
var result = new JObject { ["capturing"] = performanceCapturing, ["label"] = performanceLabel,
["remainingSeconds"] = performanceCapturing ? Math.Max(0, performanceUntil - ClockMs) / 1000 : 0,
["gameFps"] = MyFpsManager.GetFps(), ["gameFrameTimeMs"] = MyFpsManager.FrameTimeAvg,
["simulationRatio"] = session == null ? null : (JToken)MyPhysics.SimulationRatio, ["paused"] = MySandboxGame.IsPaused,
["logicalProcessors"] = Environment.ProcessorCount, ["simpleProfiler"] = MySimpleProfiler.ENABLE_SIMPLE_PROFILER };
result["parallelScheduler"] = ParallelTasks.Parallel.Scheduler.GetType().FullName;
result["parallelWorkersPerPool"] = ParallelTasks.Parallel.Scheduler.ThreadCount;
result["renderWorkerLimit"] = VRageRender.MyRenderProxy.Settings.RenderThreadCount;
result["gc"] = new JObject { ["server"] = System.Runtime.GCSettings.IsServerGC,
["latencyMode"] = System.Runtime.GCSettings.LatencyMode.ToString(),
["managedBytes"] = GC.GetTotalMemory(false),
["gen0"] = GC.CollectionCount(0), ["gen1"] = GC.CollectionCount(1), ["gen2"] = GC.CollectionCount(2) };
if (session != null)
{
result["worldPath"] = session.CurrentPath;
result["controlledEntityId"] = session.ControlledEntity?.Entity == null ? null : Sid(session.ControlledEntity.Entity.EntityId);
result["cameraController"] = session.CameraController?.GetType().FullName;
}
var pool = typeof(MyPhysics).GetField("m_threadPool", BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null);
if (pool != null) result["havokWorkers"] = JToken.FromObject(pool.GetType().GetProperty("ThreadCount").GetValue(pool));
result["profile"] = ProfileSnapshot();
result["tuning"] = performanceTuning?.Status();
result["graphics"] = GraphicsDiagnostics.Snapshot();
result["drawEnabled"] = MySandboxGame.Static?.GameRenderComponent?.RenderThread?.RenderWindow?.DrawEnabled;
result["screens"] = new JArray(Sandbox.Graphics.GUI.MyScreenManager.Screens.Select(screen => screen.GetType().FullName));
return result;
}
private static JArray ProfileSnapshot()
{
var blocks = ProfilingBlocks?.GetValue(null) as Dictionary<string, MySimpleProfiler.MySimpleProfilingBlock>;
if (blocks == null || ProfilingAverage == null) return new JArray();
// The engine publishes immutable dictionary instances; never call Commit,
// which would consume/reset the game's own counters.
return new JArray(blocks.Values.Select(b => new { b.Name, Kind = b.Type.ToString(), Ms = (float)ProfilingAverage.GetValue(b) / 1000.0 })
.OrderByDescending(b => b.Ms).Take(48).Select(b => new JObject { ["name"] = b.Name, ["kind"] = b.Kind, ["averageMs"] = b.Ms }));
}
private JObject StartPerformanceCapture(JObject args)
{
if (performanceCapturing) throw new InvalidOperationException("A performance capture is already running.");
double seconds = (double?)args["seconds"] ?? 60;
if (seconds < 5 || seconds > 180 || double.IsNaN(seconds)) throw new ArgumentException("seconds must be 5..180.");
string label = (string)args["label"] ?? "capture";
if (label.Length > 128) throw new ArgumentException("label exceeds 128 characters.");
measuredRenderThread = MySandboxGame.Static?.GameRenderComponent?.RenderThread;
if (measuredRenderThread == null) throw new InvalidOperationException("No render thread is available.");
if (args["engineStages"] != null && args["engineStages"].Type != JTokenType.Boolean) throw new ArgumentException("engineStages must be boolean.");
if ((bool?)args["engineStages"] == true) measuredStages = new EngineStages();
renderFrames.Reset(); updateFrames.Reset(); performanceSamples.Clear(); performanceReport = null;
performanceLabel = label; performanceStarted = nextPerformanceSample = ClockMs; performanceUntil = performanceStarted + seconds * 1000;
measuredStages?.StartClock();
using (var process = Process.GetCurrentProcess()) performanceCpuStart = process.TotalProcessorTime.TotalSeconds;
originalSimpleProfiler = MySimpleProfiler.ENABLE_SIMPLE_PROFILER; MySimpleProfiler.ENABLE_SIMPLE_PROFILER = true;
performanceCapturing = true; measuredRenderThread.BeforeDraw += MarkRenderedFrame;
return new JObject { ["started"] = true, ["label"] = label, ["seconds"] = seconds, ["pollMethod"] = "performance.report" };
}
private void MarkRenderedFrame() { if (performanceCapturing) renderFrames.Mark(ClockMs); }
private void UpdatePerformanceCapture()
{
performanceTuning?.UpdateRenderLimit();
if (!performanceCapturing) return;
double now = ClockMs; updateFrames.Mark(now);
if (now >= nextPerformanceSample)
{
nextPerformanceSample = now + 500;
var row = PerformanceStatus(); row["utc"] = DateTime.UtcNow.ToString("o");
row["elapsedMs"] = now - performanceStarted;
performanceSamples.Add(row);
}
if (now >= performanceUntil) FinishPerformanceCapture();
}
private void FinishPerformanceCapture()
{
if (!performanceCapturing) return;
performanceCapturing = false;
measuredRenderThread.BeforeDraw -= MarkRenderedFrame; measuredRenderThread = null;
MySimpleProfiler.ENABLE_SIMPLE_PROFILER = originalSimpleProfiler;
double elapsed = (ClockMs - performanceStarted) / 1000, cpu;
using (var process = Process.GetCurrentProcess()) cpu = process.TotalProcessorTime.TotalSeconds - performanceCpuStart;
performanceReport = new JObject { ["label"] = performanceLabel, ["completedUtc"] = DateTime.UtcNow.ToString("o"),
["elapsedSeconds"] = elapsed, ["processCpuSeconds"] = cpu, ["averageBusyCores"] = cpu / elapsed,
["renderIntervals"] = JObject.FromObject(renderFrames.Summarize()), ["updateIntervals"] = JObject.FromObject(updateFrames.Summarize()),
["samples"] = new JArray(performanceSamples),
["measurement"] = "Render BeforeDraw wall-clock intervals and plugin Update intervals; simulation ratio and native profiler averages reported separately. Not a GPU-present trace." };
if (measuredStages != null)
{
performanceReport["engineStages"] = measuredStages.Report();
measuredStages.Dispose(); measuredStages = null;
}
}
private JObject GetPerformanceReport() => performanceCapturing ? PerformanceStatus() : performanceReport ?? new JObject { ["capturing"] = false, ["report"] = null };
private JObject ClosePauseMenu()
{
// A world loaded through the engine can leave the main-menu overlay open.
// Close only that known menu; never confirm dialogs or other screens.
int closed = 0;
foreach (var screen in Sandbox.Graphics.GUI.MyScreenManager.Screens.ToArray())
if (screen.GetType().Name == "MyGuiScreenMainMenu") { screen.CloseScreenNow(); closed++; }
return new JObject { ["closed"] = closed };
}
private JObject DismissInfo(JObject args)
{
string expected=(string)args["text"];
if(string.IsNullOrWhiteSpace(expected) || expected.Length>2048) throw new ArgumentException("An exact information message text is required.");
int closed=0;
foreach(var screen in Sandbox.Graphics.GUI.MyScreenManager.Screens.ToArray())
{
var message=screen as Sandbox.Graphics.GUI.MyGuiScreenMessageBox;
if(message==null || message.MessageText?.ToString()!=expected) continue;
var buttons=HarmonyLib.AccessTools.Field(message.GetType(),"m_buttonType")?.GetValue(message);
if(buttons?.ToString()!="OK") continue;
// Close an already observed information overlay. Never invoke a
// confirmation callback, select Yes/No, or change game settings.
screen.CloseScreenNow(); closed++;
}
return new JObject { ["closed"]=closed };
}
}
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json.Linq;
using Sandbox;
using Sandbox.Engine.Physics;
using Sandbox.Engine.Utils;
using Sandbox.Game.World;
using VRage;
using VRageRender.ExternalApp;
using XFE.SeAgent.Plugin.Performance;
namespace XFE.SeAgent.Plugin.Game
{
public sealed partial class GameDebugApi
{
private PerformanceTuning performanceTuning;
private EngineStages measuredStages;
private readonly FrameSeries renderFrames = new FrameSeries(), updateFrames = new FrameSeries();
private readonly List<JObject> performanceSamples = new List<JObject>();
private MyRenderThread measuredRenderThread;
private volatile bool performanceCapturing;
private bool originalSimpleProfiler;
private double performanceStarted, performanceUntil, nextPerformanceSample;
private string performanceLabel;
private double performanceCpuStart;
private JObject performanceReport;
private static readonly FieldInfo ProfilingBlocks = typeof(MySimpleProfiler).GetField("m_profilingBlocks", BindingFlags.Static | BindingFlags.NonPublic);
private static readonly FieldInfo ProfilingAverage = typeof(MySimpleProfiler.MySimpleProfilingBlock).GetField("m_avgTickTime", BindingFlags.Instance | BindingFlags.NonPublic);
private static double ClockMs => Stopwatch.GetTimestamp() * (1000.0 / Stopwatch.Frequency);
private JObject PerformanceStatus()
{
var session = MySession.Static;
var result = new JObject { ["capturing"] = performanceCapturing, ["label"] = performanceLabel,
["remainingSeconds"] = performanceCapturing ? Math.Max(0, performanceUntil - ClockMs) / 1000 : 0,
["gameFps"] = MyFpsManager.GetFps(), ["gameFrameTimeMs"] = MyFpsManager.FrameTimeAvg,
["simulationRatio"] = session == null ? null : (JToken)MyPhysics.SimulationRatio, ["paused"] = MySandboxGame.IsPaused,
["logicalProcessors"] = Environment.ProcessorCount, ["simpleProfiler"] = MySimpleProfiler.ENABLE_SIMPLE_PROFILER };
result["parallelScheduler"] = ParallelTasks.Parallel.Scheduler.GetType().FullName;
result["parallelWorkersPerPool"] = ParallelTasks.Parallel.Scheduler.ThreadCount;
result["renderWorkerLimit"] = VRageRender.MyRenderProxy.Settings.RenderThreadCount;
result["gc"] = new JObject { ["server"] = System.Runtime.GCSettings.IsServerGC,
["latencyMode"] = System.Runtime.GCSettings.LatencyMode.ToString(),
["managedBytes"] = GC.GetTotalMemory(false),
["gen0"] = GC.CollectionCount(0), ["gen1"] = GC.CollectionCount(1), ["gen2"] = GC.CollectionCount(2) };
if (session != null)
{
result["worldPath"] = session.CurrentPath;
result["controlledEntityId"] = session.ControlledEntity?.Entity == null ? null : Sid(session.ControlledEntity.Entity.EntityId);
result["cameraController"] = session.CameraController?.GetType().FullName;
}
var pool = typeof(MyPhysics).GetField("m_threadPool", BindingFlags.NonPublic | BindingFlags.Static)?.GetValue(null);
if (pool != null) result["havokWorkers"] = JToken.FromObject(pool.GetType().GetProperty("ThreadCount").GetValue(pool));
result["profile"] = ProfileSnapshot();
result["tuning"] = performanceTuning?.Status();
result["graphics"] = GraphicsDiagnostics.Snapshot();
result["drawEnabled"] = MySandboxGame.Static?.GameRenderComponent?.RenderThread?.RenderWindow?.DrawEnabled;
result["screens"] = new JArray(Sandbox.Graphics.GUI.MyScreenManager.Screens.Select(screen => screen.GetType().FullName));
return result;
}
private static JArray ProfileSnapshot()
{
var blocks = ProfilingBlocks?.GetValue(null) as Dictionary<string, MySimpleProfiler.MySimpleProfilingBlock>;
if (blocks == null || ProfilingAverage == null) return new JArray();
// The engine publishes immutable dictionary instances; never call Commit,
// which would consume/reset the game's own counters.
return new JArray(blocks.Values.Select(b => new { b.Name, Kind = b.Type.ToString(), Ms = (float)ProfilingAverage.GetValue(b) / 1000.0 })
.OrderByDescending(b => b.Ms).Take(48).Select(b => new JObject { ["name"] = b.Name, ["kind"] = b.Kind, ["averageMs"] = b.Ms }));
}
private JObject StartPerformanceCapture(JObject args)
{
if (performanceCapturing) throw new InvalidOperationException("A performance capture is already running.");
double seconds = (double?)args["seconds"] ?? 60;
if (seconds < 5 || seconds > 180 || double.IsNaN(seconds)) throw new ArgumentException("seconds must be 5..180.");
string label = (string)args["label"] ?? "capture";
if (label.Length > 128) throw new ArgumentException("label exceeds 128 characters.");
measuredRenderThread = MySandboxGame.Static?.GameRenderComponent?.RenderThread;
if (measuredRenderThread == null) throw new InvalidOperationException("No render thread is available.");
if (args["engineStages"] != null && args["engineStages"].Type != JTokenType.Boolean) throw new ArgumentException("engineStages must be boolean.");
if ((bool?)args["engineStages"] == true) measuredStages = new EngineStages();
renderFrames.Reset(); updateFrames.Reset(); performanceSamples.Clear(); performanceReport = null;
performanceLabel = label; performanceStarted = nextPerformanceSample = ClockMs; performanceUntil = performanceStarted + seconds * 1000;
measuredStages?.StartClock();
using (var process = Process.GetCurrentProcess()) performanceCpuStart = process.TotalProcessorTime.TotalSeconds;
originalSimpleProfiler = MySimpleProfiler.ENABLE_SIMPLE_PROFILER; MySimpleProfiler.ENABLE_SIMPLE_PROFILER = true;
performanceCapturing = true; measuredRenderThread.BeforeDraw += MarkRenderedFrame;
return new JObject { ["started"] = true, ["label"] = label, ["seconds"] = seconds, ["pollMethod"] = "performance.report" };
}
private void MarkRenderedFrame() { if (performanceCapturing) renderFrames.Mark(ClockMs); }
private void UpdatePerformanceCapture()
{
performanceTuning?.UpdateRenderLimit();
if (!performanceCapturing) return;
double now = ClockMs; updateFrames.Mark(now);
if (now >= nextPerformanceSample)
{
nextPerformanceSample = now + 500;
var row = PerformanceStatus(); row["utc"] = DateTime.UtcNow.ToString("o");
row["elapsedMs"] = now - performanceStarted;
performanceSamples.Add(row);
}
if (now >= performanceUntil) FinishPerformanceCapture();
}
private void FinishPerformanceCapture()
{
if (!performanceCapturing) return;
performanceCapturing = false;
measuredRenderThread.BeforeDraw -= MarkRenderedFrame; measuredRenderThread = null;
MySimpleProfiler.ENABLE_SIMPLE_PROFILER = originalSimpleProfiler;
double elapsed = (ClockMs - performanceStarted) / 1000, cpu;
using (var process = Process.GetCurrentProcess()) cpu = process.TotalProcessorTime.TotalSeconds - performanceCpuStart;
performanceReport = new JObject { ["label"] = performanceLabel, ["completedUtc"] = DateTime.UtcNow.ToString("o"),
["elapsedSeconds"] = elapsed, ["processCpuSeconds"] = cpu, ["averageBusyCores"] = cpu / elapsed,
["renderIntervals"] = JObject.FromObject(renderFrames.Summarize()), ["updateIntervals"] = JObject.FromObject(updateFrames.Summarize()),
["samples"] = new JArray(performanceSamples),
["measurement"] = "Render BeforeDraw wall-clock intervals and plugin Update intervals; simulation ratio and native profiler averages reported separately. Not a GPU-present trace." };
if (measuredStages != null)
{
performanceReport["engineStages"] = measuredStages.Report();
measuredStages.Dispose(); measuredStages = null;
}
}
private JObject GetPerformanceReport() => performanceCapturing ? PerformanceStatus() : performanceReport ?? new JObject { ["capturing"] = false, ["report"] = null };
private JObject ClosePauseMenu()
{
// A world loaded through the engine can leave the main-menu overlay open.
// Close only that known menu; never confirm dialogs or other screens.
int closed = 0;
foreach (var screen in Sandbox.Graphics.GUI.MyScreenManager.Screens.ToArray())
if (screen.GetType().Name == "MyGuiScreenMainMenu") { screen.CloseScreenNow(); closed++; }
return new JObject { ["closed"] = closed };
}
private JObject DismissInfo(JObject args)
{
string expected=(string)args["text"];
if(string.IsNullOrWhiteSpace(expected) || expected.Length>2048) throw new ArgumentException("An exact information message text is required.");
int closed=0;
foreach(var screen in Sandbox.Graphics.GUI.MyScreenManager.Screens.ToArray())
{
var message=screen as Sandbox.Graphics.GUI.MyGuiScreenMessageBox;
if(message==null || message.MessageText?.ToString()!=expected) continue;
var buttons=HarmonyLib.AccessTools.Field(message.GetType(),"m_buttonType")?.GetValue(message);
if(buttons?.ToString()!="OK") continue;
// Close an already observed information overlay. Never invoke a
// confirmation callback, select Yes/No, or change game settings.
screen.CloseScreenNow(); closed++;
}
return new JObject { ["closed"]=closed };
}
}
}