Files
AppleHillsProduction/Assets/Scripts/Cinematics/CinematicsManager.cs
tschesky 0aa2270e1a Lifecycle System Refactor & Logging Centralization (#56)
## ManagedBehaviour System Refactor

- **Sealed `Awake()`** to prevent override mistakes that break singleton registration
- **Added `OnManagedAwake()`** for early initialization (fires during registration)
- **Renamed lifecycle hook:** `OnManagedAwake()` → `OnManagedStart()` (fires after boot, mirrors Unity's Awake→Start)
- **40 files migrated** to new pattern (2 core, 38 components)
- Eliminated all fragile `private new void Awake()` patterns
- Zero breaking changes - backward compatible

## Centralized Logging System

- **Automatic tagging** via `CallerMemberName` and `CallerFilePath` - logs auto-tagged as `[ClassName][MethodName] message`
- **Unified API:** Single `Logging.Debug/Info/Warning/Error()` replaces custom `LogDebugMessage()` implementations
- **~90 logging call sites** migrated across 10 files
- **10 redundant helper methods** removed
- All logs broadcast via `Logging.OnLogEntryAdded` event for real-time monitoring

## Custom Log Console (Editor Window)

- **Persistent filter popups** for multi-selection (classes, methods, log levels) - windows stay open during selection
- **Search** across class names, methods, and message content
- **Time range filter** with MinMaxSlider
- **Export** filtered logs to timestamped `.txt` files
- **Right-click context menu** for quick filtering and copy actions
- **Visual improvements:** White text, alternating row backgrounds, color-coded log levels
- **Multiple instances** supported for simultaneous system monitoring
- Open via `AppleHills > Custom Log Console`

Co-authored-by: Michal Pikulski <michal@foolhardyhorizons.com>
Co-authored-by: Michal Pikulski <michal.a.pikulski@gmail.com>
Reviewed-on: #56
2025-11-11 08:48:29 +00:00

237 lines
8.4 KiB
C#

using System.Collections.Generic;
using Core;
using Core.Lifecycle;
using UI;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.Playables;
using UnityEngine.UI;
using UI.Core;
namespace Cinematics
{
/// <summary>
/// Handles loading, playing and unloading cinematics
/// </summary>
public class CinematicsManager : ManagedBehaviour
{
public event System.Action OnCinematicStarted;
public event System.Action OnCinematicStopped;
private static CinematicsManager _instance;
private Image _cinematicSprites;
public GameObject cinematicSpritesGameObject;
private bool _isCinematicPlaying = false;
public bool IsCinematicPlaying => _isCinematicPlaying;
public GameObject cinematicBackground;
public DivingGameOverScreen divingGameOverScreen;
// Dictionary to track addressable handles by PlayableDirector
private Dictionary<PlayableDirector, AsyncOperationHandle<PlayableAsset>> _addressableHandles
= new Dictionary<PlayableDirector, AsyncOperationHandle<PlayableAsset>>();
/// <summary>
/// Singleton instance of the CinematicsManager. No longer creates an instance if one doesn't exist.
/// </summary>
public static CinematicsManager Instance => _instance;
public PlayableDirector playableDirector;
public override int ManagedAwakePriority => 170; // Cinematic systems
internal override void OnManagedAwake()
{
// Set instance immediately (early initialization)
_instance = this;
}
internal override void OnManagedStart()
{
Logging.Debug("[CinematicsManager] Initialized");
}
private void OnEnable()
{
// Subscribe to application quit event to ensure cleanup
Application.quitting += OnApplicationQuit;
}
private void OnDisable()
{
// Unsubscribe from application quit event
Application.quitting -= OnApplicationQuit;
// Clean up any remaining addressable handles when disabled
ReleaseAllHandles();
}
private void OnApplicationQuit()
{
ReleaseAllHandles();
}
/// <summary>
/// Initializes required components for the CinematicsManager
/// </summary>
private void InitializeComponents()
{
// Initialize PlayableDirector if not set
if (playableDirector == null)
{
playableDirector = PlayerHudManager.Instance.playableDirector;
// If still null, try to add the component
if (playableDirector == null)
{
Logging.Debug("[CinematicsManager] Could not find Playable Director on the PlayerHudManager");
}
}
// Initialize _cinematicSprites if not set
if (_cinematicSprites == null)
{
// First try to find in children in the PlayerHud
_cinematicSprites = PlayerHudManager.Instance.cinematicSprites;
// If still null, return error
if (_cinematicSprites == null)
{
Logging.Warning("[CinematicsManager] No Image found for cinematics display. Cinematics may not display correctly.");
}
}
cinematicSpritesGameObject = PlayerHudManager.Instance.currentCinematicPlayer;
cinematicBackground = PlayerHudManager.Instance.CinematicBackground;
}
/// <summary>
/// Plays a cinematic from an object reference and returns the PlayableDirector playing the timeline
/// </summary>
public PlayableDirector PlayCinematic(PlayableAsset assetToPlay)
{
// Ensure components are initialized before playing
InitializeComponents();
if (_cinematicSprites != null)
{
_cinematicSprites.enabled = true;
cinematicSpritesGameObject.SetActive(true);
}
cinematicBackground.SetActive(true);
playableDirector.stopped += OnPlayableDirectorStopped;
playableDirector.Play(assetToPlay);
Logging.Debug("Playing cinematic " + assetToPlay.name);
_isCinematicPlaying = true;
OnCinematicStarted?.Invoke();
return playableDirector;
}
void OnPlayableDirectorStopped(PlayableDirector director)
{
_cinematicSprites.enabled = false;
cinematicSpritesGameObject.SetActive(false);
Logging.Debug("Cinematic stopped!");
_isCinematicPlaying = false;
OnCinematicStopped?.Invoke();
// Release the addressable handle associated with this director
ReleaseAddressableHandle(director);
ShowCinematicBackground(false);
}
/// <summary>
/// Loads a playable from an asset path and plays it as a cinematic
/// </summary>
public PlayableDirector LoadAndPlayCinematic(string key, bool playPortraitMode)
{
InitializeComponents();
// Load the asset via addressables
var handle = Addressables.LoadAssetAsync<PlayableAsset>(key);
var result = handle.WaitForCompletion();
// Store the handle for later release
_addressableHandles[playableDirector] = handle;
Logging.Debug($"[CinematicsManager] Loaded addressable cinematic: {key}");
PlayerHudManager.Instance.SetPortraitMode(playPortraitMode);
return PlayCinematic(result);
}
/// <summary>
/// Skips the currently playing cinematic if one is active
/// </summary>
public void SkipCurrentCinematic()
{
if (playableDirector != null && playableDirector.state == PlayState.Playing)
{
Logging.Debug("Skipping current cinematic");
playableDirector.Stop();
}
}
/// <summary>
/// Releases the addressable handle associated with a specific PlayableDirector
/// </summary>
private void ReleaseAddressableHandle(PlayableDirector director)
{
if (_addressableHandles.TryGetValue(director, out var handle))
{
Logging.Debug($"[CinematicsManager] Releasing addressable handle for cinematic");
Addressables.Release(handle);
_addressableHandles.Remove(director);
}
}
/// <summary>
/// Releases all active addressable handles
/// </summary>
private void ReleaseAllHandles()
{
foreach (var handle in _addressableHandles.Values)
{
if (handle.IsValid())
{
Addressables.Release(handle);
}
}
_addressableHandles.Clear();
}
public void ShowCinematicBackground(bool shouldBeActive)
{
cinematicBackground.SetActive(shouldBeActive);
}
public void ShowGameOverScreen()
{
// Diagnostic: log time and call stack to track when/why game over is triggered
Logging.Debug($"[CinematicsManager] ShowGameOverScreen called at time={Time.time:F2}");
if (divingGameOverScreen != null && UIPageController.Instance != null)
{
UIPageController.Instance.PushPage(divingGameOverScreen);
}
else if (divingGameOverScreen != null)
{
// Fallback if UIPageController is not available
divingGameOverScreen.gameObject.SetActive(true);
Logging.Warning("[CinematicsManager] UIPageController not found, falling back to simple activation.");
}
else
{
Logging.Warning("[CinematicsManager] DivingGameOverScreen reference is not set!");
}
}
public void ChangeCinematicBackgroundColour(Color clr)
{
PlayerHudManager.Instance.cinematicBackgroundSprites.color = clr;
}
}
}