GameLoadingView.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using System;
  2. using System.Reflection;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. namespace DevilLink2.Loading
  6. {
  7. // Shared presentation only: no player, session, scene loader or persistence ownership.
  8. public sealed class GameLoadingView : MonoBehaviour
  9. {
  10. private Text heading, status, percent;
  11. private Button retryButton;
  12. private Action retry;
  13. private Image energy, vortex, fillGlow, logoSpark, loadingArt;
  14. private const float EnergyWidth = 280.48f, EnergyHeight = 30.14f;
  15. private static int activeViews, attempt;
  16. private static double introDeadline, firstRenderAt;
  17. private static bool introCompleted, initializing;
  18. private static float sharedVisualFill;
  19. private bool presentationReady, closeRequested;
  20. private const double MinimumIntroSeconds=.9;
  21. private void Awake()
  22. {
  23. if(activeViews++==0){introDeadline=firstRenderAt=-1;introCompleted=initializing=false;attempt=0;sharedVisualFill=0;}
  24. Canvas.willRenderCanvases+=FirstRender;
  25. }
  26. private void FirstRender()
  27. {
  28. if(!presentationReady || !isActiveAndEnabled)return;
  29. if(firstRenderAt<0){firstRenderAt=Time.realtimeSinceStartupAsDouble;introDeadline=firstRenderAt+MinimumIntroSeconds;Trace("LoadingShown");}
  30. Canvas.willRenderCanvases-=FirstRender;
  31. }
  32. private void OnDestroy(){Canvas.willRenderCanvases-=FirstRender;activeViews=Mathf.Max(0,activeViews-1);}
  33. public float IntroRemaining => firstRenderAt<0 ? (float)MinimumIntroSeconds : Mathf.Max(0,(float)(introDeadline-Time.realtimeSinceStartupAsDouble));
  34. [System.Diagnostics.Conditional("UNITY_EDITOR")]
  35. private static void Trace(string point)
  36. {
  37. double now=Time.realtimeSinceStartupAsDouble;
  38. Debug.Log("[LoadingTiming] "+point+" attempt="+attempt+" realtime="+now.ToString("F3",System.Globalization.CultureInfo.InvariantCulture)+
  39. " visible="+(firstRenderAt<0?"not-rendered":(now-firstRenderAt).ToString("F3",System.Globalization.CultureInfo.InvariantCulture)));
  40. }
  41. public void InitializationStarted()
  42. {if(initializing)return;initializing=true;attempt++;Trace("InitializationStarted");}
  43. public void InitializationSucceeded(){if(!initializing)return;initializing=false;Trace("InitializationSucceeded");}
  44. public void InitializationFailed(){if(!initializing)return;initializing=false;Trace("InitializationFailed");}
  45. public void DismissForRecovery(){InitializationFailed();HideNow();}
  46. private RectTransform segment;
  47. private float clock, target, shown;
  48. private bool measurable, failed, completed, stageBased;
  49. private int fullFrame=-1;
  50. private string currentStage="Initializing game";
  51. public static GameLoadingView Create(Transform parent)
  52. {
  53. var go=new GameObject("DevilLink2Loading",typeof(RectTransform),typeof(Canvas),typeof(CanvasScaler),typeof(GraphicRaycaster));
  54. UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(go,parent.gameObject.scene);
  55. var canvas=go.GetComponent<Canvas>();canvas.renderMode=RenderMode.ScreenSpaceOverlay;canvas.sortingOrder=30000;
  56. var scaler=go.GetComponent<CanvasScaler>();scaler.uiScaleMode=CanvasScaler.ScaleMode.ScaleWithScreenSize;scaler.referenceResolution=new Vector2(430,932);scaler.screenMatchMode=CanvasScaler.ScreenMatchMode.Expand;
  57. var v=go.AddComponent<GameLoadingView>();
  58. var safe=Rect("SafeArea",go.transform,0,0,430,932);safe.gameObject.AddComponent<LoadingSafeArea>();
  59. var frame=Rect("PortraitFrame",safe,0,0,430,932);frame.anchorMin=frame.anchorMax=frame.pivot=new Vector2(.5f,.5f);frame.anchoredPosition=Vector2.zero;
  60. frame.gameObject.AddComponent<RectMask2D>();
  61. var fitter=frame.gameObject.AddComponent<AspectRatioFitter>();fitter.aspectMode=AspectRatioFitter.AspectMode.FitInParent;fitter.aspectRatio=430f/932;
  62. var bg=Picture("ReferenceCastleScene",frame,Resources.Load<Sprite>("LoadingArt/ReferenceScene_R3"),0,0,430,932);bg.preserveAspect=false;bg.raycastTarget=true;
  63. // Logo and the solid portal belong to the reference illustration; no duplicate overlays.
  64. v.logoSpark=Picture("LogoGemSpark",frame,Resources.Load<Sprite>("LobbyLogoAnimation/Crystal_Star"),208,145,14,14);
  65. v.vortex=Picture("PortalEnergy",frame,Resources.Load<Sprite>("StartScreenArt/Portal_Vortex"),128,292,174,174);
  66. v.vortex.color=new Color(1,1,1,.30f);
  67. v.heading=TextAt(frame,"LOADING FAILED",23,45,630,340,36);
  68. v.heading.gameObject.SetActive(false);
  69. v.loadingArt=Picture("LoadingArtLetters",frame,Resources.Load<Sprite>("LoadingArt/R4/LoadingLetters"),115,631,200,25.55f);
  70. // Original bar layers share an 871x182 extraction canvas; use the same scale for every ornament.
  71. var bar=Rect("BarRoot",frame,40,680,350,73.13f);
  72. const float scale=350f/871f;
  73. Picture("DeepPurpleSlot",bar,Resources.Load<Sprite>("LoadingArt/R4/Slot"),84*scale,55*scale,EnergyWidth,EnergyHeight);
  74. var mask=Rect("EnergyViewport",bar,84*scale,55*scale,EnergyWidth,EnergyHeight);
  75. var roundedMask=mask.gameObject.AddComponent<Image>();roundedMask.sprite=Resources.Load<Sprite>("LoadingArt/R4/Slot");roundedMask.raycastTarget=false;
  76. mask.gameObject.AddComponent<Mask>().showMaskGraphic=false;
  77. v.energy=Picture("PurpleEnergy",mask,Resources.Load<Sprite>("LoadingArt/R4/Energy"),0,0,EnergyWidth,EnergyHeight);v.energy.preserveAspect=false;v.segment=v.energy.rectTransform;
  78. v.fillGlow=Picture("FillFrontGlow",mask,Resources.Load<Sprite>("LobbyModeAnimation/SoftGlow"),0,-2,18,EnergyHeight+4);
  79. v.fillGlow.color=new Color(1,.35f,1,.45f);v.fillGlow.enabled=false;
  80. v.segment.sizeDelta=new Vector2(EnergyWidth,EnergyHeight);v.segment.anchoredPosition=Vector2.zero;
  81. v.energy.type=Image.Type.Filled;v.energy.fillMethod=Image.FillMethod.Horizontal;v.energy.fillOrigin=0;
  82. v.shown=sharedVisualFill;v.energy.fillAmount=v.shown;
  83. var gold=Picture("GoldOrnament",bar,Resources.Load<Sprite>("LoadingArt/R4/GoldFrame_R5"),0,0,350,73.13f);
  84. Picture("TopCrystal",bar,Resources.Load<Sprite>("LoadingArt/R4/TopCrystal"),360*scale,-18*scale,150*scale,93*scale);
  85. Picture("BottomCrystal",bar,Resources.Load<Sprite>("LoadingArt/R4/BottomCrystal"),371*scale,100*scale,128*scale,80*scale);
  86. gold.transform.SetAsLastSibling(); // Static metal above slot, energy and jewel joins.
  87. v.percent=TextAt(frame,"",16,50,748,330,26);
  88. v.status=TextAt(frame,"Initializing game",13,35,755,360,60);
  89. var retryFace=Picture("Retry",frame,Resources.Load<Sprite>("ProfileProgressCapsule"),143,855,144,44);retryFace.color=new Color(.22f,.08f,.3f);retryFace.raycastTarget=true;
  90. v.retryButton=retryFace.gameObject.AddComponent<Button>();v.retryButton.targetGraphic=retryFace;v.retryButton.transition=Selectable.Transition.None;
  91. TextAt(retryFace.transform,"RETRY",16,0,0,144,44);
  92. v.retryButton.onClick.AddListener(()=>{v.retryButton.gameObject.SetActive(false);var action=v.retry;v.retry=null;action?.Invoke();});v.retryButton.gameObject.SetActive(false);
  93. v.presentationReady=true;
  94. return v;
  95. }
  96. static void TryLogoRig(GameObject owner,Image logo)
  97. {
  98. // Reuse the existing rig only when its runtime assembly is already available.
  99. var screenType=Type.GetType("DevilLink2.UI.UIScreen, DevilLink2");
  100. var rigType=Type.GetType("DevilLink2.UI.LobbyLogoAnimation, DevilLink2");
  101. if(screenType==null||rigType==null||!logo.sprite)return;
  102. try {
  103. var screen=owner.AddComponent(screenType);
  104. screenType.GetMethod("SetVisible").Invoke(screen,new object[]{true});
  105. rigType.GetMethod("Install",new[]{screenType,typeof(Image)}).Invoke(null,new object[]{screen,logo});
  106. } catch(Exception error) { Debug.LogWarning("Loading logo rig unavailable; using original artwork: "+error.Message); }
  107. }
  108. private void SetTitle(bool art,string text="")
  109. { if(loadingArt)loadingArt.enabled=art;heading.gameObject.SetActive(!art && text.Length>0);heading.text=text; }
  110. private void FillCaption()
  111. {
  112. status.text=closeRequested ? "Opening start screen" : measurable || stageBased ? currentStage :
  113. (IntroRemaining>0 ? "Opening effect · " : "Waiting for initialization · ")+currentStage;
  114. }
  115. public void Indeterminate(string stage)
  116. {
  117. if(failed){shown=target=sharedVisualFill=0;stageBased=false;fullFrame=-1;}
  118. failed=completed=measurable=false;SetTitle(true);currentStage=stage;
  119. if(retryButton)retryButton.gameObject.SetActive(false);
  120. energy.enabled=true;energy.type=Image.Type.Filled;energy.fillMethod=Image.FillMethod.Horizontal;energy.fillOrigin=0;
  121. segment.sizeDelta=new Vector2(EnergyWidth,EnergyHeight);segment.anchoredPosition=Vector2.zero;
  122. energy.fillAmount=shown;fillGlow.enabled=false;percent.text="";FillCaption();
  123. status.rectTransform.anchoredPosition=new Vector2(35,-755);status.rectTransform.sizeDelta=new Vector2(360,60);
  124. }
  125. // Discrete completed stages, not downloaded bytes or a fabricated percentage.
  126. public void StageCompleted(bool sceneReady,string stage)
  127. {
  128. Indeterminate(stage);stageBased=true;
  129. target=Mathf.Max(target,sceneReady ? 2f/3f : 1f/3f);FillCaption();
  130. }
  131. public void ShowFailure(string message,Action retryAction=null)
  132. {
  133. InitializationFailed();closeRequested=false;failed=true;completed=false;retry=retryAction;SetTitle(false,"LOADING FAILED");
  134. percent.text="";status.text=message;status.rectTransform.anchoredPosition=new Vector2(35,-773);status.rectTransform.sizeDelta=new Vector2(360,76);
  135. energy.enabled=true;fillGlow.enabled=false;if(retryButton)retryButton.gameObject.SetActive(retryAction!=null);
  136. }
  137. // This API accepts only an actual operation's normalized progress, never pipeline weights.
  138. public void Measured(string stage,float value)
  139. {
  140. if(!measurable)shown=target=0;
  141. failed=completed=false;measurable=true;SetTitle(true);if(retryButton)retryButton.gameObject.SetActive(false);
  142. energy.enabled=true;energy.type=Image.Type.Filled;energy.fillMethod=Image.FillMethod.Horizontal;energy.fillOrigin=0;
  143. segment.sizeDelta=new Vector2(EnergyWidth,EnergyHeight);segment.anchoredPosition=Vector2.zero;
  144. energy.fillAmount=shown;target=Mathf.Max(target,Mathf.Clamp01(value));currentStage=stage;status.text=stage;
  145. }
  146. public void Complete()
  147. {
  148. failed=false;completed=true;measurable=false;shown=target=1;
  149. SetTitle(false,"READY");percent.text="";status.text="Ready";fillGlow.enabled=false;
  150. energy.enabled=true;energy.type=Image.Type.Filled;energy.fillAmount=1;
  151. segment.sizeDelta=new Vector2(EnergyWidth,EnergyHeight);segment.anchoredPosition=Vector2.zero;
  152. if(retryButton)retryButton.gameObject.SetActive(false);
  153. }
  154. private void Update()
  155. {
  156. if(firstRenderAt>=0 && !introCompleted && IntroRemaining<=0){introCompleted=true;Trace("IntroCompleted");if(!failed)FillCaption();}
  157. if(failed)return;
  158. clock+=Time.unscaledDeltaTime;
  159. if(logoSpark)logoSpark.color=new Color(1,.8f,.5f,.15f+.4f*(.5f+.5f*Mathf.Sin(clock*1.4f)));
  160. if(vortex){vortex.rectTransform.localRotation=Quaternion.Euler(0,0,clock*7);vortex.color=new Color(1,1,1,.30f+.10f*Mathf.Sin(clock*1.5f));}
  161. if(completed)return;
  162. if(measurable)
  163. shown=Mathf.MoveTowards(shown,target,Time.unscaledDeltaTime);
  164. else
  165. {
  166. // Intro fill is explicitly presentation, never a signal that initialization succeeded.
  167. float introFill=firstRenderAt<0 ? 0 : Mathf.Clamp01((float)((Time.realtimeSinceStartupAsDouble-firstRenderAt)/MinimumIntroSeconds));
  168. float visualFill=0;
  169. #if UNITY_EDITOR
  170. visualFill=introFill;
  171. #endif
  172. float desired=closeRequested ? Mathf.Max(target,introFill) : stageBased ? target : visualFill;
  173. shown=Mathf.Max(shown,sharedVisualFill);
  174. shown=Mathf.MoveTowards(shown,Mathf.Max(shown,desired),Time.unscaledDeltaTime*2);
  175. sharedVisualFill=Mathf.Max(sharedVisualFill,shown);
  176. }
  177. energy.fillAmount=shown;
  178. fillGlow.enabled=shown>0 && shown<1;
  179. fillGlow.rectTransform.anchoredPosition=new Vector2(EnergyWidth*shown-9,-2);
  180. percent.text=measurable ? Mathf.FloorToInt(shown*100)+"%" : "";
  181. if(closeRequested && introCompleted && shown>=1)
  182. {
  183. // Render at least one complete frame before the successful UI handoff.
  184. if(fullFrame<0)fullFrame=Time.frameCount;
  185. else if(Time.frameCount>fullFrame){Trace("StartScreenEntered");HideNow();}
  186. }
  187. }
  188. public void Close()
  189. {
  190. if(closeRequested || failed)return;
  191. InitializationSucceeded();completed=measurable=false;closeRequested=true;FillCaption();
  192. // No scene changes here. Only a real successful initializer is allowed to request Close.
  193. }
  194. private void HideNow(){gameObject.SetActive(false);Destroy(gameObject);}
  195. static RectTransform Rect(string name,Transform parent,float x,float y,float w,float h)
  196. {var r=(RectTransform)new GameObject(name,typeof(RectTransform)).transform;r.SetParent(parent,false);r.anchorMin=r.anchorMax=r.pivot=new Vector2(0,1);r.anchoredPosition=new Vector2(x,-y);r.sizeDelta=new Vector2(w,h);return r;}
  197. static Image Picture(string name,Transform parent,Sprite sprite,float x,float y,float w,float h)
  198. {var i=Rect(name,parent,x,y,w,h).gameObject.AddComponent<Image>();i.sprite=sprite;i.preserveAspect=true;i.raycastTarget=false;i.color=sprite?Color.white:new Color(.1f,.03f,.15f);return i;}
  199. static Text TextAt(Transform parent,string text,int size,float x,float y,float w,float h)
  200. {var t=Rect(text,parent,x,y,w,h).gameObject.AddComponent<Text>();t.font=Resources.GetBuiltinResource<Font>("LegacyRuntime.ttf");t.fontSize=size;t.color=new Color(.91f,.75f,.43f);t.alignment=TextAnchor.MiddleCenter;t.text=text;t.raycastTarget=false;return t;}
  201. }
  202. public sealed class LoadingSafeArea : MonoBehaviour
  203. {
  204. void LateUpdate(){var r=(RectTransform)transform;var s=Screen.safeArea;if(Screen.width<=0||Screen.height<=0)return;r.anchorMin=s.min/new Vector2(Screen.width,Screen.height);r.anchorMax=s.max/new Vector2(Screen.width,Screen.height);r.offsetMin=r.offsetMax=Vector2.zero;}
  205. }
  206. }