| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208 |
- using System;
- using System.Reflection;
- using UnityEngine;
- using UnityEngine.UI;
- namespace DevilLink2.Loading
- {
- // Shared presentation only: no player, session, scene loader or persistence ownership.
- public sealed class GameLoadingView : MonoBehaviour
- {
- private Text heading, status, percent;
- private Button retryButton;
- private Action retry;
- private Image energy, vortex, fillGlow, logoSpark, loadingArt;
- private const float EnergyWidth = 280.48f, EnergyHeight = 30.14f;
- private static int activeViews, attempt;
- private static double introDeadline, firstRenderAt;
- private static bool introCompleted, initializing;
- private static float sharedVisualFill;
- private bool presentationReady, closeRequested;
- private const double MinimumIntroSeconds=.9;
- private void Awake()
- {
- if(activeViews++==0){introDeadline=firstRenderAt=-1;introCompleted=initializing=false;attempt=0;sharedVisualFill=0;}
- Canvas.willRenderCanvases+=FirstRender;
- }
- private void FirstRender()
- {
- if(!presentationReady || !isActiveAndEnabled)return;
- if(firstRenderAt<0){firstRenderAt=Time.realtimeSinceStartupAsDouble;introDeadline=firstRenderAt+MinimumIntroSeconds;Trace("LoadingShown");}
- Canvas.willRenderCanvases-=FirstRender;
- }
- private void OnDestroy(){Canvas.willRenderCanvases-=FirstRender;activeViews=Mathf.Max(0,activeViews-1);}
- public float IntroRemaining => firstRenderAt<0 ? (float)MinimumIntroSeconds : Mathf.Max(0,(float)(introDeadline-Time.realtimeSinceStartupAsDouble));
- [System.Diagnostics.Conditional("UNITY_EDITOR")]
- private static void Trace(string point)
- {
- double now=Time.realtimeSinceStartupAsDouble;
- Debug.Log("[LoadingTiming] "+point+" attempt="+attempt+" realtime="+now.ToString("F3",System.Globalization.CultureInfo.InvariantCulture)+
- " visible="+(firstRenderAt<0?"not-rendered":(now-firstRenderAt).ToString("F3",System.Globalization.CultureInfo.InvariantCulture)));
- }
- public void InitializationStarted()
- {if(initializing)return;initializing=true;attempt++;Trace("InitializationStarted");}
- public void InitializationSucceeded(){if(!initializing)return;initializing=false;Trace("InitializationSucceeded");}
- public void InitializationFailed(){if(!initializing)return;initializing=false;Trace("InitializationFailed");}
- public void DismissForRecovery(){InitializationFailed();HideNow();}
- private RectTransform segment;
- private float clock, target, shown;
- private bool measurable, failed, completed, stageBased;
- private int fullFrame=-1;
- private string currentStage="Initializing game";
- public static GameLoadingView Create(Transform parent)
- {
- var go=new GameObject("DevilLink2Loading",typeof(RectTransform),typeof(Canvas),typeof(CanvasScaler),typeof(GraphicRaycaster));
- UnityEngine.SceneManagement.SceneManager.MoveGameObjectToScene(go,parent.gameObject.scene);
- var canvas=go.GetComponent<Canvas>();canvas.renderMode=RenderMode.ScreenSpaceOverlay;canvas.sortingOrder=30000;
- var scaler=go.GetComponent<CanvasScaler>();scaler.uiScaleMode=CanvasScaler.ScaleMode.ScaleWithScreenSize;scaler.referenceResolution=new Vector2(430,932);scaler.screenMatchMode=CanvasScaler.ScreenMatchMode.Expand;
- var v=go.AddComponent<GameLoadingView>();
- var safe=Rect("SafeArea",go.transform,0,0,430,932);safe.gameObject.AddComponent<LoadingSafeArea>();
- var frame=Rect("PortraitFrame",safe,0,0,430,932);frame.anchorMin=frame.anchorMax=frame.pivot=new Vector2(.5f,.5f);frame.anchoredPosition=Vector2.zero;
- frame.gameObject.AddComponent<RectMask2D>();
- var fitter=frame.gameObject.AddComponent<AspectRatioFitter>();fitter.aspectMode=AspectRatioFitter.AspectMode.FitInParent;fitter.aspectRatio=430f/932;
- var bg=Picture("ReferenceCastleScene",frame,Resources.Load<Sprite>("LoadingArt/ReferenceScene_R3"),0,0,430,932);bg.preserveAspect=false;bg.raycastTarget=true;
- // Logo and the solid portal belong to the reference illustration; no duplicate overlays.
- v.logoSpark=Picture("LogoGemSpark",frame,Resources.Load<Sprite>("LobbyLogoAnimation/Crystal_Star"),208,145,14,14);
- v.vortex=Picture("PortalEnergy",frame,Resources.Load<Sprite>("StartScreenArt/Portal_Vortex"),128,292,174,174);
- v.vortex.color=new Color(1,1,1,.30f);
- v.heading=TextAt(frame,"LOADING FAILED",23,45,630,340,36);
- v.heading.gameObject.SetActive(false);
- v.loadingArt=Picture("LoadingArtLetters",frame,Resources.Load<Sprite>("LoadingArt/R4/LoadingLetters"),115,631,200,25.55f);
- // Original bar layers share an 871x182 extraction canvas; use the same scale for every ornament.
- var bar=Rect("BarRoot",frame,40,680,350,73.13f);
- const float scale=350f/871f;
- Picture("DeepPurpleSlot",bar,Resources.Load<Sprite>("LoadingArt/R4/Slot"),84*scale,55*scale,EnergyWidth,EnergyHeight);
- var mask=Rect("EnergyViewport",bar,84*scale,55*scale,EnergyWidth,EnergyHeight);
- var roundedMask=mask.gameObject.AddComponent<Image>();roundedMask.sprite=Resources.Load<Sprite>("LoadingArt/R4/Slot");roundedMask.raycastTarget=false;
- mask.gameObject.AddComponent<Mask>().showMaskGraphic=false;
- v.energy=Picture("PurpleEnergy",mask,Resources.Load<Sprite>("LoadingArt/R4/Energy"),0,0,EnergyWidth,EnergyHeight);v.energy.preserveAspect=false;v.segment=v.energy.rectTransform;
- v.fillGlow=Picture("FillFrontGlow",mask,Resources.Load<Sprite>("LobbyModeAnimation/SoftGlow"),0,-2,18,EnergyHeight+4);
- v.fillGlow.color=new Color(1,.35f,1,.45f);v.fillGlow.enabled=false;
- v.segment.sizeDelta=new Vector2(EnergyWidth,EnergyHeight);v.segment.anchoredPosition=Vector2.zero;
- v.energy.type=Image.Type.Filled;v.energy.fillMethod=Image.FillMethod.Horizontal;v.energy.fillOrigin=0;
- v.shown=sharedVisualFill;v.energy.fillAmount=v.shown;
- var gold=Picture("GoldOrnament",bar,Resources.Load<Sprite>("LoadingArt/R4/GoldFrame_R5"),0,0,350,73.13f);
- Picture("TopCrystal",bar,Resources.Load<Sprite>("LoadingArt/R4/TopCrystal"),360*scale,-18*scale,150*scale,93*scale);
- Picture("BottomCrystal",bar,Resources.Load<Sprite>("LoadingArt/R4/BottomCrystal"),371*scale,100*scale,128*scale,80*scale);
- gold.transform.SetAsLastSibling(); // Static metal above slot, energy and jewel joins.
- v.percent=TextAt(frame,"",16,50,748,330,26);
- v.status=TextAt(frame,"Initializing game",13,35,755,360,60);
- var retryFace=Picture("Retry",frame,Resources.Load<Sprite>("ProfileProgressCapsule"),143,855,144,44);retryFace.color=new Color(.22f,.08f,.3f);retryFace.raycastTarget=true;
- v.retryButton=retryFace.gameObject.AddComponent<Button>();v.retryButton.targetGraphic=retryFace;v.retryButton.transition=Selectable.Transition.None;
- TextAt(retryFace.transform,"RETRY",16,0,0,144,44);
- v.retryButton.onClick.AddListener(()=>{v.retryButton.gameObject.SetActive(false);var action=v.retry;v.retry=null;action?.Invoke();});v.retryButton.gameObject.SetActive(false);
- v.presentationReady=true;
- return v;
- }
- static void TryLogoRig(GameObject owner,Image logo)
- {
- // Reuse the existing rig only when its runtime assembly is already available.
- var screenType=Type.GetType("DevilLink2.UI.UIScreen, DevilLink2");
- var rigType=Type.GetType("DevilLink2.UI.LobbyLogoAnimation, DevilLink2");
- if(screenType==null||rigType==null||!logo.sprite)return;
- try {
- var screen=owner.AddComponent(screenType);
- screenType.GetMethod("SetVisible").Invoke(screen,new object[]{true});
- rigType.GetMethod("Install",new[]{screenType,typeof(Image)}).Invoke(null,new object[]{screen,logo});
- } catch(Exception error) { Debug.LogWarning("Loading logo rig unavailable; using original artwork: "+error.Message); }
- }
- private void SetTitle(bool art,string text="")
- { if(loadingArt)loadingArt.enabled=art;heading.gameObject.SetActive(!art && text.Length>0);heading.text=text; }
- private void FillCaption()
- {
- status.text=closeRequested ? "Opening start screen" : measurable || stageBased ? currentStage :
- (IntroRemaining>0 ? "Opening effect · " : "Waiting for initialization · ")+currentStage;
- }
- public void Indeterminate(string stage)
- {
- if(failed){shown=target=sharedVisualFill=0;stageBased=false;fullFrame=-1;}
- failed=completed=measurable=false;SetTitle(true);currentStage=stage;
- if(retryButton)retryButton.gameObject.SetActive(false);
- energy.enabled=true;energy.type=Image.Type.Filled;energy.fillMethod=Image.FillMethod.Horizontal;energy.fillOrigin=0;
- segment.sizeDelta=new Vector2(EnergyWidth,EnergyHeight);segment.anchoredPosition=Vector2.zero;
- energy.fillAmount=shown;fillGlow.enabled=false;percent.text="";FillCaption();
- status.rectTransform.anchoredPosition=new Vector2(35,-755);status.rectTransform.sizeDelta=new Vector2(360,60);
- }
- // Discrete completed stages, not downloaded bytes or a fabricated percentage.
- public void StageCompleted(bool sceneReady,string stage)
- {
- Indeterminate(stage);stageBased=true;
- target=Mathf.Max(target,sceneReady ? 2f/3f : 1f/3f);FillCaption();
- }
- public void ShowFailure(string message,Action retryAction=null)
- {
- InitializationFailed();closeRequested=false;failed=true;completed=false;retry=retryAction;SetTitle(false,"LOADING FAILED");
- percent.text="";status.text=message;status.rectTransform.anchoredPosition=new Vector2(35,-773);status.rectTransform.sizeDelta=new Vector2(360,76);
- energy.enabled=true;fillGlow.enabled=false;if(retryButton)retryButton.gameObject.SetActive(retryAction!=null);
- }
- // This API accepts only an actual operation's normalized progress, never pipeline weights.
- public void Measured(string stage,float value)
- {
- if(!measurable)shown=target=0;
- failed=completed=false;measurable=true;SetTitle(true);if(retryButton)retryButton.gameObject.SetActive(false);
- energy.enabled=true;energy.type=Image.Type.Filled;energy.fillMethod=Image.FillMethod.Horizontal;energy.fillOrigin=0;
- segment.sizeDelta=new Vector2(EnergyWidth,EnergyHeight);segment.anchoredPosition=Vector2.zero;
- energy.fillAmount=shown;target=Mathf.Max(target,Mathf.Clamp01(value));currentStage=stage;status.text=stage;
- }
- public void Complete()
- {
- failed=false;completed=true;measurable=false;shown=target=1;
- SetTitle(false,"READY");percent.text="";status.text="Ready";fillGlow.enabled=false;
- energy.enabled=true;energy.type=Image.Type.Filled;energy.fillAmount=1;
- segment.sizeDelta=new Vector2(EnergyWidth,EnergyHeight);segment.anchoredPosition=Vector2.zero;
- if(retryButton)retryButton.gameObject.SetActive(false);
- }
- private void Update()
- {
- if(firstRenderAt>=0 && !introCompleted && IntroRemaining<=0){introCompleted=true;Trace("IntroCompleted");if(!failed)FillCaption();}
- if(failed)return;
- clock+=Time.unscaledDeltaTime;
- if(logoSpark)logoSpark.color=new Color(1,.8f,.5f,.15f+.4f*(.5f+.5f*Mathf.Sin(clock*1.4f)));
- 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));}
- if(completed)return;
- if(measurable)
- shown=Mathf.MoveTowards(shown,target,Time.unscaledDeltaTime);
- else
- {
- // Intro fill is explicitly presentation, never a signal that initialization succeeded.
- float introFill=firstRenderAt<0 ? 0 : Mathf.Clamp01((float)((Time.realtimeSinceStartupAsDouble-firstRenderAt)/MinimumIntroSeconds));
- float visualFill=0;
- #if UNITY_EDITOR
- visualFill=introFill;
- #endif
- float desired=closeRequested ? Mathf.Max(target,introFill) : stageBased ? target : visualFill;
- shown=Mathf.Max(shown,sharedVisualFill);
- shown=Mathf.MoveTowards(shown,Mathf.Max(shown,desired),Time.unscaledDeltaTime*2);
- sharedVisualFill=Mathf.Max(sharedVisualFill,shown);
- }
- energy.fillAmount=shown;
- fillGlow.enabled=shown>0 && shown<1;
- fillGlow.rectTransform.anchoredPosition=new Vector2(EnergyWidth*shown-9,-2);
- percent.text=measurable ? Mathf.FloorToInt(shown*100)+"%" : "";
- if(closeRequested && introCompleted && shown>=1)
- {
- // Render at least one complete frame before the successful UI handoff.
- if(fullFrame<0)fullFrame=Time.frameCount;
- else if(Time.frameCount>fullFrame){Trace("StartScreenEntered");HideNow();}
- }
- }
- public void Close()
- {
- if(closeRequested || failed)return;
- InitializationSucceeded();completed=measurable=false;closeRequested=true;FillCaption();
- // No scene changes here. Only a real successful initializer is allowed to request Close.
- }
- private void HideNow(){gameObject.SetActive(false);Destroy(gameObject);}
- static RectTransform Rect(string name,Transform parent,float x,float y,float w,float h)
- {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;}
- static Image Picture(string name,Transform parent,Sprite sprite,float x,float y,float w,float h)
- {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;}
- static Text TextAt(Transform parent,string text,int size,float x,float y,float w,float h)
- {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;}
- }
- public sealed class LoadingSafeArea : MonoBehaviour
- {
- 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;}
- }
- }
|