// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.Overlays;
using UnityEditor.SceneManagement;
using UnityEngine;

namespace WPFMA
{
    /// <summary>
    /// Tints every visible mesh in the Scene view from green to red by how heavy it is: triangles, material slots,
    /// texture memory, or whether it's see-through (overdraw). Only the Scene view shows it; nothing in the scene changes.
    /// </summary>
    [InitializeOnLoad]
    internal static class WPFMAHeatmap
    {
        internal enum Mode
        {
            Triangles,
            Materials,
            TextureMemory,
            SeeThrough
        }

        internal static readonly string[] ModeNames = { "Triangles", "Material slots", "Texture memory", "See-through" };

        internal sealed class Entry
        {
            public Renderer Renderer;
            public Mesh Mesh;
            public bool Baked;
            public double Value;
            public float Heat;
        }

        private const string OnKey = "WPFMA.Heatmap.On";
        private const string ModeKey = "WPFMA.Heatmap.Mode";

        private static readonly List<Entry> entries = new List<Entry>();
        private static int builtStamp = -1;
        private static Mode builtMode;
        private static double nextBuild;
        private static bool dirty = true;
        private static double cap;
        private static Material material;
        private static MaterialPropertyBlock block;

        static WPFMAHeatmap()
        {
            SceneView.beforeSceneGui += Draw;
            SceneView.duringSceneGui += Labels;
            EditorSceneManager.sceneOpened += (scene, mode) => dirty = true;
            AssemblyReloadEvents.beforeAssemblyReload += ClearBaked;
        }

        internal static bool On
        {
            get { return SessionState.GetBool(OnKey, false); }
            set
            {
                SessionState.SetBool(OnKey, value);
                dirty = true;
                SceneView.RepaintAll();
            }
        }

        internal static Mode Current
        {
            get { return (Mode)Mathf.Clamp(EditorPrefs.GetInt(ModeKey, 0), 0, ModeNames.Length - 1); }
            set
            {
                EditorPrefs.SetInt(ModeKey, (int)value);
                dirty = true;
                SceneView.RepaintAll();
            }
        }

        internal static List<Entry> Entries
        {
            get
            {
                Refresh();
                return entries;
            }
        }

        internal static double Cap
        {
            get { return cap; }
        }

        internal static string Format(double value, Mode mode)
        {
            switch (mode)
            {
                case Mode.Triangles: return value >= 1000 ? (value / 1000.0).ToString("0.#") + "k tris" : value.ToString("0") + " tris";
                case Mode.Materials: return value.ToString("0") + (value == 1 ? " slot" : " slots");
                case Mode.TextureMemory: return (value / (1024.0 * 1024.0)).ToString("0.#") + " MB";
                default: return "see-through";
            }
        }

        /// <summary>Green (light) through yellow to red (heavy).</summary>
        internal static Color HeatColor(float heat)
        {
            heat = Mathf.Clamp01(heat);
            return heat < 0.5f
                ? Color.Lerp(new Color(0.2f, 0.85f, 0.35f), new Color(1f, 0.85f, 0.15f), heat * 2f)
                : Color.Lerp(new Color(1f, 0.85f, 0.15f), new Color(0.95f, 0.2f, 0.15f), (heat - 0.5f) * 2f);
        }

        // ---- Working out the values ---------------------------------------------------------------------------------

        /// <summary>Measured again when the scene changes (at most twice a second), not on every repaint.</summary>
        private static void Refresh()
        {
            int stamp = WPFMASceneStamp.Value;
            var mode = Current;
            if (!dirty && stamp == builtStamp && mode == builtMode)
                return;
            if (!dirty && mode == builtMode && EditorApplication.timeSinceStartup < nextBuild)
                return;

            dirty = false;
            builtStamp = stamp;
            builtMode = mode;
            nextBuild = EditorApplication.timeSinceStartup + 0.5;
            Build(mode);
        }

        private static void Build(Mode mode)
        {
            ClearBaked();
            entries.Clear();
            var textureBytes = new Dictionary<Texture, long>();

            foreach (var renderer in Object.FindObjectsByType<Renderer>(FindObjectsInactive.Exclude, FindObjectsSortMode.None))
            {
                if (renderer == null || !renderer.enabled || !renderer.gameObject.activeInHierarchy || !renderer.gameObject.scene.IsValid())
                    continue;

                Mesh mesh = null;
                bool baked = false;
                var skinned = renderer as SkinnedMeshRenderer;
                if (skinned != null)
                {
                    if (skinned.sharedMesh == null)
                        continue;
                    mesh = new Mesh { hideFlags = HideFlags.HideAndDontSave };
                    skinned.BakeMesh(mesh, true);
                    baked = true;
                }
                else if (renderer is MeshRenderer)
                {
                    var filter = renderer.GetComponent<MeshFilter>();
                    mesh = filter != null ? filter.sharedMesh : null;
                }
                if (mesh == null)
                    continue;

                double value;
                var source = skinned != null ? skinned.sharedMesh : mesh;
                switch (mode)
                {
                    case Mode.Triangles:
                        value = WPFMATriangleCounterSection.Triangles(source);
                        break;
                    case Mode.Materials:
                        value = renderer.sharedMaterials.Length;
                        break;
                    case Mode.TextureMemory:
                        value = TextureMemory(renderer, textureBytes);
                        break;
                    default:
                        value = renderer.sharedMaterials.Any(m => m != null && m.renderQueue >= 2500) ? 1 : 0;
                        break;
                }

                entries.Add(new Entry { Renderer = renderer, Mesh = mesh, Baked = baked, Value = value });
            }

            // The heaviest few percent are all full red, so one huge object doesn't turn everything else green.
            var values = entries.Where(e => e.Value > 0).Select(e => e.Value).OrderBy(v => v).ToList();
            cap = mode == Mode.SeeThrough || values.Count == 0 ? 1 : values[Mathf.Clamp((int)(values.Count * 0.95f), 0, values.Count - 1)];
            if (cap <= 0)
                cap = 1;
            foreach (var entry in entries)
                entry.Heat = entry.Value <= 0 ? 0f : Mathf.Clamp01((float)(entry.Value / cap));
            entries.Sort((a, b) => b.Value.CompareTo(a.Value));
        }

        private static double TextureMemory(Renderer renderer, Dictionary<Texture, long> sizes)
        {
            var seen = new HashSet<Texture>();
            double total = 0;
            foreach (var material in renderer.sharedMaterials)
            {
                if (material == null || material.shader == null)
                    continue;
                var shader = material.shader;
                for (int i = 0; i < shader.GetPropertyCount(); i++)
                {
                    if (shader.GetPropertyType(i) != UnityEngine.Rendering.ShaderPropertyType.Texture)
                        continue;
                    var texture = material.GetTexture(shader.GetPropertyNameId(i));
                    if (texture == null || !seen.Add(texture))
                        continue;
                    long bytes;
                    if (!sizes.TryGetValue(texture, out bytes))
                        sizes[texture] = bytes = WPFMATextureOptimizer.Size(texture);
                    total += bytes;
                }
            }
            return total;
        }

        private static void ClearBaked()
        {
            foreach (var entry in entries)
                if (entry.Baked && entry.Mesh != null)
                    Object.DestroyImmediate(entry.Mesh);
        }

        // ---- Drawing ------------------------------------------------------------------------------------------------

        private static void Draw(SceneView view)
        {
            if (!On || Event.current.type != EventType.Repaint || view.camera == null)
                return;

            Refresh();
            if (material == null)
            {
                material = new Material(Shader.Find("Hidden/Internal-Colored")) { hideFlags = HideFlags.HideAndDontSave };
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.SetInt("_ZTest", (int)UnityEngine.Rendering.CompareFunction.LessEqual);
                material.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Back);
                material.renderQueue = 3100;
            }
            if (block == null)
                block = new MaterialPropertyBlock();

            foreach (var entry in entries)
            {
                if (entry.Heat <= 0f || entry.Renderer == null || entry.Mesh == null)
                    continue;
                var color = HeatColor(entry.Heat);
                color.a = 0.5f;
                block.SetColor("_Color", color);
                var t = entry.Renderer.transform;
                var matrix = entry.Baked ? Matrix4x4.TRS(t.position, t.rotation, Vector3.one) : t.localToWorldMatrix;
                for (int sub = 0; sub < entry.Mesh.subMeshCount; sub++)
                    Graphics.DrawMesh(entry.Mesh, matrix, material, 0, view.camera, sub, block);
            }
        }

        /// <summary>The five heaviest get their number written on them.</summary>
        private static void Labels(SceneView view)
        {
            if (!On || Event.current.type != EventType.Repaint)
                return;
            var style = new GUIStyle(EditorStyles.whiteMiniLabel) { alignment = TextAnchor.MiddleCenter };
            var mode = Current;
            foreach (var entry in entries.Where(e => e.Renderer != null && e.Value > 0).Take(5))
                Handles.Label(entry.Renderer.bounds.center, Format(entry.Value, mode), style);
        }

        // ---- Controls (the Tools panel and the Scene view panel) ----------------------------------------------------

        internal static void DrawControls(bool compact)
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                bool on = GUILayout.Toggle(On, new GUIContent("Show", "Tint the Scene view by how heavy each object is."), GUILayout.Width(60f));
                if (on != On)
                    On = on;
                var mode = (Mode)EditorGUILayout.Popup((int)Current, ModeNames);
                if (mode != Current)
                    Current = mode;
            }

            if (!On)
                return;

            var list = Entries;
            var shown = list.Where(e => e.Renderer != null && e.Value > 0).ToList();

            // The legend: light to heavy.
            var bar = GUILayoutUtility.GetRect(0f, 8f, GUILayout.ExpandWidth(true));
            for (int i = 0; i < 20; i++)
                EditorGUI.DrawRect(new Rect(bar.x + bar.width * i / 20f, bar.y, bar.width / 20f + 1f, bar.height), HeatColor(i / 19f));
            using (new EditorGUILayout.HorizontalScope())
            {
                GUILayout.Label("light", EditorStyles.miniLabel);
                GUILayout.FlexibleSpace();
                GUILayout.Label(Current == Mode.SeeThrough ? "see-through" : Format(Cap, Current) + "+", EditorStyles.miniLabel);
            }

            if (shown.Count == 0)
            {
                GUILayout.Label(Current == Mode.SeeThrough ? "Nothing see-through." : "Nothing to show.", EditorStyles.miniLabel);
                return;
            }

            GUILayout.Label(new GUIContent("Heaviest of " + shown.Count, "Click a name to select it."), EditorStyles.miniBoldLabel);
            foreach (var entry in shown.Take(compact ? 5 : 10))
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    var dot = GUILayoutUtility.GetRect(8f, 14f, GUILayout.Width(8f));
                    EditorGUI.DrawRect(new Rect(dot.x, dot.y + 3f, 8f, 8f), HeatColor(entry.Heat));
                    if (GUILayout.Button(entry.Renderer.name, EditorStyles.miniLabel, GUILayout.MinWidth(80f)))
                    {
                        Selection.activeGameObject = entry.Renderer.gameObject;
                        EditorGUIUtility.PingObject(entry.Renderer.gameObject);
                    }
                    GUILayout.FlexibleSpace();
                    GUILayout.Label(Format(entry.Value, Current), EditorStyles.miniLabel);
                }
            }
        }
    }

    internal static class WPFMAHeatmapSection
    {
        private const string PrefKey = "WPFMA.Tools.HeatmapExpanded";

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Performance heatmap", WPFMAHeatmap.On ? WPFMAHeatmap.ModeNames[(int)WPFMAHeatmap.Current] : "off", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("See what's heavy, right in the Scene view.",
                    "Tints every visible mesh from green to red by its triangles, material slots, texture memory, or whether it's " +
                    "see-through (overdraw). Only the Scene view shows it - nothing in the scene changes."),
                WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);
            WPFMAHeatmap.DrawControls(false);
        }
    }

    /// <summary>The heatmap's controls in the Scene view, while it's on.</summary>
    [Overlay(typeof(SceneView), "wpfma-heatmap", "WPFMA Heatmap", true)]
    public sealed class WPFMAHeatmapOverlay : IMGUIOverlay, ITransientOverlay
    {
        public bool visible
        {
            get { return WPFMAHeatmap.On; }
        }

        public override void OnGUI()
        {
            using (new GUILayout.VerticalScope(GUILayout.Width(220f)))
                WPFMAHeatmap.DrawControls(true);
        }
    }
}
#endif
