diff --git a/Assets/Script/PerformanceStressRunner.cs b/Assets/Script/PerformanceStressRunner.cs new file mode 100644 index 0000000..f6b1b09 --- /dev/null +++ b/Assets/Script/PerformanceStressRunner.cs @@ -0,0 +1,135 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; +using ZoneUA.Performance; + +public sealed class PerformanceStressRunner : MonoBehaviour +{ + [SerializeField] private StressScenarioDefinition scenario; + [SerializeField] private RuntimePerformanceMonitor monitor; + [SerializeField] private MapGenerator mapGenerator; + [SerializeField] private GameObject npcPrefab; + [SerializeField] private GameObject projectilePrefab; + [SerializeField, Tooltip("Optional lightweight prefab used to reach the requested generated-object load.")] + private GameObject generatedLoadPrefab; + [SerializeField] private Transform spawnRoot; + [SerializeField, Min(0.1f)] private float spawnRadius = 20f; + [SerializeField] private bool runOnStart; + + private readonly List spawnedObjects = new List(); + private Coroutine routine; + + public bool IsRunning => routine != null; + + private void Start() + { + if (runOnStart) Run(); + } + + [ContextMenu("Run Stress Scenario")] + public void Run() + { + if (routine != null || scenario == null) return; + routine = StartCoroutine(RunRoutine()); + } + + [ContextMenu("Stop Stress Scenario")] + public void Stop() + { + if (routine != null) + { + StopCoroutine(routine); + routine = null; + } + CleanupSpawnedObjects(); + } + + private IEnumerator RunRoutine() + { + if (scenario.RegenerateWorldBeforeCapture && mapGenerator != null) + { + mapGenerator.Regenerate(); + } + + SpawnNpcLoad(scenario.RequestedNpcCount); + SpawnGeneratedObjectLoad(scenario.RequestedGeneratedObjectCount); + + float warmupEnd = Time.realtimeSinceStartup + scenario.WarmupSeconds; + while (Time.realtimeSinceStartup < warmupEnd) + { + SpawnProjectileLoad(Time.unscaledDeltaTime); + yield return null; + } + + float captureEnd = Time.realtimeSinceStartup + scenario.CaptureSeconds; + while (Time.realtimeSinceStartup < captureEnd) + { + SpawnProjectileLoad(Time.unscaledDeltaTime); + yield return null; + } + + monitor?.CaptureSample(); + monitor?.WriteReports(); + CleanupSpawnedObjects(); + routine = null; + } + + private void SpawnNpcLoad(int count) + { + if (npcPrefab == null) return; + for (int i = 0; i < count; i++) + { + Vector2 offset = Random.insideUnitCircle * spawnRadius; + SpawnTracked(npcPrefab, transform.position + (Vector3)offset, Quaternion.identity); + } + } + + private void SpawnGeneratedObjectLoad(int count) + { + if (generatedLoadPrefab == null) return; + for (int i = 0; i < count; i++) + { + Vector2 offset = Random.insideUnitCircle * spawnRadius; + SpawnTracked(generatedLoadPrefab, transform.position + (Vector3)offset, Quaternion.identity); + } + } + + private void SpawnProjectileLoad(float deltaTime) + { + if (projectilePrefab == null || scenario.RequestedProjectileBurstsPerSecond <= 0) return; + float expected = scenario.RequestedProjectileBurstsPerSecond * deltaTime; + int count = Mathf.FloorToInt(expected); + if (Random.value < expected - count) count++; + + for (int i = 0; i < count; i++) + { + float angle = Random.Range(0f, 360f); + SpawnTracked(projectilePrefab, transform.position, Quaternion.Euler(0f, 0f, angle)); + } + } + + private void SpawnTracked(GameObject prefab, Vector3 position, Quaternion rotation) + { + GameObject instance = GlobalSystem.Instance != null + ? GlobalSystem.Instance.Spawn(prefab, position, rotation, spawnRoot) + : Instantiate(prefab, position, rotation, spawnRoot); + if (instance != null) spawnedObjects.Add(instance); + } + + private void CleanupSpawnedObjects() + { + RuntimeObjectPool pool = GlobalSystem.Instance != null ? GlobalSystem.Instance.ObjectPool : null; + for (int i = 0; i < spawnedObjects.Count; i++) + { + GameObject instance = spawnedObjects[i]; + if (instance == null) continue; + if (pool != null && pool.Owns(instance)) + GlobalSystem.Instance.Release(instance); + else + Destroy(instance); + } + spawnedObjects.Clear(); + } + + private void OnDisable() => Stop(); +} diff --git a/Assets/Script/PerformanceStressRunner.cs.meta b/Assets/Script/PerformanceStressRunner.cs.meta new file mode 100644 index 0000000..3d5d48c --- /dev/null +++ b/Assets/Script/PerformanceStressRunner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7086027951064611907aa0fd6ee3622b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Script/RuntimePerformanceMonitor.cs b/Assets/Script/RuntimePerformanceMonitor.cs new file mode 100644 index 0000000..1ab1af4 --- /dev/null +++ b/Assets/Script/RuntimePerformanceMonitor.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Text; +using Unity.Profiling; +using UnityEngine; +using ZoneUA.Performance; + +public sealed class RuntimePerformanceMonitor : MonoBehaviour +{ + [SerializeField] private PerformanceBudgetProfile budgetProfile; + [SerializeField, Min(0.1f)] private float sampleInterval = 1f; + [SerializeField] private bool showOverlay = true; + [SerializeField] private bool writeReportsOnDisable; + [SerializeField] private string outputBaseName = "performance-capture"; + + private readonly List samples = new List(); + private ProfilerRecorder mainThreadRecorder; + private ProfilerRecorder renderThreadRecorder; + private ProfilerRecorder gcAllocatedRecorder; + private ProfilerRecorder reservedMemoryRecorder; + private float timer; + private PerformanceSample latest; + + [Serializable] + private sealed class SampleCollection + { + public List samples = new List(); + } + + public PerformanceSample Latest => latest; + public IReadOnlyList Samples => samples; + + private void OnEnable() + { + mainThreadRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Internal, "Main Thread", 15); + renderThreadRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Internal, "Render Thread", 15); + gcAllocatedRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "GC Allocated In Frame", 15); + reservedMemoryRecorder = ProfilerRecorder.StartNew(ProfilerCategory.Memory, "Total Reserved Memory", 15); + } + + private void Update() + { + timer += Time.unscaledDeltaTime; + if (timer < sampleInterval) return; + timer = 0f; + CaptureSample(); + } + + private void OnDisable() + { + mainThreadRecorder.Dispose(); + renderThreadRecorder.Dispose(); + gcAllocatedRecorder.Dispose(); + reservedMemoryRecorder.Dispose(); + if (writeReportsOnDisable) WriteReports(); + } + + [ContextMenu("Capture Performance Sample")] + public void CaptureSample() + { + RuntimeObjectPool pool = GlobalSystem.Instance != null ? GlobalSystem.Instance.ObjectPool : null; + latest = new PerformanceSample + { + timestampSeconds = Time.realtimeSinceStartupAsDouble, + framesPerSecond = Time.unscaledDeltaTime > 0f ? 1f / Time.unscaledDeltaTime : 0f, + mainThreadMilliseconds = ToMilliseconds(mainThreadRecorder.LastValue), + renderThreadMilliseconds = ToMilliseconds(renderThreadRecorder.LastValue), + gcAllocatedBytes = gcAllocatedRecorder.LastValue, + totalReservedMemoryBytes = reservedMemoryRecorder.LastValue, + trackedPoolInstances = pool != null ? pool.TrackedInstanceCount : 0, + scheduledPoolReleases = pool != null ? pool.ScheduledReleaseCount : 0, + activeNpcCount = FindObjectsByType(FindObjectsSortMode.None).Length, + activeProjectileCount = FindObjectsByType(FindObjectsSortMode.None).Length, + generatedObjectCount = FindObjectsByType(FindObjectsSortMode.None).Length > 0 + ? CountGeneratedObjects() + : 0 + }; + samples.Add(latest); + } + + [ContextMenu("Write Performance Reports")] + public void WriteReports() + { + WriteJson(); + WriteCsv(); + } + + public void WriteJson() + { + string path = GetOutputPath("json"); + var collection = new SampleCollection { samples = new List(samples) }; + File.WriteAllText(path, JsonUtility.ToJson(collection, true)); + Debug.Log($"Performance JSON written to {path}", this); + } + + public void WriteCsv() + { + string path = GetOutputPath("csv"); + var builder = new StringBuilder(); + builder.AppendLine("timestampSeconds,fps,mainThreadMs,renderThreadMs,gcAllocatedBytes,reservedMemoryBytes,trackedPoolInstances,scheduledPoolReleases,activeNpcCount,activeProjectileCount,generatedObjectCount"); + foreach (PerformanceSample sample in samples) + { + builder.Append(sample.timestampSeconds.ToString("0.###", CultureInfo.InvariantCulture)).Append(',') + .Append(sample.framesPerSecond.ToString("0.###", CultureInfo.InvariantCulture)).Append(',') + .Append(sample.mainThreadMilliseconds.ToString("0.###", CultureInfo.InvariantCulture)).Append(',') + .Append(sample.renderThreadMilliseconds.ToString("0.###", CultureInfo.InvariantCulture)).Append(',') + .Append(sample.gcAllocatedBytes).Append(',') + .Append(sample.totalReservedMemoryBytes).Append(',') + .Append(sample.trackedPoolInstances).Append(',') + .Append(sample.scheduledPoolReleases).Append(',') + .Append(sample.activeNpcCount).Append(',') + .Append(sample.activeProjectileCount).Append(',') + .Append(sample.generatedObjectCount).AppendLine(); + } + File.WriteAllText(path, builder.ToString()); + Debug.Log($"Performance CSV written to {path}", this); + } + + private string GetOutputPath(string extension) + { + string safeBaseName = string.IsNullOrWhiteSpace(outputBaseName) ? "performance-capture" : outputBaseName.Trim(); + return Path.Combine(Application.persistentDataPath, $"{safeBaseName}.{extension}"); + } + + private void OnGUI() + { + if (!showOverlay || budgetProfile == null) return; + IReadOnlyList results = PerformanceBudgetEvaluator.Evaluate(latest, budgetProfile); + GUILayout.BeginArea(new Rect(10f, 10f, 360f, 420f), GUI.skin.box); + GUILayout.Label("Zone UA Performance"); + foreach (PerformanceBudgetResult result in results) + { + GUILayout.Label($"{result.Status}: {result.Metric} {result.Value:0.##} / {result.Budget:0.##}"); + } + GUILayout.EndArea(); + } + + private static float ToMilliseconds(long nanoseconds) => nanoseconds / 1_000_000f; + + private static int CountGeneratedObjects() + { + int count = 0; + MapGenerator[] generators = FindObjectsByType(FindObjectsSortMode.None); + foreach (MapGenerator generator in generators) count += generator.transform.childCount; + return count; + } +} diff --git a/Assets/Script/RuntimePerformanceMonitor.cs.meta b/Assets/Script/RuntimePerformanceMonitor.cs.meta new file mode 100644 index 0000000..0f7e054 --- /dev/null +++ b/Assets/Script/RuntimePerformanceMonitor.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9a54ed24aec645d19cb9c3c4cf00e4fe +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Editor/ZoneUAPerformanceTools.cs b/Assets/_ZoneUA/Editor/ZoneUAPerformanceTools.cs new file mode 100644 index 0000000..2f1aea1 --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUAPerformanceTools.cs @@ -0,0 +1,67 @@ +using System; +using System.Linq; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.SceneManagement; + +namespace ZoneUA.EditorValidation +{ + public static class ZoneUAPerformanceTools + { + [MenuItem("Zone UA/Performance/Create Stress Harness In Open Scene", priority = 40)] + public static void CreateStressHarness() + { + Scene scene = SceneManager.GetActiveScene(); + if (!scene.IsValid() || !scene.isLoaded) + { + EditorUtility.DisplayDialog("Zone UA Performance", "Open a scene before creating the stress harness.", "OK"); + return; + } + + Type monitorType = ResolveType("RuntimePerformanceMonitor"); + Type runnerType = ResolveType("PerformanceStressRunner"); + if (monitorType == null || runnerType == null) + { + EditorUtility.DisplayDialog("Zone UA Performance", "Runtime performance types are not available. Resolve compilation errors first.", "OK"); + return; + } + + GameObject existing = GameObject.Find("ZoneUA_PerformanceStressHarness"); + GameObject root = existing != null ? existing : new GameObject("ZoneUA_PerformanceStressHarness"); + Undo.RegisterCreatedObjectUndo(root, "Create performance stress harness"); + + if (root.GetComponent(monitorType) == null) Undo.AddComponent(root, monitorType); + if (root.GetComponent(runnerType) == null) Undo.AddComponent(root, runnerType); + + Selection.activeGameObject = root; + EditorGUIUtility.PingObject(root); + EditorSceneManager.MarkSceneDirty(scene); + } + + [MenuItem("Zone UA/Performance/Select Stress Harness", priority = 41)] + public static void SelectStressHarness() + { + GameObject root = GameObject.Find("ZoneUA_PerformanceStressHarness"); + if (root == null) + { + EditorUtility.DisplayDialog("Zone UA Performance", "No stress harness exists in the open scene.", "OK"); + return; + } + + Selection.activeGameObject = root; + EditorGUIUtility.PingObject(root); + } + + private static Type ResolveType(string name) + { + return AppDomain.CurrentDomain.GetAssemblies() + .SelectMany(assembly => + { + try { return assembly.GetTypes(); } + catch { return Array.Empty(); } + }) + .FirstOrDefault(type => type.Name == name); + } + } +} diff --git a/Assets/_ZoneUA/Editor/ZoneUAPerformanceTools.cs.meta b/Assets/_ZoneUA/Editor/ZoneUAPerformanceTools.cs.meta new file mode 100644 index 0000000..f6e7db2 --- /dev/null +++ b/Assets/_ZoneUA/Editor/ZoneUAPerformanceTools.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4ca4d98cb9294a0bac8de9e397a2d294 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Performance.meta b/Assets/_ZoneUA/Runtime/Performance.meta new file mode 100644 index 0000000..79488bc --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0b54dd97e9724c549ea28188882e5ced +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetEvaluator.cs b/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetEvaluator.cs new file mode 100644 index 0000000..ef5a8db --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetEvaluator.cs @@ -0,0 +1,87 @@ +using System.Collections.Generic; + +namespace ZoneUA.Performance +{ + public enum PerformanceBudgetStatus + { + Pass, + Warning, + Fail + } + + public readonly struct PerformanceBudgetResult + { + public PerformanceBudgetResult(string metric, double value, double budget, PerformanceBudgetStatus status) + { + Metric = metric; + Value = value; + Budget = budget; + Status = status; + } + + public string Metric { get; } + public double Value { get; } + public double Budget { get; } + public PerformanceBudgetStatus Status { get; } + } + + public static class PerformanceBudgetEvaluator + { + public static IReadOnlyList Evaluate( + PerformanceSample sample, + PerformanceBudgetProfile profile, + float warningRatio = 0.85f) + { + var results = new List(10); + if (profile == null) + { + return results; + } + + warningRatio = UnityEngine.Mathf.Clamp01(warningRatio); + AddMaximum(results, "Main Thread ms", sample.mainThreadMilliseconds, profile.MaximumMainThreadMilliseconds, warningRatio); + AddMaximum(results, "Render Thread ms", sample.renderThreadMilliseconds, profile.MaximumRenderThreadMilliseconds, warningRatio); + AddMaximum(results, "GC Allocated Bytes", sample.gcAllocatedBytes, profile.MaximumGcAllocatedBytesPerFrame, warningRatio); + AddMaximum(results, "Reserved Memory Bytes", sample.totalReservedMemoryBytes, profile.MaximumTotalReservedMemoryBytes, warningRatio); + AddMaximum(results, "Tracked Pool Instances", sample.trackedPoolInstances, profile.MaximumTrackedPoolInstances, warningRatio); + AddMaximum(results, "Scheduled Pool Releases", sample.scheduledPoolReleases, profile.MaximumScheduledPoolReleases, warningRatio); + AddMaximum(results, "Active NPC", sample.activeNpcCount, profile.MaximumActiveNpcCount, warningRatio); + AddMaximum(results, "Active Projectiles", sample.activeProjectileCount, profile.MaximumActiveProjectileCount, warningRatio); + AddMaximum(results, "Generated Objects", sample.generatedObjectCount, profile.MaximumGeneratedObjectCount, warningRatio); + AddMinimum(results, "FPS", sample.framesPerSecond, profile.TargetFramesPerSecond, warningRatio); + return results; + } + + private static void AddMaximum(List results, string metric, double value, double budget, float warningRatio) + { + if (budget <= 0d) + { + results.Add(new PerformanceBudgetResult(metric, value, budget, PerformanceBudgetStatus.Pass)); + return; + } + + PerformanceBudgetStatus status = value > budget + ? PerformanceBudgetStatus.Fail + : value >= budget * warningRatio + ? PerformanceBudgetStatus.Warning + : PerformanceBudgetStatus.Pass; + results.Add(new PerformanceBudgetResult(metric, value, budget, status)); + } + + private static void AddMinimum(List results, string metric, double value, double budget, float warningRatio) + { + if (budget <= 0d) + { + results.Add(new PerformanceBudgetResult(metric, value, budget, PerformanceBudgetStatus.Pass)); + return; + } + + PerformanceBudgetStatus status = value < budget * warningRatio + ? PerformanceBudgetStatus.Fail + : value < budget + ? PerformanceBudgetStatus.Warning + : PerformanceBudgetStatus.Pass; + results.Add(new PerformanceBudgetResult(metric, value, budget, status)); + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetEvaluator.cs.meta b/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetEvaluator.cs.meta new file mode 100644 index 0000000..c1470a3 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetEvaluator.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b7a5420841ee46d9ab0d4ea76b33995f +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetProfile.cs b/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetProfile.cs new file mode 100644 index 0000000..7e80d80 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetProfile.cs @@ -0,0 +1,49 @@ +using UnityEngine; + +namespace ZoneUA.Performance +{ + [CreateAssetMenu(fileName = "PerformanceBudgetProfile", menuName = "Zone UA/Performance/Budget Profile")] + public sealed class PerformanceBudgetProfile : ScriptableObject + { + [Header("Frame")] + [SerializeField, Min(1f)] private float targetFramesPerSecond = 60f; + [SerializeField, Min(0f)] private float maximumMainThreadMilliseconds = 16.67f; + [SerializeField, Min(0f)] private float maximumRenderThreadMilliseconds = 16.67f; + [SerializeField, Min(0)] private long maximumGcAllocatedBytesPerFrame = 1024; + + [Header("Runtime Objects")] + [SerializeField, Min(0)] private int maximumTrackedPoolInstances = 2000; + [SerializeField, Min(0)] private int maximumScheduledPoolReleases = 500; + [SerializeField, Min(0)] private int maximumActiveNpcCount = 150; + [SerializeField, Min(0)] private int maximumActiveProjectileCount = 500; + [SerializeField, Min(0)] private int maximumGeneratedObjectCount = 10000; + + [Header("Memory")] + [SerializeField, Min(0)] private long maximumTotalReservedMemoryBytes = 2L * 1024L * 1024L * 1024L; + + public float TargetFramesPerSecond => targetFramesPerSecond; + public float MaximumMainThreadMilliseconds => maximumMainThreadMilliseconds; + public float MaximumRenderThreadMilliseconds => maximumRenderThreadMilliseconds; + public long MaximumGcAllocatedBytesPerFrame => maximumGcAllocatedBytesPerFrame; + public int MaximumTrackedPoolInstances => maximumTrackedPoolInstances; + public int MaximumScheduledPoolReleases => maximumScheduledPoolReleases; + public int MaximumActiveNpcCount => maximumActiveNpcCount; + public int MaximumActiveProjectileCount => maximumActiveProjectileCount; + public int MaximumGeneratedObjectCount => maximumGeneratedObjectCount; + public long MaximumTotalReservedMemoryBytes => maximumTotalReservedMemoryBytes; + + private void OnValidate() + { + targetFramesPerSecond = Mathf.Max(1f, targetFramesPerSecond); + maximumMainThreadMilliseconds = Mathf.Max(0f, maximumMainThreadMilliseconds); + maximumRenderThreadMilliseconds = Mathf.Max(0f, maximumRenderThreadMilliseconds); + maximumGcAllocatedBytesPerFrame = System.Math.Max(0L, maximumGcAllocatedBytesPerFrame); + maximumTrackedPoolInstances = Mathf.Max(0, maximumTrackedPoolInstances); + maximumScheduledPoolReleases = Mathf.Max(0, maximumScheduledPoolReleases); + maximumActiveNpcCount = Mathf.Max(0, maximumActiveNpcCount); + maximumActiveProjectileCount = Mathf.Max(0, maximumActiveProjectileCount); + maximumGeneratedObjectCount = Mathf.Max(0, maximumGeneratedObjectCount); + maximumTotalReservedMemoryBytes = System.Math.Max(0L, maximumTotalReservedMemoryBytes); + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetProfile.cs.meta b/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetProfile.cs.meta new file mode 100644 index 0000000..1955b02 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/PerformanceBudgetProfile.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8a1269f0040d4e83a95d812a19cebf43 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Performance/PerformanceCaptureStatistics.cs b/Assets/_ZoneUA/Runtime/Performance/PerformanceCaptureStatistics.cs new file mode 100644 index 0000000..6a079d7 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/PerformanceCaptureStatistics.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace ZoneUA.Performance +{ + public readonly struct PerformanceCaptureStatistics + { + public PerformanceCaptureStatistics( + int sampleCount, + float averageFramesPerSecond, + float p95MainThreadMilliseconds, + float p95RenderThreadMilliseconds, + long maximumGcAllocatedBytes, + long maximumReservedMemoryBytes) + { + SampleCount = sampleCount; + AverageFramesPerSecond = averageFramesPerSecond; + P95MainThreadMilliseconds = p95MainThreadMilliseconds; + P95RenderThreadMilliseconds = p95RenderThreadMilliseconds; + MaximumGcAllocatedBytes = maximumGcAllocatedBytes; + MaximumReservedMemoryBytes = maximumReservedMemoryBytes; + } + + public int SampleCount { get; } + public float AverageFramesPerSecond { get; } + public float P95MainThreadMilliseconds { get; } + public float P95RenderThreadMilliseconds { get; } + public long MaximumGcAllocatedBytes { get; } + public long MaximumReservedMemoryBytes { get; } + + public static PerformanceCaptureStatistics From(IReadOnlyList samples) + { + if (samples == null || samples.Count == 0) + { + return default; + } + + float averageFps = samples.Average(sample => sample.framesPerSecond); + float p95Main = Percentile(samples.Select(sample => sample.mainThreadMilliseconds), 0.95f); + float p95Render = Percentile(samples.Select(sample => sample.renderThreadMilliseconds), 0.95f); + long maxGc = samples.Max(sample => sample.gcAllocatedBytes); + long maxMemory = samples.Max(sample => sample.totalReservedMemoryBytes); + + return new PerformanceCaptureStatistics( + samples.Count, + averageFps, + p95Main, + p95Render, + maxGc, + maxMemory); + } + + private static float Percentile(IEnumerable values, float percentile) + { + float[] ordered = values.OrderBy(value => value).ToArray(); + if (ordered.Length == 0) + { + return 0f; + } + + percentile = Math.Max(0f, Math.Min(1f, percentile)); + int index = (int)Math.Ceiling(percentile * ordered.Length) - 1; + index = Math.Max(0, Math.Min(ordered.Length - 1, index)); + return ordered[index]; + } + } +} diff --git a/Assets/_ZoneUA/Runtime/Performance/PerformanceCaptureStatistics.cs.meta b/Assets/_ZoneUA/Runtime/Performance/PerformanceCaptureStatistics.cs.meta new file mode 100644 index 0000000..a89357d --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/PerformanceCaptureStatistics.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 39995a1a4dc246ea86b66c77a0cf8d8b +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Performance/PerformanceSample.cs b/Assets/_ZoneUA/Runtime/Performance/PerformanceSample.cs new file mode 100644 index 0000000..1fa2b37 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/PerformanceSample.cs @@ -0,0 +1,20 @@ +using System; + +namespace ZoneUA.Performance +{ + [Serializable] + public struct PerformanceSample + { + public double timestampSeconds; + public float framesPerSecond; + public float mainThreadMilliseconds; + public float renderThreadMilliseconds; + public long gcAllocatedBytes; + public long totalReservedMemoryBytes; + public int trackedPoolInstances; + public int scheduledPoolReleases; + public int activeNpcCount; + public int activeProjectileCount; + public int generatedObjectCount; + } +} diff --git a/Assets/_ZoneUA/Runtime/Performance/PerformanceSample.cs.meta b/Assets/_ZoneUA/Runtime/Performance/PerformanceSample.cs.meta new file mode 100644 index 0000000..8f73676 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/PerformanceSample.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d57907bb0b7d4b488a844a1a9517f371 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Performance/StressScenarioDefinition.cs b/Assets/_ZoneUA/Runtime/Performance/StressScenarioDefinition.cs new file mode 100644 index 0000000..4382572 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/StressScenarioDefinition.cs @@ -0,0 +1,24 @@ +using UnityEngine; + +namespace ZoneUA.Performance +{ + [CreateAssetMenu(fileName = "StressScenario", menuName = "Zone UA/Performance/Stress Scenario")] + public sealed class StressScenarioDefinition : ScriptableObject + { + [SerializeField, Min(1f)] private float warmupSeconds = 5f; + [SerializeField, Min(1f)] private float captureSeconds = 30f; + [SerializeField, Min(0)] private int requestedNpcCount = 50; + [SerializeField, Min(0)] private int requestedProjectileBurstsPerSecond = 20; + [SerializeField, Min(0)] private int requestedGeneratedObjectCount = 3000; + [SerializeField] private bool regenerateWorldBeforeCapture = true; + [SerializeField] private PerformanceBudgetProfile budgetProfile; + + public float WarmupSeconds => warmupSeconds; + public float CaptureSeconds => captureSeconds; + public int RequestedNpcCount => requestedNpcCount; + public int RequestedProjectileBurstsPerSecond => requestedProjectileBurstsPerSecond; + public int RequestedGeneratedObjectCount => requestedGeneratedObjectCount; + public bool RegenerateWorldBeforeCapture => regenerateWorldBeforeCapture; + public PerformanceBudgetProfile BudgetProfile => budgetProfile; + } +} diff --git a/Assets/_ZoneUA/Runtime/Performance/StressScenarioDefinition.cs.meta b/Assets/_ZoneUA/Runtime/Performance/StressScenarioDefinition.cs.meta new file mode 100644 index 0000000..9c6baa8 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/StressScenarioDefinition.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 46d58fa9d3d44b82a7de470e7ecb1857 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Runtime/Performance/ZoneUA.Performance.asmdef b/Assets/_ZoneUA/Runtime/Performance/ZoneUA.Performance.asmdef new file mode 100644 index 0000000..3535b04 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/ZoneUA.Performance.asmdef @@ -0,0 +1,14 @@ +{ + "name": "ZoneUA.Performance", + "rootNamespace": "ZoneUA.Performance", + "references": [], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Assets/_ZoneUA/Runtime/Performance/ZoneUA.Performance.asmdef.meta b/Assets/_ZoneUA/Runtime/Performance/ZoneUA.Performance.asmdef.meta new file mode 100644 index 0000000..88b8df0 --- /dev/null +++ b/Assets/_ZoneUA/Runtime/Performance/ZoneUA.Performance.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: a0e9fb60d43d48c4bbf35d89d8768c9d +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Tests/EditMode/PerformanceBudgetTests.cs b/Assets/_ZoneUA/Tests/EditMode/PerformanceBudgetTests.cs new file mode 100644 index 0000000..fac06eb --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/PerformanceBudgetTests.cs @@ -0,0 +1,86 @@ +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; +using UnityEngine; +using ZoneUA.Performance; + +namespace ZoneUA.Combat.Tests +{ + public sealed class PerformanceBudgetTests + { + [Test] + public void Evaluate_PassingSample_ReturnsNoFailures() + { + PerformanceBudgetProfile profile = ScriptableObject.CreateInstance(); + var sample = new PerformanceSample + { + framesPerSecond = 60f, + mainThreadMilliseconds = 5f, + renderThreadMilliseconds = 5f, + gcAllocatedBytes = 0, + totalReservedMemoryBytes = 128 * 1024 * 1024, + trackedPoolInstances = 10, + scheduledPoolReleases = 2, + activeNpcCount = 5, + activeProjectileCount = 10, + generatedObjectCount = 100 + }; + + var results = PerformanceBudgetEvaluator.Evaluate(sample, profile); + + Assert.That(results.Any(result => result.Status == PerformanceBudgetStatus.Fail), Is.False); + Object.DestroyImmediate(profile); + } + + [Test] + public void Evaluate_ExceededFrameAndFpsBudgets_ReturnsFailures() + { + PerformanceBudgetProfile profile = ScriptableObject.CreateInstance(); + var sample = new PerformanceSample + { + framesPerSecond = 20f, + mainThreadMilliseconds = 40f + }; + + var results = PerformanceBudgetEvaluator.Evaluate(sample, profile); + + Assert.That(results.Single(result => result.Metric == "FPS").Status, Is.EqualTo(PerformanceBudgetStatus.Fail)); + Assert.That(results.Single(result => result.Metric == "Main Thread ms").Status, Is.EqualTo(PerformanceBudgetStatus.Fail)); + Object.DestroyImmediate(profile); + } + + [Test] + public void Evaluate_NullProfile_ReturnsEmptyResult() + { + var results = PerformanceBudgetEvaluator.Evaluate(default, null); + Assert.That(results, Is.Empty); + } + + [Test] + public void Statistics_UsesAverageP95AndMaximumValues() + { + var samples = new List + { + new PerformanceSample { framesPerSecond = 60f, mainThreadMilliseconds = 5f, renderThreadMilliseconds = 4f, gcAllocatedBytes = 10, totalReservedMemoryBytes = 100 }, + new PerformanceSample { framesPerSecond = 30f, mainThreadMilliseconds = 15f, renderThreadMilliseconds = 14f, gcAllocatedBytes = 20, totalReservedMemoryBytes = 200 }, + new PerformanceSample { framesPerSecond = 45f, mainThreadMilliseconds = 10f, renderThreadMilliseconds = 9f, gcAllocatedBytes = 15, totalReservedMemoryBytes = 150 } + }; + + PerformanceCaptureStatistics statistics = PerformanceCaptureStatistics.From(samples); + + Assert.That(statistics.SampleCount, Is.EqualTo(3)); + Assert.That(statistics.AverageFramesPerSecond, Is.EqualTo(45f)); + Assert.That(statistics.P95MainThreadMilliseconds, Is.EqualTo(15f)); + Assert.That(statistics.P95RenderThreadMilliseconds, Is.EqualTo(14f)); + Assert.That(statistics.MaximumGcAllocatedBytes, Is.EqualTo(20)); + Assert.That(statistics.MaximumReservedMemoryBytes, Is.EqualTo(200)); + } + + [Test] + public void Statistics_EmptyCapture_ReturnsDefault() + { + PerformanceCaptureStatistics statistics = PerformanceCaptureStatistics.From(new List()); + Assert.That(statistics.SampleCount, Is.Zero); + } + } +} diff --git a/Assets/_ZoneUA/Tests/EditMode/PerformanceBudgetTests.cs.meta b/Assets/_ZoneUA/Tests/EditMode/PerformanceBudgetTests.cs.meta new file mode 100644 index 0000000..343f2d7 --- /dev/null +++ b/Assets/_ZoneUA/Tests/EditMode/PerformanceBudgetTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 739c0f239cf847cab2b8980cc9a848ec +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef b/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef index eaa4057..b75b14d 100644 --- a/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef +++ b/Assets/_ZoneUA/Tests/EditMode/ZoneUA.Combat.EditModeTests.asmdef @@ -8,7 +8,8 @@ "ZoneUA.Infrastructure", "ZoneUA.AI", "ZoneUA.World", - "ZoneUA.Input" + "ZoneUA.Input", + "ZoneUA.Performance" ], "includePlatforms": [ "Editor" diff --git a/Docs/PERFORMANCE_BUDGETS_STRESS_TESTING.md b/Docs/PERFORMANCE_BUDGETS_STRESS_TESTING.md new file mode 100644 index 0000000..862555c --- /dev/null +++ b/Docs/PERFORMANCE_BUDGETS_STRESS_TESTING.md @@ -0,0 +1,155 @@ +# Performance budgets and stress testing + +This module provides repeatable performance capture for the Zone UA Unity project. It is intentionally separated from gameplay balancing and visual redesign. + +## Assets + +Create the following assets in Unity: + +- `Create -> Zone UA -> Performance -> Budget Profile` +- `Create -> Zone UA -> Performance -> Stress Scenario` + +The budget profile defines thresholds for: + +- target frames per second; +- main-thread time; +- render-thread time; +- GC allocation per frame; +- reserved memory; +- tracked pooled instances; +- scheduled delayed releases; +- active NPCs; +- active projectiles; +- generated objects. + +The stress scenario defines: + +- warm-up duration; +- capture duration; +- requested NPC count; +- projectile spawn rate; +- generated-object load; +- whether the world is regenerated before capture; +- the budget profile used to evaluate the run. + +## Scene setup + +Use: + +`Zone UA -> Performance -> Create Stress Harness In Open Scene` + +The command creates a `ZoneUA_PerformanceStressHarness` object with: + +- `RuntimePerformanceMonitor`; +- `PerformanceStressRunner`. + +Assign in the Inspector: + +### RuntimePerformanceMonitor + +- Budget Profile; +- Sample Interval; +- Overlay visibility; +- output base name. + +### PerformanceStressRunner + +- Stress Scenario; +- Runtime Performance Monitor; +- Map Generator; +- representative NPC prefab; +- representative projectile prefab; +- optional lightweight generated-load prefab; +- optional spawn root. + +Do not use placeholder prefabs for the final baseline. The stress scene must use the same production prefabs and definitions as normal gameplay. + +## Capture lifecycle + +A run performs: + +1. optional world regeneration; +2. NPC and generated-object load creation; +3. warm-up; +4. sustained projectile load; +5. timed capture; +6. final sample capture; +7. JSON and CSV export; +8. cleanup through the runtime object pool when possible. + +Reports are written under `Application.persistentDataPath`. + +The JSON output is intended for CI and automated comparison. The CSV output is intended for spreadsheets and manual analysis. + +## Runtime counters + +`RuntimePerformanceMonitor` records: + +- instantaneous FPS; +- main-thread milliseconds; +- render-thread milliseconds; +- allocated GC bytes; +- total reserved memory; +- pool instance count; +- scheduled pool releases; +- active NPC count; +- active projectile count; +- generated-object count. + +`PerformanceCaptureStatistics` calculates average FPS, p95 main/render thread time and maximum GC/memory values from a complete capture. + +The overlay is intended only for Editor and Development builds. Disable it in production builds after the baseline is established. + +## Initial budgets + +The default profile values are starting guardrails, not verified hardware targets. Record baselines on the actual target device classes before tightening them. + +Recommended baseline matrix: + +- development desktop; +- minimum supported desktop; +- representative Android device; +- representative high-load world seed; +- representative combat encounter; +- worst-case NPC density. + +Track median and high-percentile behaviour. A single fast frame does not prove that a scenario is stable. + +## Required validation + +- Open the project in Unity 6000.5.5f1. +- Confirm `ProfilerRecorder` counters are available on the target platform. +- Run all `PerformanceBudgetTests`. +- Create the stress harness in a dedicated development scene. +- Assign production NPC, projectile and world prefabs. +- Run the scenario for at least 30 seconds after warm-up. +- Verify JSON and CSV files are produced. +- Verify pooled instances return correctly after cleanup. +- Verify no projectile from an earlier lease is released during a later lease. +- Verify the stress harness does not remain in production scenes. +- Record CPU, memory, GC and active-object baselines before optimisation. + +## CI use + +The pure budget evaluator is covered by EditMode tests and can participate in the existing GameCI job. + +Use the report checker after downloading a JSON capture: + +```bash +python scripts/check_performance_capture.py performance-capture.json \ + --minimum-average-fps 60 \ + --maximum-p95-main-thread-ms 16.67 \ + --maximum-p95-render-thread-ms 16.67 \ + --maximum-gc-bytes 1024 \ + --maximum-reserved-memory-bytes 2147483648 +``` + +A future licensed PlayMode performance job should: + +1. open a dedicated stress scene; +2. run the configured scenario; +3. upload JSON and CSV reports; +4. run `check_performance_capture.py` with platform-specific thresholds; +5. fail only on sustained or statistically meaningful regressions. + +Do not fail CI on one noisy frame. Use a stable capture window and target-hardware-specific thresholds. diff --git a/Docs/PERFORMANCE_BUDGETS_STRESS_TESTING.md.meta b/Docs/PERFORMANCE_BUDGETS_STRESS_TESTING.md.meta new file mode 100644 index 0000000..7b4b0c3 --- /dev/null +++ b/Docs/PERFORMANCE_BUDGETS_STRESS_TESTING.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 689b8b458f074ef1b9ab864558be584d +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/scripts/check_performance_capture.py b/scripts/check_performance_capture.py new file mode 100644 index 0000000..02021a6 --- /dev/null +++ b/scripts/check_performance_capture.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +"""Validate a RuntimePerformanceMonitor JSON capture against CI thresholds.""" + +from __future__ import annotations + +import argparse +import json +import math +import pathlib +import sys +from typing import Any + + +def percentile(values: list[float], ratio: float) -> float: + if not values: + return 0.0 + ordered = sorted(values) + index = max(0, min(len(ordered) - 1, math.ceil(ratio * len(ordered)) - 1)) + return ordered[index] + + +def load_samples(path: pathlib.Path) -> list[dict[str, Any]]: + payload = json.loads(path.read_text(encoding="utf-8")) + samples = payload.get("samples") + if not isinstance(samples, list) or not samples: + raise ValueError("capture contains no samples") + return samples + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("capture", type=pathlib.Path) + parser.add_argument("--minimum-average-fps", type=float, default=0.0) + parser.add_argument("--maximum-p95-main-thread-ms", type=float, default=0.0) + parser.add_argument("--maximum-p95-render-thread-ms", type=float, default=0.0) + parser.add_argument("--maximum-gc-bytes", type=int, default=0) + parser.add_argument("--maximum-reserved-memory-bytes", type=int, default=0) + args = parser.parse_args() + + try: + samples = load_samples(args.capture) + except (OSError, ValueError, json.JSONDecodeError) as error: + print(f"ERROR: {error}") + return 2 + + average_fps = sum(float(sample.get("framesPerSecond", 0.0)) for sample in samples) / len(samples) + p95_main = percentile([float(sample.get("mainThreadMilliseconds", 0.0)) for sample in samples], 0.95) + p95_render = percentile([float(sample.get("renderThreadMilliseconds", 0.0)) for sample in samples], 0.95) + maximum_gc = max(int(sample.get("gcAllocatedBytes", 0)) for sample in samples) + maximum_memory = max(int(sample.get("totalReservedMemoryBytes", 0)) for sample in samples) + + print(f"samples={len(samples)}") + print(f"average_fps={average_fps:.3f}") + print(f"p95_main_thread_ms={p95_main:.3f}") + print(f"p95_render_thread_ms={p95_render:.3f}") + print(f"maximum_gc_bytes={maximum_gc}") + print(f"maximum_reserved_memory_bytes={maximum_memory}") + + failures: list[str] = [] + if args.minimum_average_fps > 0 and average_fps < args.minimum_average_fps: + failures.append(f"average FPS {average_fps:.3f} < {args.minimum_average_fps:.3f}") + if args.maximum_p95_main_thread_ms > 0 and p95_main > args.maximum_p95_main_thread_ms: + failures.append(f"p95 main thread {p95_main:.3f} ms > {args.maximum_p95_main_thread_ms:.3f} ms") + if args.maximum_p95_render_thread_ms > 0 and p95_render > args.maximum_p95_render_thread_ms: + failures.append(f"p95 render thread {p95_render:.3f} ms > {args.maximum_p95_render_thread_ms:.3f} ms") + if args.maximum_gc_bytes > 0 and maximum_gc > args.maximum_gc_bytes: + failures.append(f"maximum GC {maximum_gc} > {args.maximum_gc_bytes} bytes") + if args.maximum_reserved_memory_bytes > 0 and maximum_memory > args.maximum_reserved_memory_bytes: + failures.append(f"maximum reserved memory {maximum_memory} > {args.maximum_reserved_memory_bytes} bytes") + + if failures: + for failure in failures: + print(f"FAIL: {failure}") + return 1 + + print("PASS: performance capture is within configured thresholds") + return 0 + + +if __name__ == "__main__": + sys.exit(main())