// 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;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

#if WPFMA_VRC_AVATARS
using VRC.SDK3.Avatars.Components;
#endif

namespace WPFMA
{
    internal static class WPFMABlendshapeBaker
    {
        internal sealed class Shape
        {
            public int Index;
            public string Name;
            public float Weight;
            public bool Animated;
            public bool UsedByDescriptor;
            public bool Bake;
            /// <summary>Why it's kept even though nothing on the avatar animates it (null when it isn't).</summary>
            public string Kept;

            public bool Protected
            {
                get { return Animated || UsedByDescriptor || Kept != null; }
            }
        }

        internal static List<Shape> Inspect(GameObject root, SkinnedMeshRenderer renderer)
        {
            var shapes = new List<Shape>();
            var mesh = renderer != null ? renderer.sharedMesh : null;
            if (mesh == null)
                return shapes;

            var animated = AnimatedShapes(root, renderer);
            var reserved = DescriptorShapes(root, renderer);
            var addOns = WPFMAAvatarAnimations.Use(root).Shapes;

            for (int i = 0; i < mesh.blendShapeCount; i++)
            {
                string name = mesh.GetBlendShapeName(i);
                var shape = new Shape
                {
                    Index = i,
                    Name = name,
                    Weight = renderer.GetBlendShapeWeight(i),
                    Animated = animated.Contains(name),
                    UsedByDescriptor = reserved.Contains(name),
                    Kept = addOns.Contains(name) ? "Modular Avatar / VRCFury"
                        : WPFMAAvatarAnimations.MmdShapes.Contains(name) ? "MMD worlds"
                        : WPFMAAvatarAnimations.IsFaceTrackingShape(name) ? "face tracking"
                        : null
                };
                shape.Bake = Mathf.Abs(shape.Weight) > 0.001f && !shape.Protected;
                shapes.Add(shape);
            }

            return shapes;
        }

        internal static string Bake(GameObject root, SkinnedMeshRenderer renderer, List<Shape> shapes, bool removeUnusedZero)
        {
            var mesh = renderer.sharedMesh;
            var bake = new HashSet<int>(shapes.Where(s => s.Bake).Select(s => s.Index));
            var drop = new HashSet<int>(bake);

            if (removeUnusedZero)
            {
                foreach (var shape in shapes)
                {
                    if (Mathf.Abs(shape.Weight) <= 0.001f && !shape.Protected)
                        drop.Add(shape.Index);
                }
            }

            if (drop.Count == 0)
                return "Nothing ticked to bake or remove.";

            int count = mesh.vertexCount;
            var vertices = mesh.vertices;
            var normals = mesh.normals;
            var tangents = mesh.tangents;
            bool hasNormals = normals != null && normals.Length == count;
            bool hasTangents = tangents != null && tangents.Length == count;

            var dv = new Vector3[count];
            var dn = new Vector3[count];
            var dt = new Vector3[count];

            foreach (int index in bake)
            {
                float weight = renderer.GetBlendShapeWeight(index);
                AccumulateDelta(mesh, index, weight, dv, dn, dt, vertices, normals, tangents, hasNormals, hasTangents);
            }

            if (hasNormals)
            {
                for (int i = 0; i < count; i++)
                    normals[i] = normals[i].sqrMagnitude > 0f ? normals[i].normalized : normals[i];
            }

            var baked = UnityEngine.Object.Instantiate(mesh);
            baked.name = mesh.name + " (baked)";
            baked.ClearBlendShapes();
            baked.vertices = vertices;
            if (hasNormals)
                baked.normals = normals;
            if (hasTangents)
                baked.tangents = tangents;

            var keptWeights = new List<KeyValuePair<string, float>>();
            for (int shape = 0; shape < mesh.blendShapeCount; shape++)
            {
                if (drop.Contains(shape))
                    continue;

                string name = mesh.GetBlendShapeName(shape);
                int frames = mesh.GetBlendShapeFrameCount(shape);
                for (int frame = 0; frame < frames; frame++)
                {
                    mesh.GetBlendShapeFrameVertices(shape, frame, dv, dn, dt);
                    baked.AddBlendShapeFrame(name, mesh.GetBlendShapeFrameWeight(shape, frame), dv, dn, dt);
                }

                keptWeights.Add(new KeyValuePair<string, float>(name, renderer.GetBlendShapeWeight(shape)));
            }

            baked.RecalculateBounds();

            string folder = WPFMAAvatarFolders.For(root) + "/Baked Meshes";
            WPFMAAvatarFolders.Ensure(folder);
            string path = AssetDatabase.GenerateUniqueAssetPath(folder + "/" + WPFMAPaths.SafeFileName(baked.name) + ".asset");
            AssetDatabase.CreateAsset(baked, path);
            AssetDatabase.SaveAssets();

            Undo.SetCurrentGroupName("Bake blendshapes");
            int group = Undo.GetCurrentGroup();

            Undo.RecordObject(renderer, "Bake blendshapes");
            renderer.sharedMesh = baked;
            for (int i = 0; i < keptWeights.Count; i++)
                renderer.SetBlendShapeWeight(i, keptWeights[i].Value);
            PrefabUtility.RecordPrefabInstancePropertyModifications(renderer);

            FixDescriptorIndices(root, renderer, mesh, baked);

            Undo.CollapseUndoOperations(group);

            return "Baked " + bake.Count + " and removed " + (drop.Count - bake.Count) + " unused shape(s). " +
                   "New mesh: " + path + ". The original mesh is untouched.";
        }

        private static void AccumulateDelta(Mesh mesh, int shape, float weight, Vector3[] dv, Vector3[] dn, Vector3[] dt,
            Vector3[] vertices, Vector3[] normals, Vector4[] tangents, bool hasNormals, bool hasTangents)
        {
            int frames = mesh.GetBlendShapeFrameCount(shape);
            if (frames == 0 || Mathf.Abs(weight) < 0.0001f)
                return;

            int count = vertices.Length;
            var av = new Vector3[count];
            var an = new Vector3[count];
            var at = new Vector3[count];

            int lower, upper;
            float t;
            Pick(mesh, shape, weight, out lower, out upper, out t);

            mesh.GetBlendShapeFrameVertices(shape, lower, dv, dn, dt);
            Array.Copy(dv, av, count);
            Array.Copy(dn, an, count);
            Array.Copy(dt, at, count);

            if (upper != lower)
            {
                mesh.GetBlendShapeFrameVertices(shape, upper, dv, dn, dt);
                for (int i = 0; i < count; i++)
                {
                    av[i] = Vector3.LerpUnclamped(av[i], dv[i], t);
                    an[i] = Vector3.LerpUnclamped(an[i], dn[i], t);
                    at[i] = Vector3.LerpUnclamped(at[i], dt[i], t);
                }
            }
            else
            {
                for (int i = 0; i < count; i++)
                {
                    av[i] *= t;
                    an[i] *= t;
                    at[i] *= t;
                }
            }

            for (int i = 0; i < count; i++)
            {
                vertices[i] += av[i];
                if (hasNormals)
                    normals[i] += an[i];
                if (hasTangents)
                {
                    var tangent = tangents[i];
                    tangents[i] = new Vector4(tangent.x + at[i].x, tangent.y + at[i].y, tangent.z + at[i].z, tangent.w);
                }
            }
        }

        private static void Pick(Mesh mesh, int shape, float weight, out int lower, out int upper, out float t)
        {
            int frames = mesh.GetBlendShapeFrameCount(shape);
            float first = mesh.GetBlendShapeFrameWeight(shape, 0);

            if (frames == 1 || weight <= first)
            {
                lower = upper = 0;
                t = Mathf.Approximately(first, 0f) ? 0f : weight / first;
                return;
            }

            for (int frame = 0; frame < frames - 1; frame++)
            {
                float a = mesh.GetBlendShapeFrameWeight(shape, frame);
                float b = mesh.GetBlendShapeFrameWeight(shape, frame + 1);
                if (weight <= b)
                {
                    lower = frame;
                    upper = frame + 1;
                    t = Mathf.Approximately(a, b) ? 1f : (weight - a) / (b - a);
                    return;
                }
            }

            float last = mesh.GetBlendShapeFrameWeight(shape, frames - 1);
            lower = upper = frames - 1;
            t = Mathf.Approximately(last, 0f) ? 0f : weight / last;
        }

        private static HashSet<string> AnimatedShapes(GameObject root, SkinnedMeshRenderer renderer)
        {
            var names = new HashSet<string>();
            if (root == null)
                return names;

            // The avatar's own layers and Modular Avatar merges, each from the object its paths start from.
            foreach (var source in WPFMAAvatarAnimations.Sources(root, true))
            {
                if (renderer.transform != source.Base && !renderer.transform.IsChildOf(source.Base))
                    continue;

                string path = AnimationUtility.CalculateTransformPath(renderer.transform, source.Base);
                foreach (var clip in source.Clips)
                {
                    foreach (var binding in AnimationUtility.GetCurveBindings(clip))
                    {
                        if (binding.path == path && binding.type == typeof(SkinnedMeshRenderer) &&
                            binding.propertyName.StartsWith("blendShape."))
                            names.Add(binding.propertyName.Substring("blendShape.".Length));
                    }
                }
            }

            return names;
        }

        private static HashSet<string> DescriptorShapes(GameObject root, SkinnedMeshRenderer renderer)
        {
            var names = new HashSet<string>();
#if WPFMA_VRC_AVATARS
            var descriptor = root != null ? root.GetComponent<VRCAvatarDescriptor>() : null;
            if (descriptor == null || renderer.sharedMesh == null)
                return names;

            if (descriptor.VisemeSkinnedMesh == renderer && descriptor.VisemeBlendShapes != null)
            {
                foreach (var name in descriptor.VisemeBlendShapes)
                    if (!string.IsNullOrEmpty(name))
                        names.Add(name);
            }

            var eyes = descriptor.customEyeLookSettings;
            if (eyes.eyelidsSkinnedMesh == renderer && eyes.eyelidsBlendshapes != null)
            {
                foreach (int index in eyes.eyelidsBlendshapes)
                    if (index >= 0 && index < renderer.sharedMesh.blendShapeCount)
                        names.Add(renderer.sharedMesh.GetBlendShapeName(index));
            }
#endif
            return names;
        }

        private static void FixDescriptorIndices(GameObject root, SkinnedMeshRenderer renderer, Mesh before, Mesh after)
        {
#if WPFMA_VRC_AVATARS
            var descriptor = root != null ? root.GetComponent<VRCAvatarDescriptor>() : null;
            if (descriptor == null)
                return;

            var eyes = descriptor.customEyeLookSettings;
            if (eyes.eyelidsSkinnedMesh != renderer || eyes.eyelidsBlendshapes == null)
                return;

            Undo.RecordObject(descriptor, "Bake blendshapes");
            var remapped = eyes.eyelidsBlendshapes.Select(index =>
            {
                if (index < 0 || index >= before.blendShapeCount)
                    return -1;
                return after.GetBlendShapeIndex(before.GetBlendShapeName(index));
            }).ToArray();

            eyes.eyelidsBlendshapes = remapped;
            descriptor.customEyeLookSettings = eyes;
            EditorUtility.SetDirty(descriptor);
#endif
        }
    }

    internal static class WPFMABlendshapeBakerSection
    {
        private const string PrefKey = "WPFMA.Tools.BlendshapeBakerExpanded";

        private static SkinnedMeshRenderer renderer;
        private static GameObject root;
        private static List<WPFMABlendshapeBaker.Shape> shapes;
        private static bool removeUnusedZero { get { return WPFMAToolDefaults.BlendshapeRemoveZero; } set { WPFMAToolDefaults.BlendshapeRemoveZero = value; } }
        private static bool showAll;
        private static string status;
        private static Vector2 scroll;
        private static List<SkinnedMeshRenderer> options;
        private static string[] optionNames;
        private static string optionsKey;

        internal static void Draw(GUIStyle sectionStyle)
        {
            WPFMAToolSection.Draw(sectionStyle, "Blendshape baker", Detail(), PrefKey, Body);
        }

        private static string Detail()
        {
            return renderer == null ? "no mesh picked" : renderer.name;
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Bake unused slider shapes into the mesh.", "Bakes slider blendshapes you never animate (body shape, chest size, ear shape...) into the mesh and " + "removes them. The avatar looks the same but has fewer blendshapes. Works on a copy of the mesh."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var active = Selection.activeGameObject;
            var selectedRenderer = active != null && !EditorUtility.IsPersistent(active) ? active.GetComponent<SkinnedMeshRenderer>() : null;
            var avatar = WPFMAAvatarFolders.AvatarRoot(active);

            if (selectedRenderer != null && selectedRenderer != renderer)
                Pick(selectedRenderer, avatar);

            if (avatar != null)
            {
                // The avatar's meshes are listed again when the avatar or the scene changes, not on every repaint.
                string key = avatar.GetInstanceID() + "|" + WPFMASceneStamp.Value;
                if (options == null || key != optionsKey)
                {
                    optionsKey = key;
                    options = avatar.GetComponentsInChildren<SkinnedMeshRenderer>(true)
                        .Where(r => r.sharedMesh != null && r.sharedMesh.blendShapeCount > 0)
                        .ToList();
                    optionNames = options.Select(r => r.name + "  (" + r.sharedMesh.blendShapeCount + ")").ToArray();
                }

                if (options.Count > 0 && options.All(r => r != null))
                {
                    int index = Mathf.Max(0, options.IndexOf(renderer));
                    int picked = EditorGUILayout.Popup("Mesh", index, optionNames);
                    if (options[picked] != renderer)
                        Pick(options[picked], avatar);
                }
            }

            if (renderer == null || shapes == null)
            {
                EditorGUILayout.LabelField(new GUIContent("Select an avatar or a mesh.", "Select the avatar or a mesh with blendshapes in the Hierarchy."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            int nonZero = shapes.Count(s => Mathf.Abs(s.Weight) > 0.001f);
            EditorGUILayout.LabelField(shapes.Count + " blendshapes, " + nonZero + " set above 0.",
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            showAll = EditorGUILayout.ToggleLeft("Show shapes at 0 too", showAll);

            scroll = EditorGUILayout.BeginScrollView(scroll, GUILayout.MaxHeight(260f));
            foreach (var shape in shapes)
            {
                bool zero = Mathf.Abs(shape.Weight) <= 0.001f;
                if (zero && !showAll)
                    continue;

                using (new EditorGUILayout.HorizontalScope())
                {
                    using (new EditorGUI.DisabledScope(zero))
                        shape.Bake = EditorGUILayout.Toggle(shape.Bake && !zero, GUILayout.Width(16f));

                    EditorGUILayout.LabelField(shape.Name, WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
                    EditorGUILayout.LabelField(shape.Weight.ToString("0.#"), WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(40f));

                    string flag = shape.UsedByDescriptor ? "lip sync / blink" : shape.Animated ? "animated" : shape.Kept ?? string.Empty;
                    EditorGUILayout.LabelField(new GUIContent(flag, shape.Kept != null ? "Used by " + shape.Kept + ", so it is kept." : flag),
                        WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber), GUILayout.Width(140f));
                }
            }
            EditorGUILayout.EndScrollView();

            if (shapes.Any(s => s.Bake && s.Protected))
            {
                EditorGUILayout.LabelField(new GUIContent("Some ticked shapes are in use - baking freezes them.", "Some ticked shapes are animated, used for lip sync/blink, or used by Modular Avatar, VRCFury, MMD worlds " + "or face tracking. Baking them freezes them at their current value and breaks those."), WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
            }

            removeUnusedZero = EditorGUILayout.ToggleLeft(new GUIContent("Also remove unused shapes at 0",
                "Shapes at 0 that nothing animates. Smaller file, but they can't be used later."), removeUnusedZero);

            int bakeCount = shapes.Count(s => s.Bake);
            int dropCount = removeUnusedZero ? shapes.Count(s => Mathf.Abs(s.Weight) <= 0.001f && !s.Protected) : 0;

            using (new EditorGUI.DisabledScope(bakeCount + dropCount == 0))
            {
                if (GUILayout.Button("Bake " + bakeCount + (dropCount > 0 ? " and remove " + dropCount : string.Empty), GUILayout.Height(26f)))
                {
                    var target = renderer;
                    var avatarRoot = root;
                    var list = shapes;
                    bool remove = removeUnusedZero;
                    EditorApplication.delayCall += () =>
                    {
                        string folder = WPFMAAvatarFolders.For(avatarRoot) + "/Baked Meshes";
                        var before = WPFMAChangeLog.FilesIn(folder);
                        status = WPFMAChangeLog.Run("Blendshape baker", "Bake shapes on '" + target.name + "'", null, true,
                            () => WPFMABlendshapeBaker.Bake(avatarRoot, target, list, remove), () => WPFMAChangeLog.NewFiles(folder, before));
                        Debug.Log("[WPFMA-SDK] " + status);
                        Pick(target, avatarRoot);
                    };
                }
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
        }

        private static void Pick(SkinnedMeshRenderer picked, GameObject avatar)
        {
            renderer = picked;
            root = avatar != null ? avatar : picked.transform.root.gameObject;
            shapes = WPFMABlendshapeBaker.Inspect(root, renderer);
        }
    }
}
#endif
