| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213 |
- using System;
- using System.Collections;
- using DevilLink2.Loading;
- using System.IO;
- using DevilLink2.Persistence;
- using DevilLink2.Presentation;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- using UnityEngine.UI;
- namespace DevilLink2.UI
- {
- public static class MainUIInstaller
- {
- #if UNITY_EDITOR
- [UnityEditor.MenuItem("Tools/Devil Link 2/Test Platform Open")]
- private static void TestPlatformOpen()
- {
- AppRuntimesEvents.RaisePlatformOpen();
- Debug.Log("[Test] 模拟平台打开事件");
- }
- #endif
- public const string ValidationSessionKey = "DevilLink2.Task08A.PlayPending";
- // Tests/editor acceptance can inject an isolated player without touching real player saves.
- public static Func<SavedPlayer> PlayerLoaderOverride;
- private const string MainScenePath = "Assets/DevilLink2/Scenes/Main.unity";
- private static readonly System.Collections.Generic.Dictionary<int, int> preparing = new System.Collections.Generic.Dictionary<int, int>();
- [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
- private static void ResetStartupHooks()
- {
- // Also runs when Domain Reload is disabled. Do not retain old scene IDs or delegates.
- SceneManager.sceneLoaded -= OnSceneLoaded;
- SceneManager.sceneUnloaded -= OnSceneUnloaded;
- AppRuntimesEvents.OnPlatformOpen -= OnPlatformOpen;
- preparing.Clear();
- }
- [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
- [HotPatch.HotPatchInitializer(-100)]
- [UnityEngine.Scripting.Preserve]
- private static void RegisterStartupHooks()
- {
- // The hot-patch entry registers before Main is loaded in a Player as well.
- SceneManager.sceneLoaded -= OnSceneLoaded;
- SceneManager.sceneLoaded += OnSceneLoaded;
- SceneManager.sceneUnloaded -= OnSceneUnloaded;
- SceneManager.sceneUnloaded += OnSceneUnloaded;
- AppRuntimesEvents.OnPlatformOpen -= OnPlatformOpen;
- AppRuntimesEvents.OnPlatformOpen += OnPlatformOpen;
- }
- [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
- private static void InstallMain()
- {
- // Retain both direct-Main startup and EditorLocalGameResources' explicit entry.
- RegisterStartupHooks();
- for (int i = 0; i < SceneManager.sceneCount; i++) InstallScene(SceneManager.GetSceneAt(i));
- }
- private static void OnSceneLoaded(Scene scene, LoadSceneMode mode) => InstallScene(scene);
- private static void InstallScene(Scene scene)
- {
- if (!scene.IsValid() || !scene.isLoaded || scene.path != MainScenePath) return;
- BoardDemoBootstrap bootstrap = null;
- int count = 0;
- foreach (var root in scene.GetRootGameObjects())
- foreach (var candidate in root.GetComponentsInChildren<BoardDemoBootstrap>(true))
- {
- // sceneLoaded precedes Start, even while Launch is still the active scene.
- candidate.ConfigureAutomaticStart(false);
- bootstrap = candidate;
- count++;
- }
- if (count != 1)
- {
- Debug.LogError("Main requires exactly one BoardDemoBootstrap; found " + count + ".");
- return;
- }
- bootstrap.ConfigureAutomaticStart(false);
- BeginStart(bootstrap, false);
- }
- private static void OnSceneUnloaded(Scene scene)
- {
- var stale = new System.Collections.Generic.List<int>();
- foreach (var entry in preparing) if (entry.Value == scene.handle) stale.Add(entry.Key);
- foreach (int id in stale) preparing.Remove(id);
- }
- private static bool HasInitializedUI(BoardDemoBootstrap bootstrap)
- {
- var manager = bootstrap.GetComponentInChildren<UIManager>(true);
- return manager && manager.IsInitialized;
- }
- private static bool HasRecoveryUI(BoardDemoBootstrap bootstrap)
- {
- var recovery = bootstrap.transform.Find("SafeArea/PortraitFrame/SaveRecovery");
- return recovery && recovery.gameObject.activeSelf;
- }
- private static void OnPlatformOpen()
- {
- Debug.Log("[Main] Platform Open - Mute Audio");
- var audio = AudioManager.Instance;
- if (audio == null) return;
- audio.SetMusicEnabled(false); // 关闭背景音乐
- audio.SetSfxEnabled(false); // 关闭音效
- }
- private static void BeginStart(BoardDemoBootstrap bootstrap, bool memoryOnly)
- {
- if (!bootstrap || !bootstrap.isActiveAndEnabled) return;
- bootstrap.ConfigureAutomaticStart(false);
- if (HasInitializedUI(bootstrap) || HasRecoveryUI(bootstrap)) return;
- int id = bootstrap.GetInstanceID();
- if (preparing.ContainsKey(id)) return;
- preparing.Add(id, bootstrap.gameObject.scene.handle);
- try { bootstrap.StartCoroutine(PrepareStart(bootstrap, memoryOnly, id)); }
- catch { preparing.Remove(id); throw; }
- }
- private static IEnumerator PrepareStart(BoardDemoBootstrap bootstrap, bool memoryOnly, int id)
- {
- GameLoadingView loading = null;
- bool success = false;
- try
- {
- loading = GameLoadingView.Create(bootstrap.transform);
- loading.InitializationStarted();
- loading.Indeterminate(memoryOnly ? "Preparing temporary session" : "Reading local save and initializing interface");
- yield return null; // Present once before synchronous initialization; no timed artificial delay.
- if (!bootstrap) yield break;
- success = TryStart(bootstrap, memoryOnly);
- }
- finally
- {
- if (loading) { if (success) loading.Close(); else loading.DismissForRecovery(); }
- preparing.Remove(id);
- } // Success reveals Start; failure reveals the existing recovery panel.
- }
- private static bool TryStart(BoardDemoBootstrap bootstrap, bool memoryOnly)
- {
- if (HasInitializedUI(bootstrap)) return true;
- SavedPlayer player = null;
- try
- {
- #if UNITY_EDITOR
- if (UnityEditor.SessionState.GetBool(ValidationSessionKey, false) && PlayerLoaderOverride == null)
- throw new InvalidOperationException("Isolated Play Mode test player has not been installed; refusing real player storage.");
- #endif
- bool atomic = Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor;
- player = memoryOnly ? SavedPlayer.CreateMemoryOnly() : PlayerLoaderOverride != null ? PlayerLoaderOverride() : new SavedPlayer(new LocalSaveService(
- new FileSaveStorage(Path.Combine(Application.persistentDataPath, "DevilLink2"), atomic)));
- var frame = bootstrap.transform.Find("SafeArea/PortraitFrame") as RectTransform;
- var view = bootstrap.GetComponentInChildren<BoardView>(true);
- if (!frame || !view) throw new InvalidOperationException("Existing Main Canvas/board structure is incomplete.");
- var title = frame.Find("Title")?.GetComponent<Text>();
- var audio = DevilLink2.Presentation.AudioManager.Ensure(bootstrap.gameObject);
- audio.SetMusic(MusicTrack.Lobby);
- var manager = UIBuilder.Build(frame, bootstrap, view, title);
- manager.Initialize(player, bootstrap, true);
- manager.Settings.BindAudio(audio);
- var recovery = manager.GetComponent<SaveRecoveryController>();
- if (!recovery) recovery = manager.gameObject.AddComponent<SaveRecoveryController>();
- recovery.Bind(player, frame);
- return true;
- }
- catch (Exception error) when (error is IOException || error is UnauthorizedAccessException ||
- error is UnsupportedSaveVersionException || error is SaveFormatException || error is System.Security.SecurityException)
- {
- player?.Dispose();
- ShowRecovery(bootstrap, error);
- }
- catch (Exception error)
- { player?.Dispose(); Debug.LogError("DevilLink2 UI startup failed: " + error); ShowRecovery(bootstrap, error, false); }
- return false;
- }
- private static void ShowRecovery(BoardDemoBootstrap bootstrap, Exception error, bool storageFailure = true)
- {
- var frame = bootstrap.transform.Find("SafeArea/PortraitFrame") as RectTransform;
- if (!frame) { Debug.LogError("Save recovery requires the existing PortraitFrame: " + error); return; }
- Debug.LogWarning("DevilLink2 save unavailable: " + error.Message);
- var overlay = UIBuilder.Rect("SaveRecovery", frame, 0, 0, 430, 932);
- var shade = overlay.gameObject.AddComponent<Image>(); shade.color = new Color(.04f, .015f, .07f, .96f);
- var card = UIBuilder.Fill("RecoveryCard", overlay, UIBuilder.Hex("291333"), UIBuilder.Hex("150D20"), 35, 280, 360, 360, 18);
- bool future = error is UnsupportedSaveVersionException;
- UIBuilder.Label("Heading", card.transform, !storageFailure ? "INITIALIZATION FAILED" : future ? "SAVE VERSION INCOMPATIBLE" : "SAVE UNAVAILABLE", 19, UIBuilder.Gold, 16, 18, 328, 50);
- UIBuilder.Label("Message", card.transform, !storageFailure ? "The game could not finish initialization. Please retry or exit. No loading percentage is being simulated." : future ?
- "This save needs a newer game version. Your original save and backup will not be overwritten. Retry, exit, or play temporarily without saving." :
- "Your save could not be accessed. Retry when storage is available, or play temporarily. Temporary progress will not be saved and your disk saves will not be changed.", 14, UIBuilder.LightGold, 20, 76, 320, 120);
- AddRecoveryButton(card.transform, "RETRY", 208, () => { overlay.gameObject.SetActive(false); UnityEngine.Object.Destroy(overlay.gameObject); BeginStart(bootstrap, false); });
- if (storageFailure) AddRecoveryButton(card.transform, "PLAY WITHOUT SAVING", 254, () => { overlay.gameObject.SetActive(false); UnityEngine.Object.Destroy(overlay.gameObject); BeginStart(bootstrap, true); });
- AddRecoveryButton(card.transform, "EXIT", 300, () =>
- {
- #if UNITY_EDITOR
- UnityEditor.EditorApplication.isPlaying = false;
- #else
- Application.Quit();
- #endif
- });
- overlay.SetAsLastSibling();
- }
- private static void AddRecoveryButton(Transform parent, string caption, float y, UnityEngine.Events.UnityAction action)
- {
- var button = UIBuilder.Button(caption, parent, caption, 36, y, 288, 40, UIBuilder.Hex("382044"), UIBuilder.Hex("21122F"), 14);
- button.transition = Selectable.Transition.None;
- button.GetComponentInChildren<Text>().color = UIBuilder.LightGold;
- button.onClick.AddListener(action);
- }
- }
- }
|