Files
chameleon/Assets/Scripts/GameMode/GameModeManager.cs
T
adminandClaude Opus 4.8 bfcd84afe4 Add manual radar ping, blip refresh/fade, and resolution statue barrier
- Manual hider ping on "E": server-authoritative RequestManualPing gated to
  Seek + living hider; shared EmitRadarPings path so interval and manual pings
  produce identical blips. Ping key read client-side in GameModeManager, role-
  gated and excluded in FreeCam (E is fly-up there).
- Radar refreshes an existing blip for the same transform target instead of
  duplicating it (lifetime resets to the configured value) via RadarTarget.Refresh.
- Blips fade in/out independently of the disc fade: per-blip MoveTowards factor
  multiplied on top of the radar fade, refresh-safe, with separate in/out speeds.
- Resolution countdown waits for conversion statues to load: generalized the
  match-start loading barrier (RunReadinessBarrier over _barrierTargets, hold
  phase carried in MsgBeginLoad) and run it a second time over statue IDs before
  starting the real resolveDuration. Only holds for Conversion with real statues.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-06 13:59:28 +02:00

552 lines
25 KiB
C#

using System.Collections.Generic;
using UnityEngine;
using Unity.Cinemachine;
using Chameleon.Components;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
/// <summary>
/// Switches the game between high-level modes. The switch key (Tab) cycles to the next registered
/// mode. The mode set is scoped to the local avatar's <see cref="PlayerRole"/> when it spawns
/// (Hunter: First Person + Paint; Hider: Player Control + Paint + Free Cam); a non-networked scene
/// uses the full set. Attach to a single, persistent scene GameObject.
/// </summary>
[DisallowMultipleComponent]
public class GameModeManager : MonoBehaviour
{
[Header("Controlled Systems")]
[Tooltip("Player movement controller. Empty = found automatically.")]
public PlayerCharacterController player;
[Tooltip("Third-person orbit camera input. Empty = found automatically.")]
public ThirdPersonOrbitInput cameraInput;
[Tooltip("Mesh painter. Empty = found automatically.")]
public MeshPainter painter;
[Tooltip("Free-fly spectator camera. Empty = found automatically. Absent = Free Cam is left out of the cycle.")]
public FreeCamController freeCam;
[Tooltip("First-person camera. Empty = found automatically. Absent = First Person is left out of the cycle.")]
public FirstPersonController firstPerson;
[Header("Switching")]
[Tooltip("Key that cycles to the next mode.")]
#if ENABLE_INPUT_SYSTEM
public Key switchKey = Key.Tab;
#else
public KeyCode switchKey = KeyCode.Tab;
#endif
[Tooltip("Mode active at startup (0 = Player Control).")]
public int startModeIndex = 0;
[Header("Hider radar ping")]
[Tooltip("Key a HIDER presses to manually ping itself on every hunter's radar during Seek - the same blip " +
"as the periodic sweep, on demand. Ignored for hunters, outside Seek, and in Free Cam (whose fly " +
"controls already use this key).")]
#if ENABLE_INPUT_SYSTEM
public Key pingKey = Key.E;
#else
public KeyCode pingKey = KeyCode.E;
#endif
[Header("Player collision")]
[Tooltip("ON = players physically block each other (default). OFF = the local player passes through every " +
"other player - their CharacterController stops colliding with other players' body colliders. " +
"Only affects player-vs-player; environment collision is unchanged. Can be toggled live in Play mode.")]
[SerializeField] private bool playersCollide = true;
/// <summary>Whether players physically block each other. Setting it re-applies on the next frame.</summary>
public bool PlayersCollide
{
get => playersCollide;
set { playersCollide = value; _playerCollisionDirty = true; }
}
public PlayerCharacterController Player => player;
public ThirdPersonOrbitInput CameraInput => cameraInput;
public MeshPainter Painter => painter;
public FreeCamController FreeCam => freeCam;
public FirstPersonController FirstPerson => firstPerson;
/// <summary>Raised after a mode switch finishes (the new mode's Enter has already run).
/// Argument = the now-active mode. Used by UI (e.g. the paint HUD) to follow the mode.</summary>
public event System.Action<GameMode> ModeChanged;
/// <summary>Raised when the painter the HUD should edit changes - i.e. when the local
/// networked avatar spawns and <see cref="BindLocalPlayer"/> binds its per-avatar painter.
/// With spawn-on-connect there is no painter at scene start, so the paint HUD follows this
/// to (re)bind its widgets to the live painter once it exists.</summary>
public event System.Action<MeshPainter> PainterChanged;
private readonly List<GameMode> _modes = new List<GameMode>();
private int _activeIndex = -1;
private bool _paused;
private int _resumeIndex = -1;
private bool _loadFrozen; // true while the pre-match Loading barrier is holding the local player still
private PlayerRole? _localRole; // bound local avatar's role (null = pre-spawn / spectator / unscoped lobby)
// Player-collision reconciler state (see ReconcilePlayerCollision). Non-serialized: reset each play session.
private bool _playerCollisionDirty = true; // force a re-apply (startup, toggle flip, inspector edit)
private CharacterController _localCapsule; // the local player's capsule, cached to detect a respawn swap
private void OnValidate() => _playerCollisionDirty = true; // an inspector toggle takes effect next frame
/// <summary>The currently active mode (null before startup).</summary>
public GameMode ActiveMode =>
(_activeIndex >= 0 && _activeIndex < _modes.Count) ? _modes[_activeIndex] : null;
private void Awake()
{
if (!player) player = FindFirstObjectByType<PlayerCharacterController>();
if (!cameraInput) cameraInput = FindFirstObjectByType<ThirdPersonOrbitInput>();
if (!painter) painter = FindFirstObjectByType<MeshPainter>();
// Include inactive so a freecam rig that starts disabled is still found and wired.
if (!freeCam) freeCam = FindFirstObjectByType<FreeCamController>(FindObjectsInactive.Include);
if (!firstPerson) firstPerson = FindFirstObjectByType<FirstPersonController>(FindObjectsInactive.Include);
BuildModes();
}
private void Start()
{
// Go live only when this scene already holds a player to control (a scene-placed avatar). In the
// networked Main scene the avatar spawns on connect, so the manager stays inert - no camera control,
// no mode switching - until BindLocalPlayer promotes it once the lobby avatar exists. Without this,
// the pre-spawn menu already lets you orbit the camera and Tab-cycle modes with no player.
if (player && _modes.Count > 0)
SwitchTo(Mathf.Clamp(startModeIndex, 0, _modes.Count - 1));
else
EnterNoPlayerState();
}
/// <summary>Registers the modes for the current context. Without a role (no networked avatar yet,
/// or a non-networked scene) the full set is built from whichever rigs are present. With a role the
/// set is scoped to that side and ordered so index 0 is its intended start mode. Add new modes here.</summary>
private void BuildModes() => BuildModes(null);
private void BuildModes(PlayerRole? role)
{
_modes.Clear();
switch (role)
{
case PlayerRole.Hunter:
if (firstPerson) _modes.Add(new FirstPersonMode());
_modes.Add(new PaintMode());
break;
case PlayerRole.Hider:
if (player) _modes.Add(new PlayerControlMode());
_modes.Add(new PaintMode());
if (freeCam) _modes.Add(new FreeCamMode());
break;
default:
// No role: legacy full set, gated on whichever rigs exist (a player-less pre-spawn
// stays in Paint rather than a dead frozen Player Control).
if (player) _modes.Add(new PlayerControlMode());
_modes.Add(new PaintMode());
if (freeCam) _modes.Add(new FreeCamMode());
if (firstPerson) _modes.Add(new FirstPersonMode());
break;
}
foreach (var m in _modes)
m.Bind(this);
}
/// <summary>Spectator mode set for a mid-match joiner: free-fly camera only (no player control, no
/// paint). They can fly around and watch, but not play, until the host ends the match (then they
/// respawn as a neutral lobby Player). Falls back to nothing if the scene has no free-cam rig.</summary>
private void BuildSpectatorModes()
{
_modes.Clear();
if (freeCam) _modes.Add(new FreeCamMode());
foreach (var m in _modes)
m.Bind(this);
}
/// <summary>
/// Binds a mid-match spectator. The spectator object is empty (no body/painter to bind), so just clear
/// the player/painter and switch the cycle to free-cam-only. The free-cam rig is a separate persistent
/// scene object that flies off Camera.main, so it needs nothing from the spectator. Called from
/// <see cref="SpectatorSetup"/> on the owning client.
/// </summary>
public void BindSpectator()
{
_paused = false;
_resumeIndex = -1;
ClearPlayerBindings();
TearDownActiveMode();
BuildSpectatorModes();
SwitchTo(0);
}
/// <summary>Drops the player/painter bindings and notifies painter-following UI.</summary>
private void ClearPlayerBindings()
{
player = null;
painter = null;
_localRole = null; // spectator / released: no hider ping
PainterChanged?.Invoke(null);
}
/// <summary>Exits the active mode and marks no mode active.</summary>
private void TearDownActiveMode()
{
ActiveMode?.Exit();
_activeIndex = -1;
}
/// <summary>
/// Binds the scene singletons (this manager, the orbit/first-person cameras, the painter) to the
/// locally-owned networked player after it spawns, then enters Player Control. Called from
/// <see cref="NetworkPlayerSetup"/> on the owning client. Before this runs the scene has no player,
/// so the cycle sits in a player-less mode (Paint); this promotes it once the avatar exists.
/// </summary>
public void BindLocalPlayer(PlayerCharacterController localPlayer)
{
if (!localPlayer) return;
// A fresh bind is a definitive state reset - drop any modal pause so the new avatar starts live.
_paused = false;
_resumeIndex = -1;
var setup = localPlayer.GetComponent<NetworkPlayerSetup>();
player = localPlayer;
// Re-point UNCONDITIONALLY: on a lobby->match respawn the old painter is Destroy-pending (still
// non-null), so a `if (!painter)` guard would keep the stale reference and the new avatar's
// painter would never be mode-toggled.
painter = localPlayer.GetComponentInChildren<MeshPainter>(true);
PainterChanged?.Invoke(painter);
Transform camTarget = localPlayer.transform.Find("CameraTarget");
if (cameraInput)
{
var vcam = cameraInput.GetComponent<CinemachineCamera>();
if (vcam)
{
vcam.Follow = camTarget;
vcam.LookAt = camTarget;
// Follow (and its lossyScale) is live now - start at this avatar's scaled default zoom
// instead of inheriting the previous avatar's radius.
cameraInput.ResetZoom();
}
}
if (firstPerson)
firstPerson.SetPlayer(localPlayer);
// Tear down the pre-spawn (player-less) mode and rebuild scoped to this avatar's role.
TearDownActiveMode();
// Lobby avatar -> full set; match variant -> its role's modes. Scope is baked per prefab
// variant, so it follows the spawned avatar with no replicated-phase timing race.
if (setup && setup.ScopedModes)
{
_localRole = setup.Role;
BuildModes(setup.Role);
}
else
{
_localRole = null; // unscoped lobby avatar: no hider ping
BuildModes(null);
}
// Index 0 is each set's intended start mode.
SwitchTo(0);
}
/// <summary>
/// Drops back to a player-less state when the local avatar is gone (disconnect / server shutdown
/// returns the session to the empty Main scene). Tears down the active mode so any FreeCam/First-Person
/// camera takeover is undone (which unlocks the cursor), clears the mode cycle, and - crucially - parks
/// the persistent orbit input in Disabled: it otherwise re-locks the cursor every frame while
/// AlwaysActive, so a one-off unlock would be reverted next frame and the OS cursor would stay captured
/// with no avatar to control. A reconnect's <see cref="BindLocalPlayer"/> restores everything.
/// </summary>
public void ReleaseToNoPlayer()
{
TearDownActiveMode();
_modes.Clear();
ClearPlayerBindings();
EnterNoPlayerState();
}
/// <summary>
/// Puts the manager in the inert "no local player" state: no active mode, the persistent orbit input
/// parked in Disabled (it otherwise re-locks the cursor every frame while AlwaysActive, so a one-off
/// unlock would be reverted next frame) and the cursor freed. Entered at startup in a networked scene
/// before the lobby avatar spawns, and again after it is gone (see <see cref="ReleaseToNoPlayer"/>).
/// <see cref="BindLocalPlayer"/> / <see cref="BindSpectator"/> promote out of it. With no active mode
/// (_activeIndex &lt; 0) Update ignores the switch key, so Tab cannot bootstrap a mode from here.
/// </summary>
private void EnterNoPlayerState()
{
_paused = false;
_resumeIndex = -1;
_activeIndex = -1;
if (cameraInput)
cameraInput.LookMode = ThirdPersonOrbitInput.OrbitLookMode.Disabled;
// Belt-and-braces explicit release (covers the orbit input being absent/disabled).
InputUtil.SetCursorLocked(false);
// The cycle is inert (no SwitchTo runs), so notify mode-following UI explicitly - otherwise the
// paint HUD (hides only via ModeChanged) would stay open after a shutdown during PaintMode.
ModeChanged?.Invoke(null);
}
/// <summary>
/// Pauses/resumes local gameplay for a full-screen modal overlay (the Esc session panel). Suppresses
/// ALL local input and frees the cursor WITHOUT tearing down the mode cycle, so resuming re-enters
/// the exact mode that was active. Deliberately never Exits the active mode: the FP/free-cam vcam
/// keeps its priority, so the view stays frozen instead of blending back to the orbit camera (no
/// jump on open), and the resumed mode's snap-to-current-view is a no-op (no jump on close).
/// </summary>
public void SetPaused(bool paused)
{
if (paused == _paused) return;
_paused = paused;
if (paused)
{
_resumeIndex = _activeIndex;
_activeIndex = -1; // bookkeeping: no live mode while paused (Tick won't run)
// Freeze every input source without touching vcam priorities: dropping the FP/freecam
// `enabled` freezes their look in place; a Disabled orbit look-mode stops the per-frame
// cursor re-grab. At most one rig is ever enabled, so disabling both is safe.
if (player) player.ControlEnabled = false;
if (painter) painter.PaintingEnabled = false;
if (firstPerson) firstPerson.enabled = false;
if (freeCam) freeCam.enabled = false;
if (cameraInput)
{
cameraInput.enabled = true;
cameraInput.LookMode = ThirdPersonOrbitInput.OrbitLookMode.Disabled;
}
InputUtil.SetCursorLocked(false);
ModeChanged?.Invoke(null); // hide mode-following UI (the paint HUD) beneath the overlay
}
else
{
int resume = _resumeIndex;
_resumeIndex = -1;
if (resume >= 0 && resume < _modes.Count)
{
// Re-Enter the SAME mode (never Exited): its sync-to-current-view is a no-op -> no jump.
_activeIndex = resume;
ActiveMode.Enter();
ModeChanged?.Invoke(ActiveMode);
}
else
ModeChanged?.Invoke(ActiveMode);
}
}
private void Update()
{
// Independent of mode/pause: keep player-vs-player collision matching the toggle every frame.
ReconcilePlayerCollision();
if (_paused) return;
if (_modes.Count == 0) return;
// No active mode = the inert no-player state (pre-lobby, or after ReleaseToNoPlayer). Ignore the
// switch key and Tick so Tab can't bootstrap a mode and no camera rig is driven until a bind.
if (_activeIndex < 0) return;
// Pre-match loading barrier: hold the local player frozen (no movement, painting or mode switching)
// until every client has finished loading and the Hide phase begins. Re-asserted each frame so nothing
// sneaks input in; on release the active mode is re-entered to restore its intended control state
// without a camera jump (exactly like SetPaused's resume - the mode was never Exited).
if (MovementGated())
{
if (player)
{
player.ControlEnabled = false;
player.GravityEnabled = false; // hover in place; don't settle to the floor while loading
}
if (painter) painter.PaintingEnabled = false;
// Hide the own body so the frozen avatar doesn't hang in the half-loaded world. Re-asserted every
// frame (not once) because a lobby->match respawn rebinds `player` mid-load, so the fresh avatar
// must be hidden too.
SetOwnerBodyHidden(true);
_loadFrozen = true;
return;
}
if (_loadFrozen)
{
_loadFrozen = false;
if (player) player.GravityEnabled = true; // Enter() doesn't touch gravity, so restore it here
SetOwnerBodyHidden(false); // show the body, then let Enter() re-hide it if first-person
ActiveMode?.Enter();
}
// Resolution (the reveal window) is watch-only: force out of Paint and keep the switch key from
// re-entering. No restore needed - the end-of-match respawn rebuilds the cycle at index 0.
bool suppressPaint = PaintSuppressed();
if (suppressPaint && ActiveMode is PaintMode)
{
int fallback = FirstNonPaintFrom(0);
if (fallback >= 0) SwitchTo(fallback);
else if (painter) painter.PaintingEnabled = false; // degenerate paint-only set: at least stop painting
}
if (InputUtil.GameplayKeyPressed(switchKey))
{
int next = (_activeIndex + 1) % _modes.Count;
if (suppressPaint && _modes[next] is PaintMode)
{
int skip = FirstNonPaintFrom(next);
if (skip >= 0) next = skip;
}
SwitchTo(next);
}
// A hider manually pings itself onto every hunter's radar (same blip as the periodic sweep), on demand.
// Excluded in Free Cam whose fly controls already use this key; the phase/role gate lives in MatchManager
// (RequestManualPing no-ops outside Seek / for a found hider), so a stray press is harmless.
if (_localRole == PlayerRole.Hider && !(ActiveMode is FreeCamMode) &&
InputUtil.GameplayKeyPressed(pingKey) && MatchManager.Instance)
MatchManager.Instance.RequestManualPing();
ActiveMode?.Tick();
}
/// <summary>True while the local match is in its resolution (reveal) phase, during which painting is
/// disabled for the local player regardless of role.</summary>
private bool PaintSuppressed()
{
var match = MatchManager.Instance;
return match && match.MatchActive &&
match.LocalSubPhase == MatchManager.MatchSubPhase.Resolution;
}
/// <summary>True while the local match is in its pre-Hide LOADING barrier, during which the local player is
/// frozen (no movement, painting or mode switching) until every client has finished loading.</summary>
private bool MovementGated()
{
var match = MatchManager.Instance;
return match && match.MatchActive &&
match.LocalSubPhase == MatchManager.MatchSubPhase.Loading;
}
// Keeps player-vs-player collision in sync with `playersCollide`. Only the LOCAL owner's CharacterController
// actively depenetrates (remote replicas run with their controller disabled), and it collides with the other
// avatars' body MeshColliders (and conversion statues, which carry the same runtime paint collider) - so
// making the local capsule ignore those colliders is a complete, per-machine way to let the player pass
// through both. Environment collision is untouched.
//
// While OFF this re-asserts every frame (n = a handful of avatars, so it is cheap) because Physics.IgnoreCollision
// is fragile exactly here: its state resets whenever a collider is disabled/re-enabled (teleports toggle the
// capsule) and a freshly-spawned avatar's MeshCollider only appears a frame after spawn. Re-applying each frame
// sidesteps all of that. While ON it does one restoring pass on a change, then stays idle (collision is the default).
private void ReconcilePlayerCollision()
{
var capsule = player ? player.GetComponent<CharacterController>() : null;
bool changed = _playerCollisionDirty || capsule != _localCapsule;
_playerCollisionDirty = false;
_localCapsule = capsule;
if (playersCollide)
{
// Collisions on: only act on a transition (toggle flip / new capsule) to restore the pairs we ignored.
if (changed) ApplyPlayerCollisionIgnore(capsule, false);
return;
}
// Collisions off: re-assert the ignore against every current avatar (see the fragility note above).
ApplyPlayerCollisionIgnore(capsule, true);
}
// Ignores (or restores) collision between the local capsule and every OTHER avatar's body collider,
// plus every conversion statue (its own paint MeshCollider - otherwise the local player still bumps into
// statues while the toggle is off, since statues aren't NetworkPlayerSetup avatars).
private void ApplyPlayerCollisionIgnore(CharacterController capsule, bool ignore)
{
if (!capsule) return; // no local player (pre-spawn / spectator / found) - nothing to gate
var avatars = NetworkPlayerSetup.Active;
for (int i = 0; i < avatars.Count; i++)
{
var avatar = avatars[i];
if (!avatar || avatar.IsOwner) continue; // skip the local player's own avatar
var col = avatar.BodyCollider;
if (col && col.enabled) Physics.IgnoreCollision(capsule, col, ignore);
}
var statues = MatchStatue.Active;
for (int i = 0; i < statues.Count; i++)
{
var statue = statues[i];
if (!statue) continue;
var col = statue.BodyCollider;
if (col && col.enabled) Physics.IgnoreCollision(capsule, col, ignore);
}
}
// Cached body/fur renderers of the currently bound local avatar, re-resolved only when `player` changes
// (a lobby->match respawn rebinds mid-load), so the per-frame Loading hide doesn't walk the hierarchy each tick.
private PlayerCharacterController _bodyHideOwner;
private SkinnedMeshRenderer[] _bodyHideRenderers;
private FurShellRenderer[] _bodyHideFur;
/// <summary>Hides/shows the LOCAL player's own body (skinned mesh + fur) during the pre-match loading freeze,
/// so the owner doesn't watch its frozen avatar hang in the half-loaded world. Local-only (renderer.enabled
/// is not replicated, so remotes are unaffected - their view is driven by <see cref="NetworkPlayerSetup"/>).
/// On show the freeze release re-enters the active mode, so first-person re-applies its own-body self-hide.</summary>
private void SetOwnerBodyHidden(bool hidden)
{
if (player != _bodyHideOwner)
{
_bodyHideOwner = player;
_bodyHideRenderers = player ? player.GetComponentsInChildren<SkinnedMeshRenderer>(true) : null;
_bodyHideFur = player ? player.GetComponentsInChildren<FurShellRenderer>(true) : null;
}
if (_bodyHideRenderers != null)
foreach (var r in _bodyHideRenderers)
if (r) r.enabled = !hidden;
// Fur draws via a GPU-instanced camera hook, not a Renderer, so the skinned-mesh toggle misses it;
// disabling the component unsubscribes that hook (mirrors FirstPersonController.SetMeshHidden).
if (_bodyHideFur != null)
foreach (var f in _bodyHideFur)
if (f) f.enabled = !hidden;
}
/// <summary>First non-Paint mode index at or after <paramref name="start"/> (wrapping once through the
/// cycle); -1 if the set has no non-paint mode (a degenerate paint-only configuration).</summary>
private int FirstNonPaintFrom(int start)
{
for (int step = 0; step < _modes.Count; step++)
{
int i = (start + step) % _modes.Count;
if (!(_modes[i] is PaintMode)) return i;
}
return -1;
}
/// <summary>Activates the mode at <paramref name="index"/> (Exit old, Enter new).</summary>
public void SwitchTo(int index)
{
if (index < 0 || index >= _modes.Count || index == _activeIndex) return;
ActiveMode?.Exit();
_activeIndex = index;
ActiveMode.Enter();
Debug.Log($"[GameModeManager] Mode -> {ActiveMode.DisplayName}", this);
ModeChanged?.Invoke(ActiveMode);
}
}