Files
vampire-like/Assets/GameMain/Scripts/Procedure/DebugPanel/RuntimeDebugPanelComponent.cs
T
2026-09-18 21:43:22 +08:00

562 lines
20 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using SepCore.Event;
using SepCore.Definition;
using SepCore.Entity;
using SepCore.Components;
using SepCore.CustomUtility;
using SepCore.Simulation;
using SepCore.EnemyManager;
using SepCore.Procedure;
using UnityEngine;
using UnityGameFramework.Runtime;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
namespace SepCore.DebugPanel
{
public class RuntimeDebugPanelComponent : MonoBehaviour
{
private const float MinSpawnRate = 0.1f;
private const float CornerTapWindow = 0.6f;
private const int RequiredCornerTapCount = 3;
private const int DebugHealAmount = 200;
[Header("Window Content")]
[SerializeField] private bool _showBuffSection = true;
[SerializeField] private bool _showBattleOverview = true;
[SerializeField] private bool _showCollisionStats = true;
[SerializeField] private bool _showSpawnControls = true;
[SerializeField] private bool _showBattleDurationControls = true;
[SerializeField] private bool _showPlayerWeaponControls = true;
[SerializeField] private bool _showPlayerHealthControls = true;
[SerializeField] private bool _showTips = true;
private Rect _windowRect;
private Vector2 _panelScroll;
private GUISkin _panelSkin;
private bool _isPanelVisible;
private int _windowId;
private string _searchText = string.Empty;
private int _selectedIndex;
private int _addCount = 1;
private Vector2 _buffScroll;
private float _spawnRateScaleInput = 1f;
private float _extendDurationSeconds = 30f;
private IReadOnlyList<PropConfig> _allProps;
private IReadOnlyList<PropConfig> _filteredProps;
private string[] _displayNames = Array.Empty<string>();
private int _cornerTapCount;
private float _lastCornerTapTime = -10f;
private bool _lockPlayerHealthToMax;
private void Awake()
{
_windowId = GetInstanceID();
}
private void Update()
{
if (IsTogglePressed())
{
_isPanelVisible = !_isPanelVisible;
}
HandleCornerTapGesture();
if (_lockPlayerHealthToMax)
{
KeepPlayerHealthAtMax();
}
}
private void OnGUI()
{
GUISkin previousSkin = GUI.skin;
Matrix4x4 previousMatrix = GUI.matrix;
if (_panelSkin == null)
{
_panelSkin = Instantiate(previousSkin);
_panelSkin.label.fontSize = 18;
_panelSkin.label.wordWrap = true;
_panelSkin.button.fontSize = 18;
_panelSkin.button.padding = new RectOffset(12, 12, 10, 10);
_panelSkin.button.fixedHeight = 44f;
_panelSkin.textField.fontSize = 20;
_panelSkin.textField.fixedHeight = 44f;
_panelSkin.textField.padding = new RectOffset(10, 10, 10, 10);
_panelSkin.window.padding = new RectOffset(16, 16, 12, 16);
_panelSkin.verticalScrollbar.fixedWidth = 28f;
_panelSkin.verticalScrollbarThumb.fixedWidth = 28f;
}
Rect safeArea = Screen.safeArea;
float scale = Mathf.Max(0.1f, Mathf.Min(safeArea.width, safeArea.height) / 480f);
Rect bounds = new Rect(0f, 0f, safeArea.width / scale, safeArea.height / scale);
try
{
GUI.skin = _panelSkin;
GUI.matrix = Matrix4x4.TRS(
new Vector3(safeArea.x, Screen.height - safeArea.yMax, 0f),
Quaternion.identity, new Vector3(scale, scale, 1f));
DrawToggleButton(bounds);
if (!_isPanelVisible) return;
float width = Mathf.Min(460f, bounds.width - 24f);
_windowRect = new Rect(bounds.width - width - 12f, 72f, width,
Mathf.Min(760f, bounds.height - 84f));
GUI.Window(_windowId, _windowRect, DrawWindow, string.Empty);
}
finally
{
GUI.matrix = previousMatrix;
GUI.skin = previousSkin;
}
}
private void OnDestroy()
{
if (_panelSkin != null) Destroy(_panelSkin);
}
private void DrawToggleButton(Rect bounds)
{
const float width = 120f;
const float height = 48f;
Rect buttonRect = new Rect(bounds.width - width - 12f, 12f, width, height);
if (GUI.Button(buttonRect, "DEBUG"))
{
_isPanelVisible = !_isPanelVisible;
}
}
private void DrawWindow(int windowId)
{
if (_showBuffSection)
{
EnsurePropList();
}
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
GUILayout.Label("Runtime Debug", GUILayout.ExpandWidth(true));
if (GUILayout.Button("Close", GUILayout.Width(90f))) _isPanelVisible = false;
GUILayout.EndHorizontal();
GUILayout.Space(8f);
_panelScroll = GUILayout.BeginScrollView(_panelScroll, false, true);
bool hasPreviousSection = false;
if (_showBuffSection)
{
DrawBuffSection();
hasPreviousSection = true;
}
if (HasVisibleBattleSection())
{
if (hasPreviousSection)
{
GUILayout.Space(8f);
GUILayout.Label(string.Empty, GUI.skin.horizontalSlider);
GUILayout.Space(8f);
}
DrawBattleSection();
hasPreviousSection = true;
}
if (_showTips)
{
if (hasPreviousSection)
{
GUILayout.Space(8f);
}
GUILayout.Label("Tips: press F8 or tap top-left corner 3 times to toggle.");
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
}
private void DrawBuffSection()
{
GUILayout.Label("Buff Debug");
GUILayout.BeginHorizontal();
GUILayout.Label("Search", GUILayout.Width(78f));
_searchText = GUILayout.TextField(_searchText);
if (GUILayout.Button("Refresh", GUILayout.Width(100f)))
{
EnsurePropList(true);
}
GUILayout.EndHorizontal();
ApplyFilter(_searchText);
if (_displayNames.Length == 0)
{
GUILayout.Label("No Buff data. Enter battle and try again.");
return;
}
_selectedIndex = Mathf.Clamp(_selectedIndex, 0, _displayNames.Length - 1);
_buffScroll = GUILayout.BeginScrollView(_buffScroll, GUILayout.Height(120f));
_selectedIndex = GUILayout.SelectionGrid(_selectedIndex, _displayNames, 1);
GUILayout.EndScrollView();
PropConfig selectedProp = GetSelectedProp();
if (selectedProp == null) return;
GUILayout.Label($"Selected: {selectedProp.Name} ({selectedProp.Rarity})");
GUILayout.Label(ItemDescUtility.CreatePropDescription(selectedProp.StatModifierConfigs), GUILayout.Height(40f));
GUILayout.BeginHorizontal();
GUILayout.Label("Count", GUILayout.Width(78f));
string addCountText = GUILayout.TextField(_addCount.ToString(), GUILayout.Width(88f));
if (!int.TryParse(addCountText, out _addCount)) _addCount = 1;
_addCount = Mathf.Clamp(_addCount, 1, 99);
if (GUILayout.Button("Add Buff To Player", GUILayout.Height(44f)))
{
AddSelectedBuffToPlayer(selectedProp, _addCount);
}
GUILayout.EndHorizontal();
}
private void DrawBattleSection()
{
GUILayout.Label("Battle Debug");
ProcedureGame procedure = GameEntry.Procedure.CurrentProcedure as ProcedureGame;
Player player = FindPlayer();
HealthComponent playerHealth = player != null ? player.GetComponent<HealthComponent>() : null;
if (procedure == null)
{
GUILayout.Label("ProcedureGame unavailable.");
return;
}
EnemyManagerComponent enemyManager = GameEntry.EnemyManager;
if (_showBattleOverview)
{
GUILayout.Label($"Spawn Rate: {enemyManager.SpawnRateScale:F2}");
GUILayout.Label(
$"Battle Time: {enemyManager.ElapsedBattleTime:F1}s / {enemyManager.BattleDuration:F1}s");
GUILayout.Label($"Enemy Count: {enemyManager.CurrentEnemyCount}");
}
if (_showCollisionStats)
{
SimulationStats simulationStats = GameEntry.SimulationWorld.Stats;
GUILayout.Space(4f);
GUILayout.Label(
$"Collision Queries: total {simulationStats.LastCollisionQueryCount} (Projectile {simulationStats.LastProjectileCollisionQueryCount} / Area {simulationStats.LastAreaCollisionQueryCount})");
GUILayout.Label(
$"Collision Candidates: total {simulationStats.LastCollisionCandidateCount} (Projectile {simulationStats.LastProjectileCollisionCandidateCount} / Area {simulationStats.LastAreaCollisionCandidateCount})");
GUILayout.Label(
$"Area Resolve: hits {simulationStats.LastResolvedAreaHitCount}");
GUILayout.Label(
$"Broad Phase: cell {simulationStats.LastCollisionCellSize:F2}, hasEnemyTargets {(simulationStats.LastCollisionHasEnemyTargets ? "Yes" : "No")}");
}
if (_showSpawnControls)
{
GUILayout.Space(12f);
GUILayout.Label("Enemy Spawn Rate");
GUILayout.BeginHorizontal();
GUILayout.Label("Rate", GUILayout.Width(78f));
string rateText = GUILayout.TextField(_spawnRateScaleInput.ToString("F2"), GUILayout.Width(88f));
if (float.TryParse(rateText, out float parsedRate))
{
_spawnRateScaleInput = Mathf.Clamp(parsedRate, MinSpawnRate, 50f);
}
if (GUILayout.Button("Apply", GUILayout.Width(100f)))
{
enemyManager.SetSpawnRateScale(_spawnRateScaleInput);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
if (GUILayout.Button("x0.5"))
{
_spawnRateScaleInput = Mathf.Max(MinSpawnRate, enemyManager.SpawnRateScale * 0.5f);
enemyManager.SetSpawnRateScale(_spawnRateScaleInput);
}
if (GUILayout.Button("x2"))
{
_spawnRateScaleInput = enemyManager.SpawnRateScale * 2f;
enemyManager.SetSpawnRateScale(_spawnRateScaleInput);
}
GUILayout.EndHorizontal();
}
if (_showBattleDurationControls)
{
GUILayout.Space(12f);
GUILayout.Label("Battle Duration");
GUILayout.BeginHorizontal();
GUILayout.Label("Add Sec", GUILayout.Width(78f));
string durationText = GUILayout.TextField(_extendDurationSeconds.ToString("F0"), GUILayout.Width(88f));
if (float.TryParse(durationText, out float parsedDuration))
{
_extendDurationSeconds = Mathf.Clamp(parsedDuration, 1f, 3600f);
}
if (GUILayout.Button("Extend Battle", GUILayout.Height(44f)))
{
if (procedure.CurrentGameState is GameStateBattle gameState)
{
gameState.AddBattleDuration(_extendDurationSeconds);
}
}
GUILayout.EndHorizontal();
}
if (_showPlayerWeaponControls)
{
GUILayout.Space(12f);
GUILayout.Label(
$"Player Weapon: {(player == null ? "Player not found" : (player.WeaponEnabled ? "Enabled" : "Disabled"))}");
GUILayout.BeginHorizontal();
GUI.enabled = player != null;
if (GUILayout.Button("Disable Weapons", GUILayout.Height(44f)))
{
player.SetWeaponEnabled(false);
}
if (GUILayout.Button("Enable Weapons", GUILayout.Height(44f)))
{
player.SetWeaponEnabled(true);
}
GUI.enabled = true;
GUILayout.EndHorizontal();
}
if (_showPlayerHealthControls)
{
GUILayout.Space(4f);
GUILayout.Label(
$"Player HP: {(playerHealth == null ? "Unavailable" : $"{playerHealth.CurrentHealth}/{playerHealth.MaxHealth}")}");
GUILayout.BeginHorizontal();
GUI.enabled = playerHealth != null;
if (GUILayout.Button($"+{DebugHealAmount} HP", GUILayout.Height(44f)))
{
AddPlayerHealth(playerHealth, DebugHealAmount);
}
if (GUILayout.Button(_lockPlayerHealthToMax ? "GodMode: ON" : "GodMode: OFF", GUILayout.Height(44f)))
{
_lockPlayerHealthToMax = !_lockPlayerHealthToMax;
if (_lockPlayerHealthToMax)
{
RestorePlayerHealthToMax(playerHealth);
}
}
GUI.enabled = true;
GUILayout.EndHorizontal();
}
}
private bool HasVisibleBattleSection()
{
return _showBattleOverview ||
_showCollisionStats ||
_showSpawnControls ||
_showBattleDurationControls ||
_showPlayerWeaponControls ||
_showPlayerHealthControls;
}
private void EnsurePropList(bool force = false)
{
if (!force && _allProps != null && _allProps.Count > 0) return;
if (!GameEntry.Luban.IsReady)
{
_allProps = Array.Empty<PropConfig>();
_displayNames = Array.Empty<string>();
return;
}
_allProps = GameEntry.Luban.GetTable<PropConfig>();
_selectedIndex = Mathf.Clamp(_selectedIndex, 0, Mathf.Max(0, _allProps.Count - 1));
ApplyFilter(_searchText);
}
private void ApplyFilter(string keyword)
{
if (_allProps == null || _allProps.Count == 0)
{
_displayNames = Array.Empty<string>();
return;
}
if (string.IsNullOrWhiteSpace(keyword))
{
_filteredProps = _allProps;
}
else
{
string search = keyword.Trim();
_filteredProps = _allProps.Where(p =>
p.Name.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0 ||
p.Id.ToString().Contains(search)).ToArray();
}
_displayNames = _filteredProps.Select(p => $"[{p.Id}] {p.Name} ({p.Rarity})").ToArray();
if (_displayNames.Length == 0) _selectedIndex = 0;
else _selectedIndex = Mathf.Clamp(_selectedIndex, 0, _displayNames.Length - 1);
}
private PropConfig GetSelectedProp()
{
if (_filteredProps == null || _filteredProps.Count == 0) return null;
_selectedIndex = Mathf.Clamp(_selectedIndex, 0, _filteredProps.Count - 1);
return _filteredProps[_selectedIndex];
}
private static Player FindPlayer()
{
return UnityEngine.Object.FindObjectOfType<Player>();
}
private void KeepPlayerHealthAtMax()
{
Player player = FindPlayer();
if (player == null) return;
HealthComponent playerHealth = player.GetComponent<HealthComponent>();
RestorePlayerHealthToMax(playerHealth);
}
private static void AddPlayerHealth(HealthComponent playerHealth, int amount)
{
if (amount <= 0) return;
if (playerHealth.CurrentHealth <= 0) return;
int maxHealth = playerHealth.MaxHealth;
if (maxHealth <= 0) return;
int nextHealth = Mathf.Clamp(playerHealth.CurrentHealth + amount, 0, maxHealth);
if (nextHealth == playerHealth.CurrentHealth) return;
playerHealth.CurrentHealth = nextHealth;
PublishPlayerHealthChanged(playerHealth);
}
private static void RestorePlayerHealthToMax(HealthComponent playerHealth)
{
if (playerHealth.CurrentHealth <= 0) return;
int maxHealth = playerHealth.MaxHealth;
if (maxHealth <= 0 || playerHealth.CurrentHealth >= maxHealth) return;
playerHealth.CurrentHealth = maxHealth;
PublishPlayerHealthChanged(playerHealth);
}
private static void PublishPlayerHealthChanged(HealthComponent playerHealth)
{
GameEntry.Event.Fire(null,
PlayerHealthChangeEventArgs.Create(0, playerHealth.CurrentHealth, playerHealth.MaxHealth));
}
private static void AddSelectedBuffToPlayer(PropConfig prop, int count)
{
Player player = FindPlayer();
if (player == null) return;
int applyCount = Mathf.Clamp(count, 1, 99);
for (int i = 0; i < applyCount; i++)
{
player.AddProp(new PropItem(prop));
}
}
private void HandleCornerTapGesture()
{
if (!TryGetTouchReleased(out Vector2 touchPosition)) return;
if (touchPosition.x > 80f || touchPosition.y < Screen.height - 80f) return;
float now = Time.unscaledTime;
if (now - _lastCornerTapTime > CornerTapWindow)
{
_cornerTapCount = 0;
}
_lastCornerTapTime = now;
_cornerTapCount++;
if (_cornerTapCount >= RequiredCornerTapCount)
{
_cornerTapCount = 0;
_isPanelVisible = !_isPanelVisible;
}
}
private static bool IsTogglePressed()
{
#if ENABLE_INPUT_SYSTEM
Keyboard keyboard = Keyboard.current;
if (keyboard == null) return false;
return keyboard.backquoteKey.wasPressedThisFrame || keyboard.f8Key.wasPressedThisFrame;
#else
return Input.GetKeyDown(KeyCode.BackQuote) || Input.GetKeyDown(KeyCode.F8);
#endif
}
private static bool TryGetTouchReleased(out Vector2 touchPosition)
{
#if ENABLE_INPUT_SYSTEM
Touchscreen touchscreen = Touchscreen.current;
if (touchscreen == null)
{
touchPosition = default;
return false;
}
var touch = touchscreen.primaryTouch;
if (!touch.press.wasReleasedThisFrame)
{
touchPosition = default;
return false;
}
touchPosition = touch.position.ReadValue();
return true;
#else
if (Input.touchCount <= 0)
{
touchPosition = default;
return false;
}
Touch touch = Input.GetTouch(0);
if (touch.phase != TouchPhase.Ended)
{
touchPosition = default;
return false;
}
touchPosition = touch.position;
return true;
#endif
}
}
}