WheelFormalRenderCompare.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Security.Cryptography;
  7. using System.Text;
  8. using DevilLink2.UI;
  9. using UnityEditor;
  10. using UnityEngine;
  11. using UnityEngine.UI;
  12. namespace DevilLink2.Editor
  13. {
  14. [InitializeOnLoad]
  15. public static class WheelFormalRenderCompare
  16. {
  17. private const string Menu="Tools/Devil Link 2/Diagnostics/Popup Render Compare/";
  18. private sealed class Effect { public Type Type;public string Json; }
  19. private sealed class Saved {
  20. public GameObject Object;public Type Type;public string Json;public Image Native;
  21. public readonly List<Effect> Effects=new List<Effect>();public readonly List<Selectable> Targets=new List<Selectable>();
  22. public Color Tint;public bool Enabled;
  23. public readonly Dictionary<Selectable,SpriteState> SpriteStates=new Dictionary<Selectable,SpriteState>();
  24. }
  25. private static readonly List<Saved> saved=new List<Saved>();
  26. private static readonly List<UnityEngine.Object> owned=new List<UnityEngine.Object>();
  27. private static readonly List<string> manifest=new List<string>();
  28. private static readonly Dictionary<UITransition,bool?> overrides=new Dictionary<UITransition,bool?>();
  29. static WheelFormalRenderCompare(){EditorApplication.playModeStateChanged+=Changed;AssemblyReloadEvents.beforeAssemblyReload+=Restore;}
  30. [MenuItem(Menu+"A - Formal Original Rendering (Static)")]
  31. private static void A(){Apply(false,true);}
  32. [MenuItem(Menu+"B - Formal Native PNG (Static)")]
  33. private static void B(){Apply(true,true);}
  34. [MenuItem(Menu+"C - Formal Native PNG + Static")]
  35. private static void C(){Apply(true,false);}
  36. [MenuItem(Menu+"Restore Formal Wheel")]
  37. private static void Restore(){
  38. foreach(var pair in overrides)if(pair.Key)pair.Key.SetPopupAnimationOverride(pair.Value);overrides.Clear();
  39. for(int i=saved.Count-1;i>=0;i--){var entry=saved[i];if(!entry.Object)continue;
  40. foreach(var effect in entry.Object.GetComponents<BaseMeshEffect>())UnityEngine.Object.DestroyImmediate(effect);
  41. if(entry.Native)UnityEngine.Object.DestroyImmediate(entry.Native);
  42. var original=(Image)entry.Object.AddComponent(entry.Type);EditorJsonUtility.FromJsonOverwrite(entry.Json,original);
  43. foreach(var effect in entry.Effects){var component=entry.Object.AddComponent(effect.Type);EditorJsonUtility.FromJsonOverwrite(effect.Json,component);}
  44. foreach(var target in entry.Targets)if(target){target.targetGraphic=original;if(entry.SpriteStates.ContainsKey(target))target.spriteState=entry.SpriteStates[target];}
  45. original.canvasRenderer.SetColor(entry.Tint);
  46. }
  47. saved.Clear();foreach(var item in owned)if(item)UnityEngine.Object.DestroyImmediate(item);owned.Clear();
  48. }
  49. private static void Changed(PlayModeStateChange state){if(state==PlayModeStateChange.ExitingPlayMode)Restore();}
  50. private static void Apply(bool png,bool motion){
  51. if(!Application.isPlaying){Debug.LogWarning("Requires the real Main Play Mode. No test copy is created.");return;}
  52. var wheel=UnityEngine.Object.FindFirstObjectByType<LuckyWheelScreen>(FindObjectsInactive.Include);
  53. if(!wheel||wheel.IsSpinning){Debug.LogWarning("Wheel must be initialized and not spinning before mode changes.");return;}
  54. Restore();manifest.Clear();manifest.Add("REAL Wheel instance="+wheel.GetInstanceID()+" mode="+(png?(motion?"B":"C"):"A"));
  55. try{
  56. foreach(var root in new[]{wheel.gameObject,wheel.ResultPanel}){
  57. var transition=root.GetComponent<UITransition>();if(!transition)throw new InvalidOperationException("Missing real UITransition");
  58. // Motion overrides retired: every formal UITransition is synchronous.
  59. }
  60. if(png)foreach(var graphic in wheel.GetComponentsInChildren<Image>(true).ToArray()){
  61. if(graphic.GetType()==typeof(Image) && !graphic.GetComponent<UIGradient>())continue;
  62. Convert(graphic,wheel);
  63. }
  64. Directory.CreateDirectory("Temp/DevilLink2Task13B05G");File.WriteAllLines("Temp/DevilLink2Task13B05G/LastFormalManifest.txt",manifest);
  65. Debug.Log("Formal rendering mode ready (popup motion retired; static only); use actual Lobby WHEEL / X / SPIN / CONFIRM. Real rewards remain active. Use an isolated save.");
  66. }catch(Exception e){Restore();Debug.LogException(e);}
  67. }
  68. private static void Convert(Image source,LuckyWheelScreen wheel){
  69. var entry=new Saved{Object=source.gameObject,Type=source.GetType(),Json=EditorJsonUtility.ToJson(source),Tint=source.canvasRenderer.GetColor(),Enabled=source.enabled};
  70. foreach(var e in source.GetComponents<BaseMeshEffect>())entry.Effects.Add(new Effect{Type=e.GetType(),Json=EditorJsonUtility.ToJson(e)});
  71. foreach(var target in wheel.GetComponentsInChildren<Selectable>(true))if(target.targetGraphic==source){entry.Targets.Add(target);entry.SpriteStates[target]=target.spriteState;}
  72. Sprite sprite=null;var variants=new Dictionary<Sprite,Sprite>();
  73. if(source.sprite && (source.GetType().Name=="WheelSpinOrnament"||source.GetType().Name=="WheelPointerGraphic")){
  74. sprite=source.sprite;manifest.Add("REUSE existing PNG sprite: "+source.name);
  75. }else{
  76. var temp=new GameObject("GraphicBakeScratch",typeof(RectTransform),typeof(CanvasRenderer));temp.hideFlags=HideFlags.HideAndDontSave;
  77. try{
  78. // Scratch contains graphics only, never a screen, service, Button or player.
  79. temp.transform.SetParent(source.GetComponentInParent<Canvas>().transform,false);
  80. var r=(RectTransform)temp.transform;r.pivot=source.rectTransform.pivot;r.sizeDelta=source.rectTransform.rect.size;r.anchoredPosition=new Vector2(-100000,-100000);
  81. var copy=(Image)temp.AddComponent(source.GetType());EditorJsonUtility.FromJsonOverwrite(entry.Json,copy);copy.enabled=true;
  82. foreach(var e in entry.Effects)if(e.Type.Namespace!="UnityEngine.UI"){
  83. var effect=(BaseMeshEffect)temp.AddComponent(e.Type);EditorJsonUtility.FromJsonOverwrite(e.Json,effect);
  84. }
  85. string key;
  86. using(var sha=SHA256.Create())key=BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(entry.Type.FullName+entry.Json+source.rectTransform.rect+string.Join("",entry.Effects.Select(e=>e.Json))))).Replace("-","");
  87. var normal=source.sprite;
  88. copy.overrideSprite=normal;sprite=Bake(copy,key+"_normal");
  89. if(normal)variants[normal]=sprite;
  90. foreach(var target in entry.Targets)if(target.transition==Selectable.Transition.SpriteSwap){
  91. var state=target.spriteState;
  92. foreach(var variant in new[]{state.highlightedSprite,state.pressedSprite,state.selectedSprite,state.disabledSprite}){
  93. if(!variant||variants.ContainsKey(variant))continue;
  94. copy.overrideSprite=variant;variants[variant]=Bake(copy,key+"_"+variant.GetInstanceID());
  95. }
  96. }
  97. }finally{UnityEngine.Object.DestroyImmediate(temp);}
  98. }
  99. saved.Add(entry);
  100. foreach(var effect in source.GetComponents<BaseMeshEffect>())UnityEngine.Object.DestroyImmediate(effect);
  101. bool hit=source.raycastTarget,maskable=source.maskable;UnityEngine.Object.DestroyImmediate(source);
  102. var image=entry.Object.AddComponent<Image>();entry.Native=image;image.sprite=sprite;image.color=Color.white;image.material=null;
  103. image.raycastTarget=entry.Targets.Count>0?hit:false;image.maskable=maskable;image.type=Image.Type.Simple;
  104. foreach(var effect in entry.Effects)if(effect.Type.Namespace=="UnityEngine.UI"){
  105. var component=entry.Object.AddComponent(effect.Type);EditorJsonUtility.FromJsonOverwrite(effect.Json,component);
  106. }
  107. foreach(var target in entry.Targets){
  108. target.targetGraphic=image;
  109. if(target.transition==Selectable.Transition.SpriteSwap){var state=target.spriteState;
  110. if(state.highlightedSprite && variants.ContainsKey(state.highlightedSprite))state.highlightedSprite=variants[state.highlightedSprite];
  111. if(state.selectedSprite && variants.ContainsKey(state.selectedSprite))state.selectedSprite=variants[state.selectedSprite];
  112. if(state.pressedSprite && variants.ContainsKey(state.pressedSprite))state.pressedSprite=variants[state.pressedSprite];
  113. if(state.disabledSprite && variants.ContainsKey(state.disabledSprite))state.disabledSprite=variants[state.disabledSprite];
  114. target.spriteState=state;
  115. }
  116. }
  117. image.enabled=entry.Enabled;image.canvasRenderer.SetColor(entry.Tint);
  118. manifest.Add("REPLACED same object "+entry.Object.name+" from "+entry.Type.Name+" with native Image; white/opaque; Rect unchanged");
  119. }
  120. private static Sprite Bake(Image graphic,string cacheKey){
  121. string cached="Temp/DevilLink2Task13B05G/Bakes/"+cacheKey+".png";
  122. if(File.Exists(cached)){
  123. var texture=new Texture2D(2,2,TextureFormat.RGBA32,false,true);texture.LoadImage(File.ReadAllBytes(cached));texture.filterMode=FilterMode.Bilinear;texture.wrapMode=TextureWrapMode.Clamp;owned.Add(texture);
  124. var reused=Sprite.Create(texture,new Rect(0,0,texture.width,texture.height),Vector2.one*.5f,100,0,SpriteMeshType.FullRect);owned.Add(reused);manifest.Add("REUSE cached PNG "+cached);return reused;
  125. }
  126. var rect=graphic.rectTransform.rect;if(rect.width<=0||rect.height<=0)throw new InvalidOperationException("Zero-size graphic");
  127. var mesh=new Mesh();using(var helper=new VertexHelper()){
  128. var method=graphic.GetType().GetMethod("OnPopulateMesh",System.Reflection.BindingFlags.Instance|System.Reflection.BindingFlags.NonPublic,null,new[]{typeof(VertexHelper)},null);
  129. method.Invoke(graphic,new object[]{helper});
  130. foreach(var effect in graphic.GetComponents<BaseMeshEffect>())if(effect.enabled && effect.GetType().Namespace!="UnityEngine.UI")effect.ModifyMesh(helper);
  131. helper.FillMesh(mesh);
  132. }
  133. var vertices=mesh.vertices;var colors=mesh.colors32;var triangles=mesh.triangles;var uv=mesh.uv;
  134. if(vertices.Length==0){UnityEngine.Object.DestroyImmediate(mesh);throw new InvalidOperationException("Empty graphic mesh: "+graphic.name);}
  135. // Read authored textures without changing their importers, preserving custom panel UV slicing.
  136. Color[] texels=null;int tw=0,th=0;
  137. if(graphic.sprite){
  138. var texture=graphic.mainTexture;tw=texture.width;th=texture.height;
  139. var rt=RenderTexture.GetTemporary(tw,th,0,RenderTextureFormat.ARGB32,RenderTextureReadWrite.Linear);var previous=RenderTexture.active;
  140. 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);}
  141. finally{RenderTexture.active=previous;RenderTexture.ReleaseTemporary(rt);}
  142. }
  143. var bounds=rect;
  144. 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);}
  145. int w=Mathf.Clamp(Mathf.CeilToInt(bounds.width*2),1,2048),h=Mathf.Clamp(Mathf.CeilToInt(bounds.height*2),1,2048);
  146. var pixels=new Color[w*h];
  147. for(int t=0;t<triangles.Length;t+=3){
  148. int a=triangles[t],b=triangles[t+1],c=triangles[t+2];
  149. Vector2 x=Pixel(vertices[a],bounds,w,h),y=Pixel(vertices[b],bounds,w,h),z=Pixel(vertices[c],bounds,w,h);
  150. float area=Cross(y-x,z-x);if(Mathf.Abs(area)<.00001f)continue;
  151. 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);
  152. 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);
  153. for(int py=bottom;py<=top;py++)for(int px=left;px<=right;px++){
  154. 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;
  155. if(u<-.00001f||v<-.00001f||q<-.00001f)continue;
  156. Color color=(Color)colors[a]*u+(Color)colors[b]*v+(Color)colors[c]*q;
  157. 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;}
  158. int k=py*w+px;var old=pixels[k];float alpha=color.a+old.a*(1-color.a);
  159. 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;
  160. }
  161. }
  162. UnityEngine.Object.DestroyImmediate(mesh);
  163. var tex=new Texture2D(w,h,TextureFormat.RGBA32,false,true);tex.SetPixels(pixels);tex.Apply();
  164. byte[] png=tex.EncodeToPNG();UnityEngine.Object.DestroyImmediate(tex);
  165. string dir="Temp/DevilLink2Task13B05G/Bakes";Directory.CreateDirectory(dir);
  166. string file=dir+"/"+cacheKey+".png";
  167. if(File.Exists(file))png=File.ReadAllBytes(file);else File.WriteAllBytes(file,png);
  168. manifest.Add("PNG "+file+" "+w+"x"+h);
  169. tex=new Texture2D(2,2,TextureFormat.RGBA32,false,true);tex.LoadImage(png);tex.filterMode=FilterMode.Bilinear;tex.wrapMode=TextureWrapMode.Clamp;owned.Add(tex);
  170. var sprite=Sprite.Create(tex,new Rect(0,0,w,h),Vector2.one*.5f,100,0,SpriteMeshType.FullRect);owned.Add(sprite);
  171. return sprite;
  172. }
  173. 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);
  174. private static float Cross(Vector2 a,Vector2 b)=>a.x*b.y-a.y*b.x;
  175. }
  176. }