Files
AppleHillsProduction/Assets/Scripts/Cinematics/CinematicsManager.cs
2025-11-11 10:53:09 +01:00

235 lines
8.3 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;
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;
}
}
}