| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using DevilLink2.UI;
- using UnityEditor;
- using UnityEngine;
- using UnityEngine.UI;
- namespace DevilLink2.Editor
- {
- // Editor-only transient visual copy: never opens a real screen or invokes a business callback.
- [InitializeOnLoad]
- public static class PopupRenderCompare
- {
- private const string Menu="Tools/Devil Link 2/Diagnostics/Popup Render Compare/";
- private static GameObject overlay;private static RectTransform card;private static PopupAnimationController motion;
- private static CanvasGroup gate;private static bool native,shown,moving,staticMode;
- private static float started,from;private static int serial;
- private static readonly List<UnityEngine.Object> owned=new List<UnityEngine.Object>();
- private static readonly List<string> manifest=new List<string>();
- static PopupRenderCompare(){EditorApplication.playModeStateChanged+=State;AssemblyReloadEvents.beforeAssemblyReload+=Clear;}
- [MenuItem(Menu+"Original Rendering")]
- private static void Original(){native=false;Clear();Debug.Log("Render comparison A selected. Open Test Popup to run.");}
- [MenuItem(Menu+"Native Image Rendering")]
- private static void Native(){native=true;Clear();Debug.Log("Render comparison B selected. Open Test Popup to run.");}
- [MenuItem(Menu+"Open Test Popup")]
- private static void Open()
- {
- if(!Application.isPlaying){Debug.LogWarning("Requires Main Play Mode. Real save data is not touched by this tool.");return;}
- staticMode=true;
- if(shown)return;
- try {if(!overlay && !Build())return;}catch(Exception error){Clear();Debug.LogException(error);return;}
- shown=true;from=moving?motion.CurrentOffset:12;gate.alpha=1;motion.ResetVisual();overlay.SetActive(true);
- moving=!staticMode;started=Time.realtimeSinceStartup;gate.interactable=staticMode;gate.blocksRaycasts=true;
- }
- [MenuItem(Menu+"Close Test Popup")]
- private static void Close()
- {
- if(!overlay||!shown)return;shown=false;from=motion.CurrentOffset;started=Time.realtimeSinceStartup;moving=!staticMode;
- gate.interactable=false;if(staticMode)Finish();
- }
- [MenuItem(Menu+"Static No Motion")]
- private static void Static(){staticMode=true;if(overlay)Finish();}
- [MenuItem(Menu+"Motion Retired - Static Only")]
- private static void Animated(){staticMode=true;Debug.Log("Popup motion retired; static rendering comparison only.");}
- [MenuItem(Menu+"Remove Test Popup")]
- private static void Clear()
- {
- moving=shown=false;if(overlay)UnityEngine.Object.DestroyImmediate(overlay);overlay=null;card=null;motion=null;gate=null;
- foreach(var item in owned)if(item)UnityEngine.Object.DestroyImmediate(item);owned.Clear();
- }
- private static void State(PlayModeStateChange state){if(state==PlayModeStateChange.ExitingPlayMode)Clear();}
- private static bool Build()
- {
- var wheel=UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
- if(!wheel){Debug.LogWarning("Cached LuckyWheelScreen not found. Initialize Main first.");return false;}
- var source=wheel.transform.Find("Card") as RectTransform;if(!source){Debug.LogWarning("Wheel Card not found; no hierarchy changed.");return false;}
- if(wheel.IsSpinning){Debug.LogWarning("Wait until the real wheel is idle before creating a visual test copy.");return false;}
- var originalRoot=(RectTransform)wheel.transform;
- var root=new GameObject("DiagnosticPopupRenderCompare",typeof(RectTransform));overlay=root;
- root.SetActive(false);var rect=(RectTransform)root.transform;rect.SetParent(wheel.transform.parent,false);
- rect.anchorMin=originalRoot.anchorMin;rect.anchorMax=originalRoot.anchorMax;rect.pivot=originalRoot.pivot;rect.sizeDelta=originalRoot.sizeDelta;rect.anchoredPosition=originalRoot.anchoredPosition;
- root.hideFlags=HideFlags.DontSave;var shade=root.AddComponent<Image>();shade.color=wheel.GetComponent<Image>().color;shade.raycastTarget=true;
- gate=root.AddComponent<CanvasGroup>();gate.alpha=1;
- card=UnityEngine.Object.Instantiate(source,rect,false);card.name="TestVisualRoot";
- // Disable layout/business updates before activation, preserving only visual and input primitives.
- foreach(var script in card.GetComponentsInChildren<MonoBehaviour>(true)){
- bool keep=script is Graphic || script is BaseMeshEffect || script is Selectable || script is ScrollRect;
- if(!keep)script.enabled=false;
- }
- foreach(var button in card.GetComponentsInChildren<Button>(true))button.onClick=new Button.ButtonClickedEvent();
- // No original screen root, player, service, or result panel is cloned.
- motion=root.AddComponent<PopupAnimationController>();motion.Bind(card);
- root.transform.SetAsLastSibling();gate.interactable=false;root.SetActive(true);Canvas.ForceUpdateCanvases();
- manifest.Clear();manifest.Add("Mode="+(native?"B native Image":"A original")+"; Card="+card.rect.size+"; source="+source.rect.size);
- if(native){
- int index=0;
- foreach(var graphic in card.GetComponentsInChildren<Image>(true).Where(g=>g.GetType()!=typeof(Image)||g.GetComponent<UIGradient>()).ToArray()){
- if(!graphic.gameObject.activeInHierarchy)continue;
- BakeAndReplace(graphic,index++);
- }
- }
- Directory.CreateDirectory("Temp/DevilLink2Task13B05F");File.WriteAllLines("Temp/DevilLink2Task13B05F/LastBuildManifest.txt",manifest);
- root.SetActive(false);return true;
- }
- private static void BakeAndReplace(Image graphic,int index)
- {
- var rect=graphic.rectTransform.rect;if(rect.width<=0||rect.height<=0)return;
- graphic.Rebuild(CanvasUpdate.PreRender);var mesh=graphic.canvasRenderer.GetMesh();
- var vertices=mesh.vertices;var colors=mesh.colors32;var triangles=mesh.triangles;var uv=mesh.uv;
- if(vertices.Length==0){UnityEngine.Object.DestroyImmediate(mesh);manifest.Add("SKIPPED empty mesh: "+graphic.name);return;}
- // Read authored textures without changing their importers, preserving custom panel UV slicing.
- Color[] texels=null;int tw=0,th=0;
- if(graphic.sprite){
- var texture=graphic.mainTexture;tw=texture.width;th=texture.height;
- var rt=RenderTexture.GetTemporary(tw,th,0,RenderTextureFormat.ARGB32,RenderTextureReadWrite.Linear);var previous=RenderTexture.active;
- try{Graphics.Blit(texture,rt);RenderTexture.active=rt;var copy=new Texture2D(tw,th,TextureFormat.RGBA32,false,true);copy.ReadPixels(new Rect(0,0,tw,th),0,0);copy.Apply();texels=copy.GetPixels();UnityEngine.Object.DestroyImmediate(copy);}
- finally{RenderTexture.active=previous;RenderTexture.ReleaseTemporary(rt);}
- }
- var bounds=rect;
- foreach(var v in vertices){bounds.xMin=Mathf.Min(bounds.xMin,v.x);bounds.xMax=Mathf.Max(bounds.xMax,v.x);bounds.yMin=Mathf.Min(bounds.yMin,v.y);bounds.yMax=Mathf.Max(bounds.yMax,v.y);}
- int w=Mathf.Clamp(Mathf.CeilToInt(bounds.width*2),1,2048),h=Mathf.Clamp(Mathf.CeilToInt(bounds.height*2),1,2048);
- var pixels=new Color[w*h];
- for(int t=0;t<triangles.Length;t+=3){
- int a=triangles[t],b=triangles[t+1],c=triangles[t+2];
- Vector2 x=Pixel(vertices[a],bounds,w,h),y=Pixel(vertices[b],bounds,w,h),z=Pixel(vertices[c],bounds,w,h);
- float area=Cross(y-x,z-x);if(Mathf.Abs(area)<.00001f)continue;
- int left=Mathf.Clamp(Mathf.FloorToInt(Mathf.Min(x.x,Mathf.Min(y.x,z.x))),0,w-1),right=Mathf.Clamp(Mathf.CeilToInt(Mathf.Max(x.x,Mathf.Max(y.x,z.x))),0,w-1);
- int bottom=Mathf.Clamp(Mathf.FloorToInt(Mathf.Min(x.y,Mathf.Min(y.y,z.y))),0,h-1),top=Mathf.Clamp(Mathf.CeilToInt(Mathf.Max(x.y,Mathf.Max(y.y,z.y))),0,h-1);
- for(int py=bottom;py<=top;py++)for(int px=left;px<=right;px++){
- var p=new Vector2(px+.5f,py+.5f);float u=Cross(y-p,z-p)/area,v=Cross(z-p,x-p)/area,q=1-u-v;
- if(u<-.00001f||v<-.00001f||q<-.00001f)continue;
- Color color=(Color)colors[a]*u+(Color)colors[b]*v+(Color)colors[c]*q;
- if(texels!=null){var at=uv[a]*u+uv[b]*v+uv[c]*q;float xx=Mathf.Clamp01(at.x)*(tw-1),yy=Mathf.Clamp01(at.y)*(th-1);int ix=(int)xx,iy=(int)yy;var sample=Color.Lerp(Color.Lerp(texels[iy*tw+ix],texels[iy*tw+Mathf.Min(ix+1,tw-1)],xx-ix),Color.Lerp(texels[Mathf.Min(iy+1,th-1)*tw+ix],texels[Mathf.Min(iy+1,th-1)*tw+Mathf.Min(ix+1,tw-1)],xx-ix),yy-iy);color*=sample;}
- int k=py*w+px;var old=pixels[k];float alpha=color.a+old.a*(1-color.a);
- pixels[k]=alpha>0?new Color((color.r*color.a+old.r*old.a*(1-color.a))/alpha,(color.g*color.a+old.g*old.a*(1-color.a))/alpha,(color.b*color.a+old.b*old.a*(1-color.a))/alpha,alpha):Color.clear;
- }
- }
- UnityEngine.Object.DestroyImmediate(mesh);
- var tex=new Texture2D(w,h,TextureFormat.RGBA32,false,true);tex.SetPixels(pixels);tex.Apply();
- byte[] png=tex.EncodeToPNG();UnityEngine.Object.DestroyImmediate(tex);
- string dir="Temp/DevilLink2Task13B05F/Bakes";Directory.CreateDirectory(dir);File.WriteAllBytes(dir+"/"+index+"_"+graphic.name+".png",png);
- tex=new Texture2D(2,2,TextureFormat.RGBA32,false,true);tex.LoadImage(png);tex.filterMode=FilterMode.Bilinear;tex.wrapMode=TextureWrapMode.Clamp;owned.Add(tex);
- var sprite=Sprite.Create(tex,new Rect(0,0,w,h),Vector2.one*.5f,100,0,SpriteMeshType.FullRect);owned.Add(sprite);
- var go=graphic.gameObject;var tint=graphic.canvasRenderer.GetColor();var buttons=card.GetComponentsInChildren<Selectable>(true);
- var targets=new List<Selectable>();foreach(var button in buttons)if(button.targetGraphic==graphic)targets.Add(button);
- foreach(var effect in go.GetComponents<BaseMeshEffect>())UnityEngine.Object.DestroyImmediate(effect);
- bool hit=graphic.raycastTarget;UnityEngine.Object.DestroyImmediate(graphic);
- // Keep the original hit rectangle; bake shadow pixels outside it into a non-interactive child.
- var surface=go.AddComponent<Image>();surface.color=Color.clear;surface.raycastTarget=hit;surface.material=null;
- var art=new GameObject("NativeBakedArtwork",typeof(RectTransform),typeof(CanvasRenderer));var ar=(RectTransform)art.transform;ar.SetParent(go.transform,false);
- ar.anchorMin=ar.anchorMax=new Vector2(0,1);ar.pivot=new Vector2(0,1);ar.sizeDelta=bounds.size;ar.anchoredPosition=new Vector2(bounds.xMin-rect.xMin,bounds.yMax-rect.yMax);ar.SetAsFirstSibling();
- var image=art.AddComponent<Image>();image.sprite=sprite;image.color=Color.white;image.material=null;image.raycastTarget=false;image.type=Image.Type.Simple;
- foreach(var button in targets)button.targetGraphic=image;
- image.canvasRenderer.SetColor(tint);
- manifest.Add("BAKED "+go.name+" "+w+"x"+h+" native Image; no runtime MeshEffect; tint="+tint);
- }
- private static Vector2 Pixel(Vector3 p,Rect r,int w,int h)=>new Vector2((p.x-r.xMin)/r.width*w,(p.y-r.yMin)/r.height*h);
- private static float Cross(Vector2 a,Vector2 b)=>a.x*b.y-a.y*b.x;
- private static void Finish(){moving=false;if(!overlay)return;motion.ResetVisual();gate.alpha=1;gate.interactable=shown;gate.blocksRaycasts=shown;overlay.SetActive(shown);}
- }
- }
|