// 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.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using UnityEngine.Experimental.Rendering;

namespace WPFMA.Vrca
{
    public static class WPFMAVrcaExporter
    {
        private static readonly string[] NormalMapHints = { "bumpmap", "normalmap", "normaltex", "_normal" };

        private const float MinimumShaderCoverage = 0.35f;

        private const int MaxReferenceDepth = 8;

        public const string RenamePrefKey = "WPFMA.VrcaRipper.RenameTo";
        public const string WriteReportPrefKey = "WPFMA.VrcaRipper.WriteReport";
        public const string FetchShadersPrefKey = "WPFMA.VrcaRipper.FetchShaders";
        public const string VerboseLogPrefKey = "WPFMA.VrcaRipper.VerboseLog";
        public const string ForceLayerWeightPrefKey = "WPFMA.VrcaRipper.ForceLayerWeight";

        public const string ClearBlueprintPrefKey = "WPFMA.VrcaRipper.ClearBlueprintId";

        public sealed class Report
        {
            public string PrefabPath;
            public int Meshes;
            public int Textures;
            public int Materials;
            public int Clips;
            public int ClipsWithCurves;
            public int CurvesRecovered;
            public int CurveBindingsUnresolved;
            public int Avatars;
            public int MissingScriptsStripped;
            public readonly List<string> Warnings = new List<string>();

            public string ReportPath;

            public readonly Dictionary<string, int> Components = new Dictionary<string, int>();

            public readonly List<string> MissingScriptPaths = new List<string>();

            public readonly Dictionary<string, int> References = new Dictionary<string, int>();

            public IEnumerable<KeyValuePair<string, int>> VrchatComponents
            {
                get { return Components.Where(c => c.Key.StartsWith("VRC", StringComparison.Ordinal)); }
            }

            public string Summary
            {
                get
                {
                    string clips = Clips + " clips";
                    if (CurvesRecovered > 0)
                    {
                        clips += " (" + ClipsWithCurves + " with " + CurvesRecovered + " recovered curves";
                        if (CurveBindingsUnresolved > 0)
                            clips += ", " + CurveBindingsUnresolved + " unmatched";
                        clips += ")";
                    }

                    return Meshes + " meshes, " + Textures + " textures, " + Materials + " materials, " +
                           clips + ", " + Avatars + " avatar(s)";
                }
            }
        }

        private sealed class SlotRecord
        {
            public UnityEngine.Object Target;
            public string PropertyPath;
            public string AssetPath;
        }

        private sealed class Context
        {
            public string Root;
            public Shader Override;
            public readonly System.Diagnostics.Stopwatch Clock = System.Diagnostics.Stopwatch.StartNew();
            public Report Report = new Report();
            public readonly Dictionary<Texture, Texture> Textures = new Dictionary<Texture, Texture>();
            public readonly Dictionary<Mesh, Mesh> Meshes = new Dictionary<Mesh, Mesh>();
            public readonly Dictionary<Material, Material> Materials = new Dictionary<Material, Material>();
            public readonly Dictionary<UnityEngine.Object, UnityEngine.Object> References =
                new Dictionary<UnityEngine.Object, UnityEngine.Object>();
            public readonly Dictionary<Type, MonoScript> ProjectScripts = new Dictionary<Type, MonoScript>();
            public readonly HashSet<string> UnresolvedTypes = new HashSet<string>();

            public WPFMASerializedFile Cab;

            public GameObject Instance;

            public Func<float, string, bool> Progress;

            public Dictionary<long, string> ClipNames;

            public readonly System.Diagnostics.Stopwatch StageClock = new System.Diagnostics.Stopwatch();
            public string StageLabel;

            public WPFMAAnimationClipDecoder Decoder;
            public bool DecoderBuilt;

            public Dictionary<long, Material> BundleMaterials;

            public readonly HashSet<UnityEngine.Object> ClearedReferences = new HashSet<UnityEngine.Object>();

            public readonly Dictionary<UnityEngine.Object, string> ReferencePaths =
                new Dictionary<UnityEngine.Object, string>();
            public readonly Dictionary<string, Shader> ShaderChoices = new Dictionary<string, Shader>();

            public readonly HashSet<string> ShaderFamilyNotes = new HashSet<string>();
            public List<Shader> Candidates;

            public List<string> WantedShaders;

            public readonly List<SlotRecord> PendingSlots = new List<SlotRecord>();
        }

        public static Report Export(string vrcaPath, string projectFolder, Shader shaderOverride, Func<float, string, bool> onProgress)
        {
            if (!projectFolder.Replace('\\', '/').StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
                throw new WPFMAVrcaException("The export folder has to be inside Assets/ so Unity can import the results.");

            AssetBundle bundle = null;

            bool borrowedBundle = false;
            GameObject instance = null;

            var context = new Context
            {
                Root = projectFolder.Replace('\\', '/').TrimEnd('/'),
                Override = shaderOverride
            };
            EnsureRootFitsPathLimit(context.Root, context);
            LogRipStart(vrcaPath, context, shaderOverride, "bundle");

            try
            {
                Step(onProgress, 0.01f, "Reading bundle structure");
                LoadSerializedCab(vrcaPath, context);

                Step(onProgress, 0.02f, "Opening bundle");

                bundle = AssetBundle.LoadFromFile(vrcaPath);
                if (bundle == null)
                {
                    bundle = WPFMAVrcaPreview.FindLoadedEquivalent(vrcaPath);
                    borrowedBundle = bundle != null;
                }

                if (bundle == null)
                {
                    WPFMAVrcaPreview.UnloadStrayBundles();
                    bundle = AssetBundle.LoadFromFile(vrcaPath);
                }

                if (bundle == null)
                    throw new WPFMAVrcaException("Unity could not open this bundle. It is either encrypted, built for another platform, or built with an incompatible Unity version.");

                if (bundle.isStreamedSceneAssetBundle)
                    throw new WPFMAVrcaException("This bundle holds a scene rather than a prefab, so there is nothing to export.");

                var source = bundle.LoadAllAssets<GameObject>().FirstOrDefault(g => g != null && g.transform.parent == null);
                if (source == null)
                    throw new WPFMAVrcaException("The bundle contains no root GameObject.");

                foreach (var folder in new[] { "Mesh", "Texture2D", "Material", "AnimationClip", "Avatar" })
                    EnsureFolder(context.Root + "/" + folder);

                instance = UnityEngine.Object.Instantiate(source);
                instance.name = source.name;

                RunPipeline(instance, context, onProgress);
                WriteRipReport(vrcaPath, context, bundle);
                return context.Report;
            }
            finally
            {
                if (instance != null)
                    UnityEngine.Object.DestroyImmediate(instance);
                if (bundle != null && !borrowedBundle)
                    bundle.Unload(true);

                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
            }
        }

        public static bool IsPreviewIntact(GameObject instance, out string reason)
        {
            reason = null;
            if (instance == null)
            {
                reason = "There is no preview in the scene to export.";
                return false;
            }

            int renderers = 0, lost = 0;
            foreach (var renderer in instance.GetComponentsInChildren<Renderer>(true))
            {
                if (renderer is ParticleSystemRenderer || renderer is TrailRenderer || renderer is LineRenderer)
                    continue;

                var skinned = renderer as SkinnedMeshRenderer;
                var filter = skinned == null ? renderer.GetComponent<MeshFilter>() : null;
                if (skinned == null && filter == null)
                    continue;

                renderers++;
                var mesh = skinned != null ? skinned.sharedMesh : filter.sharedMesh;
                if (mesh == null && renderer.sharedMaterials.All(m => m == null))
                    lost++;
            }

            if (renderers > 0 && lost * 2 >= renderers)
            {
                reason = "The preview in the scene has lost its meshes and materials (" + lost + " of " + renderers +
                         " renderers are empty). The bundle behind it was unloaded, which usually happens when another " +
                         "copy of the same .vrca is loaded.\n\nClear the preview, preview the .vrca again, then export.";
                return false;
            }

            return true;
        }

        public static Report ExportWorld(string vrcaPath, IList<GameObject> roots, string projectFolder,
            Shader shaderOverride, Func<float, string, bool> onProgress)
        {
            if (roots == null || roots.Count == 0)
                throw new WPFMAVrcaException("No scene objects to export. Load the world with Play scene first.");

            if (!projectFolder.Replace('\\', '/').StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
                throw new WPFMAVrcaException("The export folder has to be inside Assets/ so Unity can import the results.");

            var context = new Context
            {
                Root = projectFolder.Replace('\\', '/').TrimEnd('/'),
                Override = shaderOverride
            };
            EnsureRootFitsPathLimit(context.Root, context);

            try
            {
                LoadSerializedCab(vrcaPath, context);
            }
            catch (Exception e)
            {
                context.Report.Warnings.Add("The world's serialized data could not be read (" + e.Message +
                    "), so any animator graphs inside it are rebuilt from the runtime form only.");
            }

            foreach (var folder in new[] { "Mesh", "Texture2D", "Material", "AnimationClip", "Avatar" })
                EnsureFolder(context.Root + "/" + folder);
            LogRipStart(vrcaPath, context, shaderOverride, "world");

            var prefabPaths = new List<string>();

            try
            {
                for (int i = 0; i < roots.Count; i++)
                {
                    var root = roots[i];
                    if (root == null)
                        continue;

                    if (onProgress != null && !onProgress(i / (float)roots.Count, "Rebuilding " + root.name))
                        break;

                    var working = UnityEngine.Object.Instantiate(root);
                    working.name = root.name;
                    try
                    {
                        int split = WPFMAStaticBatch.Split(working, context.Report.Warnings);
                        if (split > 0)
                            Debug.Log("[WPFMA-SDK] '" + root.name + "': rebuilt " + split +
                                      " renderer(s) out of the scene's combined mesh.");

                        context.Report.PrefabPath = null;
                        RunPipeline(working, context, onProgress);
                        if (!string.IsNullOrEmpty(context.Report.PrefabPath))
                            prefabPaths.Add(context.Report.PrefabPath);
                    }
                    catch (Exception e)
                    {
                        context.Report.Warnings.Add("'" + root.name + "' could not be rebuilt: " + e.Message);
                    }
                    finally
                    {
                        UnityEngine.Object.DestroyImmediate(working);
                    }
                }

                WPFMAWorldScene.CaptureFromPlayMode(context.Root, Path.GetFileNameWithoutExtension(vrcaPath),
                    roots, prefabPaths, context.Report.Warnings);

                WriteRipReport(vrcaPath, context, null);
                return context.Report;
            }
            finally
            {
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
            }
        }

        public static Report ExportFromInstance(GameObject sceneInstance, string projectFolder, Shader shaderOverride, Func<float, string, bool> onProgress, string vrcaPath = null)
        {
            string intactReason;
            if (!IsPreviewIntact(sceneInstance, out intactReason))
                throw new WPFMAVrcaException(intactReason);

            if (string.IsNullOrEmpty(vrcaPath) || !File.Exists(vrcaPath))
                throw new WPFMAVrcaException(
                    "The .vrca behind this preview is no longer known, which usually means Unity reloaded " +
                    "scripts since it was loaded.\n\nWithout it the animator layers and animation curves " +
                    "cannot be rebuilt.\n\nClear the preview, preview the file again, then export.");
            if (!projectFolder.Replace('\\', '/').StartsWith("Assets/", StringComparison.OrdinalIgnoreCase))
                throw new WPFMAVrcaException("The export folder has to be inside Assets/ so Unity can import the results.");

            var context = new Context
            {
                Root = projectFolder.Replace('\\', '/').TrimEnd('/'),
                Override = shaderOverride
            };
            EnsureRootFitsPathLimit(context.Root, context);

            GameObject working = null;
            try
            {
                working = UnityEngine.Object.Instantiate(sceneInstance);
                working.name = sceneInstance.name;

                if (!string.IsNullOrEmpty(vrcaPath) && File.Exists(vrcaPath))
                    LoadSerializedCab(vrcaPath, context);

                foreach (var folder in new[] { "Mesh", "Texture2D", "Material", "AnimationClip", "Avatar" })
                    EnsureFolder(context.Root + "/" + folder);
                LogRipStart(vrcaPath, context, shaderOverride, "preview");

                RunPipeline(working, context, onProgress);
                WriteRipReport(vrcaPath, context, WPFMAVrcaPreview.GetLoadedBundle(vrcaPath));
                return context.Report;
            }
            finally
            {
                if (working != null)
                    UnityEngine.Object.DestroyImmediate(working);

                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
            }
        }

        private static void EnsureFolder(string path)
        {
            path = path.Replace('\\', '/').TrimEnd('/');
            if (string.IsNullOrEmpty(path) || AssetDatabase.IsValidFolder(path))
                return;

            int slash = path.LastIndexOf('/');
            if (slash <= 0)
                return;

            string parent = path.Substring(0, slash);
            EnsureFolder(parent);

            if (Directory.Exists(path))
            {
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
                if (AssetDatabase.IsValidFolder(path))
                    return;
            }

            AssetDatabase.CreateFolder(parent, path.Substring(slash + 1));
        }

        private static void RunPipeline(GameObject instance, Context context, Func<float, string, bool> onProgress)
        {
            var previousSelection = Selection.objects;
            Selection.objects = new UnityEngine.Object[0];
            context.Instance = instance;
            context.Progress = onProgress;

            try
            {
                Stage(context, 0.1f, "Recovering textures");
                ExportTextures(instance, context, onProgress);

                Stage(context, 0.6f, "Writing meshes");
                ExportMeshes(instance, context);

                ReportRequiredPackages(context);

                context.WantedShaders = SourceShaderNames(instance);

                if (EditorPrefs.GetBool(FetchShadersPrefKey, true))
                {
                    Stage(context, 0.70f, "Checking shaders");
                    WPFMAShaderFetch.EnsureInstalled(context.WantedShaders, context.Root, context.Report.Warnings);
                }

                Stage(context, 0.72f, "Rebuilding materials");
                ExportMaterials(instance, context);

                Stage(context, 0.9f, "Rebinding scripts");
                foreach (var component in instance.GetComponentsInChildren<Component>(true))
                {
                    try
                    {
                        RebindScript(component, context);
                    }
                    catch (Exception e)
                    {
                        context.Report.Warnings.Add("Script rebind failed on '" +
                            (component != null ? component.GetType().Name : "<destroyed>") + "': " + e.Message);
                    }
                }

                Stage(context, 0.92f, "Writing animation");
                ExportAnimation(instance, context);

                Stage(context, 0.93f, "Saving component references");
                ExportComponentReferences(instance, context);

                Stage(context, 0.95f, "Verifying script bindings");
                AssetDatabase.SaveAssets();
                RepairScriptBindings(context);

                Stage(context, 0.96f, "Saving prefab");
                RestoreComponentReferences(context);
                ApplyIdentityOptions(instance, context);
                UseDefaultLocomotion(instance, context);
                SavePrefab(instance, context);

                Stage(context, 0.98f, "Verifying prefab references");
                ReconcilePrefab(instance, context);

                Stage(context, 0.99f, "Checking shaders again");
                RecheckShaders(context);

                ForceLayerWeights(context);
            }
            finally
            {
                EndStage(context);
                Selection.objects = previousSelection;
            }
        }

        private static void ReportRequiredPackages(Context context)
        {
            if (context.Cab == null)
                return;

            try
            {
                var missing = WPFMARequiredPackages.Missing(context.Cab);
                if (missing.Count == 0)
                    return;

                foreach (var requirement in missing)
                {
                    context.Report.Warnings.Add("Missing package: " + requirement.Describe() +
                                                ". Those components cannot be restored without it.");
                }

                Debug.LogWarning("[WPFMA-SDK] This avatar uses " + missing.Count +
                                 " package(s) this project does not have:\n   " +
                                 string.Join("\n   ", missing.Select(r => r.Describe()).ToArray()) +
                                 "\n\nInstall them and export again to keep those components.");
            }
            catch (Exception e)
            {
                context.Report.Warnings.Add("Could not work out which packages this avatar needs: " + e.Message);
            }
        }

        /// <summary>
        /// The descriptor's Base playable layer (idle, walk, run, crouch, prone) goes back to VRChat's own default, instead
        /// of the controller that came with the file. Read by name, so this works without the avatar SDK's types.
        /// </summary>
        private static void UseDefaultLocomotion(GameObject instance, Context context)
        {
            if (instance == null)
                return;

            foreach (var component in instance.GetComponentsInChildren<Component>(true))
            {
                if (component == null || component.GetType().Name != "VRCAvatarDescriptor")
                    continue;

                var serialized = new SerializedObject(component);
                var layers = serialized.FindProperty("baseAnimationLayers");
                if (layers == null || !layers.isArray)
                    continue;

                for (int i = 0; i < layers.arraySize; i++)
                {
                    var layer = layers.GetArrayElementAtIndex(i);
                    var type = layer.FindPropertyRelative("type");
                    if (type == null || type.intValue != 0)
                        continue;

                    var isDefault = layer.FindPropertyRelative("isDefault");
                    var controller = layer.FindPropertyRelative("animatorController");
                    var mask = layer.FindPropertyRelative("mask");
                    if (isDefault != null)
                        isDefault.boolValue = true;
                    if (controller != null)
                        controller.objectReferenceValue = null;
                    if (mask != null)
                        mask.objectReferenceValue = null;
                }

                serialized.ApplyModifiedPropertiesWithoutUndo();
                context.Report.Warnings.Add("The Base layer (idle, walk, run) uses VRChat's default animations.");
            }
        }

        private static void ForceLayerWeights(Context context)
        {
            if (!EditorPrefs.GetBool(ForceLayerWeightPrefKey, false) || context.Instance == null)
                return;

            int changed = 0;
            var touched = new HashSet<string>();

            foreach (var animator in context.Instance.GetComponentsInChildren<Animator>(true))
            {
                var controller = animator != null
                    ? animator.runtimeAnimatorController as UnityEditor.Animations.AnimatorController
                    : null;

                if (controller == null)
                    continue;

                var layers = controller.layers;
                bool dirty = false;

                for (int i = 0; i < layers.Length; i++)
                {
                    if (layers[i] == null || layers[i].defaultWeight > 0f)
                        continue;

                    layers[i].defaultWeight = 1f;
                    dirty = true;
                    changed++;
                    touched.Add(controller.name + " / " + layers[i].name);
                }

                if (dirty)
                {
                    controller.layers = layers;
                    EditorUtility.SetDirty(controller);
                }
            }

            if (changed == 0)
                return;

            AssetDatabase.SaveAssets();
            context.Report.Warnings.Add("Forced " + changed + " layer weight(s) from 0 to 1 on export: " +
                                        string.Join(", ", new List<string>(touched).ToArray()) +
                                        ". This overrides what the avatar shipped with.");

            Debug.Log("[WPFMA-SDK] Forced " + changed + " layer weight(s) to 1.");
        }

        private static void RecheckShaders(Context context)
        {
            if (!EditorPrefs.GetBool(FetchShadersPrefKey, true) || context.WantedShaders == null)
                return;

            int installed = WPFMAShaderFetch.EnsureInstalled(
                context.WantedShaders, context.Root, context.Report.Warnings);

            if (installed == 0)
                return;

            context.ShaderChoices.Clear();
            context.Candidates = null;

            int rebound = 0;
            foreach (var pair in context.Materials)
            {
                var source = pair.Key;
                var exported = pair.Value;
                if (source == null || exported == null || source.shader == null)
                    continue;

                var resolved = ResolveShader(source, context);
                if (resolved == null || exported.shader == resolved)
                    continue;

                exported.shader = resolved;

                BindTexturesByRole(source, source.shader, exported, context);

                EditorUtility.SetDirty(exported);
                rebound++;
            }

            if (rebound > 0)
            {
                AssetDatabase.SaveAssets();
                context.Report.Warnings.Add("Installed " + installed + " shader package(s) after the rebuild and " +
                                            "moved " + rebound + " material(s) onto them.");
                Debug.Log("[WPFMA-SDK] Archive filled in " + installed + " shader package(s) late; " +
                          rebound + " material(s) rebound to the real shaders.");
            }
        }

        private static void ReconcilePrefab(GameObject instance, Context context)
        {
            if (string.IsNullOrEmpty(context.Report.PrefabPath))
                return;

            var prefab = AssetDatabase.LoadAssetAtPath<GameObject>(context.Report.PrefabPath);
            if (prefab == null)
                return;

            var sourceComponents = instance.GetComponentsInChildren<Component>(true);
            var prefabComponents = prefab.GetComponentsInChildren<Component>(true);
            if (sourceComponents.Length != prefabComponents.Length)
            {
                context.Report.Warnings.Add("Post-save verification skipped: component counts diverged (" +
                    sourceComponents.Length + " vs " + prefabComponents.Length + ").");
                return;
            }

            int repaired = 0;
            bool dirty = false;

            for (int i = 0; i < sourceComponents.Length; i++)
            {
                if (sourceComponents[i] == null || prefabComponents[i] == null)
                    continue;

                var source = new SerializedObject(sourceComponents[i]);
                var target = new SerializedObject(prefabComponents[i]);
                var property = source.GetIterator();
                bool changed = false;

                while (property.NextVisible(true))
                {
                    if (property.propertyType != SerializedPropertyType.ObjectReference)
                        continue;

                    var wanted = property.objectReferenceValue;
                    if (wanted == null || wanted is Component || wanted is GameObject)
                        continue;
                    if (string.IsNullOrEmpty(AssetDatabase.GetAssetPath(wanted)))
                        continue;

                    var slot = target.FindProperty(property.propertyPath);
                    if (slot == null || slot.objectReferenceValue != null)
                        continue;

                    slot.objectReferenceValue = wanted;
                    changed = true;
                    repaired++;
                }

                if (changed)
                {
                    target.ApplyModifiedPropertiesWithoutUndo();
                    dirty = true;
                }
            }

            if (dirty)
            {
                AssetDatabase.SaveAssets();
                context.Report.Warnings.Add("Post-save check restored " + repaired +
                    " reference(s) that were lost while the prefab was being written.");
            }
        }

        private static void LogRipStart(string vrcaPath, Context context, Shader shaderOverride, string kind)
        {
            var info = new FileInfo(vrcaPath);
            Debug.Log("[WPFMA-SDK] ===== Rip started (" + kind + ") =====" +
                      "\n  source: " + vrcaPath +
                      (info.Exists ? "  (" + (info.Length / 1048576f).ToString("0.0") + " MB)" : string.Empty) +
                      "\n  output: " + context.Root +
                      (shaderOverride != null
                          ? "\n  shader: every material rebuilt on " + shaderOverride.name
                          : "\n  shader: each material matched to the closest installed shader"));
        }

        private static void LogRipFinished(Context context)
        {
            var report = context.Report;
            Debug.Log("[WPFMA-SDK] ===== Rip finished in " +
                      (context.Clock.ElapsedMilliseconds / 1000f).ToString("0.0") + " s =====" +
                      "\n  " + report.Summary +
                      "\n  warnings: " + report.Warnings.Count +
                      (report.PrefabPath != null ? "\n  prefab: " + report.PrefabPath : string.Empty) +
                      (report.ReportPath != null ? "\n  report: " + report.ReportPath : string.Empty));
        }

        private static void LoadSerializedCab(string vrcaPath, Context context)
        {
            try
            {
                using (var stream = new FileStream(vrcaPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    var container = WPFMAVrcaBundle.Open(stream);
                    if (container.UsesContentEncryption)
                        return;

                    foreach (var node in container.Nodes)
                    {
                        if ((node.Flags & 4) == 0)
                            continue;

                        context.Cab = WPFMASerializedFile.Parse(container.ExtractNodeBytes(stream, node));
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                context.Report.Warnings.Add("Could not read the bundle's serialized data (" + e.Message +
                    "); animator state machines will not be rebuilt.");
            }
        }

        private static void WriteRipReport(string vrcaPath, Context context, AssetBundle openBundle)
        {
            if (!EditorPrefs.GetBool(WriteReportPrefKey, true))
            {
                LogRipFinished(context);
                return;
            }

            if (string.IsNullOrEmpty(vrcaPath) || !File.Exists(vrcaPath))
            {
                context.Report.Warnings.Add("No export report written — the source .vrca could not be located" +
                    (string.IsNullOrEmpty(vrcaPath) ? "." : " at " + vrcaPath + "."));
                return;
            }

            try
            {
                string written = WPFMARipReport.Generate(vrcaPath,
                    context.Root + "/export report.txt", null, openBundle);

                context.Report.ReportPath = written;
                LogRipFinished(context);
            }
            catch (Exception e)
            {
                context.Report.Warnings.Add("Could not write the export report: " + e.Message);
                Debug.LogWarning("[WPFMA-SDK] Could not write the export report: " + e.Message);
            }
        }

        private static void ApplyIdentityOptions(GameObject instance, Context context)
        {
            string rename = EditorPrefs.GetString(RenamePrefKey, string.Empty).Trim();
            if (!string.IsNullOrEmpty(rename))
            {
                context.Report.Warnings.Add("Renamed the avatar from '" + instance.name + "' to '" + rename + "'.");
                instance.name = rename;
            }

            if (!EditorPrefs.GetBool(ClearBlueprintPrefKey, true))
                return;

            foreach (var component in instance.GetComponentsInChildren<Component>(true))
            {
                if (component == null || component.GetType().Name != "PipelineManager")
                    continue;

                var serialized = new SerializedObject(component);
                var blueprint = serialized.FindProperty("blueprintId");
                if (blueprint == null || string.IsNullOrEmpty(blueprint.stringValue))
                    continue;

                context.Report.Warnings.Add("Cleared the blueprint ID (" + blueprint.stringValue +
                    ") so this exports as a new avatar rather than an update to an existing one.");

                blueprint.stringValue = string.Empty;
                serialized.ApplyModifiedPropertiesWithoutUndo();
            }
        }

        private static void Stage(Context context, float fraction, string label)
        {
            EndStage(context);
            context.StageLabel = label;
            context.StageClock.Reset();
            context.StageClock.Start();
            if (EditorPrefs.GetBool(VerboseLogPrefKey, true))
                Debug.Log("[WPFMA-SDK] Rip step: " + label + "...");

            Step(context.Progress, fraction, label);
        }

        private static void EndStage(Context context)
        {
            if (string.IsNullOrEmpty(context.StageLabel))
                return;

            if (EditorPrefs.GetBool(VerboseLogPrefKey, true))
                Debug.Log("[WPFMA-SDK] Rip step finished: " + context.StageLabel + " (" +
                          (context.StageClock.ElapsedMilliseconds / 1000f).ToString("0.0") + " s)");

            context.StageLabel = null;
        }

        private static void Step(Func<float, string, bool> onProgress, float fraction, string label)
        {
            if (onProgress != null && !onProgress(fraction, label))
                throw new OperationCanceledException();
        }

        private static void ExportTextures(GameObject instance, Context context, Func<float, string, bool> onProgress)
        {
            var slots = new List<KeyValuePair<Material, string>>();
            foreach (var material in EnumerateMaterials(instance))
            {
                if (material.shader == null)
                    continue;

                foreach (var property in material.GetTexturePropertyNames())
                {
                    if (material.GetTexture(property) != null)
                        slots.Add(new KeyValuePair<Material, string>(material, property));
                }
            }

            var distinct = new List<KeyValuePair<Texture, bool>>();
            var seen = new HashSet<Texture>();
            foreach (var slot in slots)
            {
                var texture = slot.Key.GetTexture(slot.Value);
                if (texture == null || !seen.Add(texture))
                    continue;

                distinct.Add(new KeyValuePair<Texture, bool>(texture, IsNormalMapSlot(slot.Value)));
            }

            for (int i = 0; i < distinct.Count; i++)
            {
                var texture = distinct[i].Key;
                Step(onProgress, 0.1f + 0.5f * i / Math.Max(1, distinct.Count),
                    "Texture " + (i + 1) + " of " + distinct.Count + "  —  " + texture.name);

                var flat = texture as Texture2D;
                var cube = texture as Cubemap;
                if (flat == null && cube == null)
                {
                    context.Report.Warnings.Add("Skipped '" + texture.name + "' (" + texture.GetType().Name + " is not supported).");
                    continue;
                }

                try
                {
                    context.Textures[texture] = flat != null
                        ? (Texture)RecoverTexture(flat, context, distinct[i].Value)
                        : RecoverCubemap(cube, context);
                    context.Report.Textures++;
                }
                catch (Exception e)
                {
                    context.Report.Warnings.Add("Could not recover texture '" + texture.name + "': " + e.Message);
                }
            }
        }

        private static Cubemap RecoverCubemap(Cubemap source, Context context)
        {
            var faceShader = Shader.Find("Hidden/WPFMA-SDK/Cubemap Face");
            if (faceShader == null)
                throw new WPFMAVrcaException("The cubemap face shader is missing from the SDK, so cubemaps cannot be recovered.");

            int size = source.width;
            var recovered = new Cubemap(size, TextureFormat.RGBA32, false) { name = source.name };
            var blitter = new Material(faceShader) { hideFlags = HideFlags.HideAndDontSave };
            var target = RenderTexture.GetTemporary(size, size, 0, RenderTextureFormat.ARGB32,
                IsColourTexture(source) ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear);
            var readback = new Texture2D(size, size, TextureFormat.RGBA32, false);
            var previous = RenderTexture.active;

            try
            {
                blitter.SetTexture("_Cube", source);
                for (int face = 0; face < 6; face++)
                {
                    blitter.SetFloat("_Face", face);
                    Graphics.Blit(Texture2D.whiteTexture, target, blitter);
                    RenderTexture.active = target;
                    readback.ReadPixels(new Rect(0f, 0f, size, size), 0, 0);
                    readback.Apply();

                    recovered.SetPixels(readback.GetPixels(), (CubemapFace)face);
                }

                recovered.Apply();
            }
            finally
            {
                RenderTexture.active = previous;
                RenderTexture.ReleaseTemporary(target);
                UnityEngine.Object.DestroyImmediate(readback);
                UnityEngine.Object.DestroyImmediate(blitter);
            }

            Directory.CreateDirectory(context.Root + "/Cubemap");
            string path = AssetDatabase.GenerateUniqueAssetPath(context.Root + "/Cubemap/" + Sanitize(source.name) + ".cubemap");
            AssetDatabase.CreateAsset(recovered, path);
            context.ReferencePaths[source] = path;
            return recovered;
        }

        private static bool IsColourTexture(Texture source)
        {
            try
            {
                return GraphicsFormatUtility.IsSRGBFormat(source.graphicsFormat);
            }
            catch (Exception)
            {
                return true;
            }
        }

        private static Texture2D RecoverTexture(Texture2D source, Context context, bool isNormalMap)
        {
            bool colour = IsColourTexture(source);
            var target = RenderTexture.GetTemporary(source.width, source.height, 0,
                RenderTextureFormat.ARGB32, colour ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear);

            var previous = RenderTexture.active;
            byte[] png;

            try
            {
                Graphics.Blit(source, target);
                RenderTexture.active = target;

                var readback = new Texture2D(source.width, source.height, TextureFormat.RGBA32, false);
                readback.ReadPixels(new Rect(0f, 0f, source.width, source.height), 0, 0);
                readback.Apply();
                png = readback.EncodeToPNG();
                UnityEngine.Object.DestroyImmediate(readback);
            }
            finally
            {
                RenderTexture.active = previous;
                RenderTexture.ReleaseTemporary(target);
            }

            string path = AssetDatabase.GenerateUniqueAssetPath(context.Root + "/Texture2D/" + Sanitize(source.name) + ".png");
            File.WriteAllBytes(path, png);

            WPFMATextureImportRules.Register(path, new WPFMATextureImportRules.Rule
            {
                NormalMap = isNormalMap,
                Colour = colour,
                SourceSize = Math.Max(source.width, source.height)
            });

            try
            {
                AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
            }
            finally
            {
                WPFMATextureImportRules.Forget(path);
            }

            var importer = AssetImporter.GetAtPath(path) as TextureImporter;
            if (importer != null)
            {
                bool changed = false;

                if (isNormalMap && importer.textureType != TextureImporterType.NormalMap)
                {
                    importer.textureType = TextureImporterType.NormalMap;
                    changed = true;
                }

                if (!isNormalMap && importer.sRGBTexture != colour)
                {
                    importer.sRGBTexture = colour;
                    changed = true;
                }

                if (colour && !importer.alphaIsTransparency)
                {
                    importer.alphaIsTransparency = true;
                    changed = true;
                }

                if (Math.Max(source.width, source.height) > importer.maxTextureSize)
                {
                    importer.maxTextureSize = Mathf.NextPowerOfTwo(Math.Max(source.width, source.height));
                    changed = true;
                }

                if (importer.mipmapEnabled && !importer.streamingMipmaps)
                {
                    importer.streamingMipmaps = true;
                    importer.streamingMipmapsPriority = 0;
                    changed = true;
                }

                if (changed)
                {
                    importer.SaveAndReimport();
                }
            }

            context.ReferencePaths[source] = path;
            return AssetDatabase.LoadAssetAtPath<Texture2D>(path);
        }

        private static List<string> SourceShaderNames(GameObject instance)
        {
            var names = new List<string>();
            if (instance == null)
                return names;

            foreach (var renderer in instance.GetComponentsInChildren<Renderer>(true))
            {
                if (renderer == null)
                    continue;

                foreach (var material in renderer.sharedMaterials)
                {
                    if (material != null && material.shader != null)
                        names.Add(material.shader.name);
                }
            }

            return names;
        }

        private static bool IsNormalMapSlot(string propertyName)
        {
            string lowered = propertyName.ToLowerInvariant();
            foreach (var hint in NormalMapHints)
            {
                if (lowered.Contains(hint))
                    return true;
            }

            return false;
        }

        private static void ExportMeshes(GameObject instance, Context context)
        {
            foreach (var renderer in instance.GetComponentsInChildren<SkinnedMeshRenderer>(true))
                renderer.sharedMesh = PersistMesh(renderer.sharedMesh, context);

            foreach (var filter in instance.GetComponentsInChildren<MeshFilter>(true))
                filter.sharedMesh = PersistMesh(filter.sharedMesh, context);

            foreach (var collider in instance.GetComponentsInChildren<MeshCollider>(true))
                collider.sharedMesh = PersistMesh(collider.sharedMesh, context);
        }

        private static Mesh PersistMesh(Mesh source, Context context)
        {
            if (source == null)
                return null;

            Mesh existing;
            if (context.Meshes.TryGetValue(source, out existing))
                return existing != null ? existing : Resurrect(source, context) as Mesh;

            var copy = UnityEngine.Object.Instantiate(source);
            copy.name = source.name;

            string path = AssetDatabase.GenerateUniqueAssetPath(context.Root + "/Mesh/" + Sanitize(source.name) + ".asset");
            AssetDatabase.CreateAsset(copy, path);

            context.Meshes[source] = copy;
            context.ReferencePaths[source] = path;
            context.Report.Meshes++;
            return copy;
        }

        private static void ExportMaterials(GameObject instance, Context context)
        {
            foreach (var renderer in instance.GetComponentsInChildren<Renderer>(true))
            {
                var rebuilt = renderer.sharedMaterials;
                for (int i = 0; i < rebuilt.Length; i++)
                    rebuilt[i] = PersistMaterial(rebuilt[i], context);

                renderer.sharedMaterials = rebuilt;
            }
        }

        private static Material PersistMaterial(Material source, Context context)
        {
            if (source == null)
                return null;

            Material existing;
            if (context.Materials.TryGetValue(source, out existing))
                return existing != null ? existing : Resurrect(source, context) as Material;

            var sourceShader = source.shader;
            var target = ResolveShader(source, context);

            var copy = new Material(target) { name = source.name };
            int carried = 0;
            int dropped = 0;

            if (sourceShader != null)
            {
                int count = sourceShader.GetPropertyCount();
                for (int i = 0; i < count; i++)
                {
                    string name = sourceShader.GetPropertyName(i);
                    var type = sourceShader.GetPropertyType(i);

                    if (!copy.HasProperty(name))
                    {
                        dropped++;
                        continue;
                    }

                    switch (type)
                    {
                        case UnityEngine.Rendering.ShaderPropertyType.Texture:
                            var texture = source.GetTexture(name);
                            Texture recovered = null;
                            if (texture != null)
                                context.Textures.TryGetValue(texture, out recovered);
                            if (texture != null && recovered == null)
                                recovered = Resurrect(texture, context) as Texture;
                            if (recovered != null)
                                copy.SetTexture(name, recovered);
                            copy.SetTextureOffset(name, source.GetTextureOffset(name));
                            copy.SetTextureScale(name, source.GetTextureScale(name));
                            break;

                        case UnityEngine.Rendering.ShaderPropertyType.Color:
                            copy.SetColor(name, source.GetColor(name));
                            break;

                        case UnityEngine.Rendering.ShaderPropertyType.Vector:
                            copy.SetVector(name, source.GetVector(name));
                            break;

                        case UnityEngine.Rendering.ShaderPropertyType.Float:
                        case UnityEngine.Rendering.ShaderPropertyType.Range:
                            copy.SetFloat(name, source.GetFloat(name));
                            break;

                        default:
                            dropped++;
                            continue;
                    }

                    carried++;
                }
            }

            int rebound = BindTexturesByRole(source, sourceShader, copy, context);

            copy.renderQueue = source.renderQueue;
            foreach (var keyword in source.shaderKeywords)
                copy.EnableKeyword(keyword);

            string path = AssetDatabase.GenerateUniqueAssetPath(context.Root + "/Material/" + Sanitize(source.name) + ".mat");
            AssetDatabase.CreateAsset(copy, path);

            if (dropped > carried && sourceShader != null)
            {
                context.Report.Warnings.Add("'" + source.name + "' kept " + carried + " of " + (carried + dropped) +
                    " properties moving from '" + sourceShader.name + "' to '" + target.name + "'" +
                    (rebound > 0 ? ", and " + rebound + " texture(s) were matched to '" + target.name +
                                   "' slots by what they are rather than by name." : "."));
            }

            context.Materials[source] = copy;
            context.ReferencePaths[source] = path;
            context.Report.Materials++;
            return copy;
        }

        private enum TextureRole
        {
            Albedo,
            Normal,
            MetallicOrSpecular,
            Occlusion,
            Emission,
            Height,
            Detail,
            Unknown
        }

        private static TextureRole RoleOf(string propertyName)
        {
            string name = propertyName.ToLowerInvariant();

            if (name.Contains("detail")) return TextureRole.Detail;
            if (name.Contains("normal") || name.Contains("bump")) return TextureRole.Normal;
            if (name.Contains("emis") || name.Contains("glow")) return TextureRole.Emission;
            if (name.Contains("occlusion") || name.EndsWith("_ao") || name.Contains("ambientocclusion"))
                return TextureRole.Occlusion;
            if (name.Contains("metallic") || name.Contains("specular") || name.Contains("smoothness") ||
                name.Contains("gloss") || name.Contains("roughness") || name.Contains("mask"))
                return TextureRole.MetallicOrSpecular;
            if (name.Contains("parallax") || name.Contains("height") || name.Contains("displace"))
                return TextureRole.Height;
            if (name.Contains("albedo") || name.Contains("basecolor") || name.Contains("base_color") ||
                name.Contains("diffuse") || name.Contains("maintex") || name.Contains("color") ||
                name.Contains("texturesample") || name.Contains("_tex"))
                return TextureRole.Albedo;

            return TextureRole.Unknown;
        }

        private static int BindTexturesByRole(Material source, Shader sourceShader, Material copy, Context context)
        {
            if (sourceShader == null || copy.shader == null)
                return 0;

            var available = new List<KeyValuePair<TextureRole, Texture>>();
            var alreadyBound = new HashSet<int>();

            int sourceCount = sourceShader.GetPropertyCount();
            for (int i = 0; i < sourceCount; i++)
            {
                if (sourceShader.GetPropertyType(i) != UnityEngine.Rendering.ShaderPropertyType.Texture)
                    continue;

                string name = sourceShader.GetPropertyName(i);
                var texture = source.GetTexture(name);
                if (texture == null)
                    continue;

                Texture recovered;
                if (!context.Textures.TryGetValue(texture, out recovered) || recovered == null)
                    recovered = Resurrect(texture, context) as Texture;
                if (recovered == null)
                    continue;

                if (copy.HasProperty(name) && copy.GetTexture(name) == recovered)
                {
                    alreadyBound.Add(recovered.GetInstanceID());
                    continue;
                }

                available.Add(new KeyValuePair<TextureRole, Texture>(RoleOf(name), recovered));
            }

            if (available.Count == 0)
                return 0;

            int bound = 0;
            var used = new HashSet<int>(alreadyBound);
            var targetShader = copy.shader;
            int targetCount = targetShader.GetPropertyCount();

            for (int i = 0; i < targetCount; i++)
            {
                if (targetShader.GetPropertyType(i) != UnityEngine.Rendering.ShaderPropertyType.Texture)
                    continue;

                string slot = targetShader.GetPropertyName(i);
                if (copy.GetTexture(slot) != null)
                    continue;

                var wanted = RoleOf(slot);
                if (wanted == TextureRole.Unknown)
                    continue;

                foreach (var candidate in available)
                {
                    if (candidate.Key != wanted || used.Contains(candidate.Value.GetInstanceID()))
                        continue;

                    copy.SetTexture(slot, candidate.Value);
                    copy.SetTextureOffset(slot, Vector2.zero);
                    copy.SetTextureScale(slot, Vector2.one);
                    used.Add(candidate.Value.GetInstanceID());
                    bound++;
                    EnableSlotKeyword(copy, slot);
                    break;
                }
            }

            return bound;
        }

        private static void EnableSlotKeyword(Material material, string slot)
        {
            switch (slot)
            {
                case "_BumpMap":
                    material.EnableKeyword("_NORMALMAP");
                    break;
                case "_MetallicGlossMap":
                    material.EnableKeyword("_METALLICGLOSSMAP");
                    break;
                case "_SpecGlossMap":
                    material.EnableKeyword("_SPECGLOSSMAP");
                    break;
                case "_ParallaxMap":
                    material.EnableKeyword("_PARALLAXMAP");
                    break;
                case "_EmissionMap":
                    material.EnableKeyword("_EMISSION");
                    break;
                case "_DetailAlbedoMap":
                case "_DetailNormalMap":
                    material.EnableKeyword("_DETAIL_MULX2");
                    break;
            }
        }

        private static Shader ResolveShader(Material source, Context context)
        {
            if (context.Override != null)
                return context.Override;

            var sourceShader = source.shader;
            if (sourceShader == null)
                return Shader.Find("Standard");

            Shader cached;
            if (context.ShaderChoices.TryGetValue(sourceShader.name, out cached))
                return cached;

            var direct = Shader.Find(sourceShader.name);
            if (direct != null && !direct.name.Contains("InternalError"))
            {
                context.ShaderChoices[sourceShader.name] = direct;
                return direct;
            }

            string familyReason;
            var family = WPFMAShaderResolver.FindFamilyMatch(sourceShader.name, GetCandidateShaders(context), out familyReason);
            if (family != null)
            {
                if (context.ShaderFamilyNotes.Add(familyReason))
                    context.Report.Warnings.Add("Shader " + familyReason + ".");

                context.ShaderChoices[sourceShader.name] = family;
                return family;
            }

            var wanted = new HashSet<string>();
            int propertyCount = sourceShader.GetPropertyCount();
            for (int i = 0; i < propertyCount; i++)
                wanted.Add(sourceShader.GetPropertyName(i));

            Shader best = null;
            int bestScore = 0;

            foreach (var candidate in GetCandidateShaders(context))
            {
                int score = 0;
                int count = candidate.GetPropertyCount();
                for (int i = 0; i < count; i++)
                {
                    if (wanted.Contains(candidate.GetPropertyName(i)))
                        score++;
                }

                if (score > bestScore)
                {
                    bestScore = score;
                    best = candidate;
                }
            }

            float coverage = wanted.Count == 0 ? 0f : (float)bestScore / wanted.Count;
            if (best == null || coverage < MinimumShaderCoverage)
            {
                context.Report.Warnings.Add("No installed shader closely matches '" + sourceShader.name + "' (best was " +
                    (best != null ? "'" + best.name + "' covering " + Mathf.RoundToInt(coverage * 100f) + "% of its properties" : "nothing") +
                    "). Using Standard instead — install the shader family this avatar was built with, then export again.");
                best = Shader.Find("Standard");
            }

            var chosen = best ?? Shader.Find("Standard");
            context.ShaderChoices[sourceShader.name] = chosen;
            return chosen;
        }

        private static List<Shader> GetCandidateShaders(Context context)
        {
            if (context.Candidates != null)
                return context.Candidates;

            context.Candidates = new List<Shader>();

            foreach (var info in ShaderUtil.GetAllShaderInfo())
            {
                if (info.hasErrors || info.name.StartsWith("Hidden/", StringComparison.Ordinal))
                    continue;

                var shader = Shader.Find(info.name);
                if (shader != null)
                    context.Candidates.Add(shader);
            }

            return context.Candidates;
        }

        private static long BundlePathId(UnityEngine.Object loaded)
        {
            string guid;
            long localId;
            return loaded != null && AssetDatabase.TryGetGUIDAndLocalFileIdentifier(loaded, out guid, out localId)
                ? localId
                : 0;
        }

        private static void RestoreClipCurves(AnimationClip clip, AnimationClip source, Context context)
        {
            if (clip == null)
                return;

            if (EnsureDecoder(context) == null)
                return;

            if (context.Decoder.Restore(clip, BundlePathId(source)))
            {
                EditorUtility.SetDirty(clip);
                context.Report.ClipsWithCurves++;
            }

            context.Report.CurvesRecovered = context.Decoder.Report.CurvesWritten;
            context.Report.CurveBindingsUnresolved =
                context.Decoder.Report.BindingsUnresolvedPath + context.Decoder.Report.BindingsUnresolvedProperty;
        }

        private static Dictionary<uint, string> transformPathsCache;
        private static GameObject transformPathsFor;

        private static Func<uint, string> TransformPathResolver(Context context)
        {
            var root = context.Instance;
            if (root == null)
                return null;

            if (transformPathsCache == null || transformPathsFor != root)
            {
                transformPathsCache = new Dictionary<uint, string>();
                transformPathsFor = root;
                foreach (var transform in root.GetComponentsInChildren<Transform>(true))
                {
                    var parts = new List<string>();
                    for (var current = transform; current != null && current != root.transform; current = current.parent)
                        parts.Add(current.name);
                    parts.Reverse();
                    string path = string.Join("/", parts.ToArray());
                    transformPathsCache[WPFMAAnimationClipDecoder.Crc32(path)] = path;
                }
            }

            var map = transformPathsCache;
            return hash =>
            {
                string path;
                return map.TryGetValue(hash, out path) ? path : null;
            };
        }

        private static WPFMAAnimationClipDecoder EnsureDecoder(Context context)
        {
            if (!context.DecoderBuilt)
            {
                context.DecoderBuilt = true;
                if (context.Cab != null)
                {
                    try
                    {
                        context.Decoder = new WPFMAAnimationClipDecoder(
                            context.Cab, context.Instance, context.Report.Warnings);
                    }
                    catch (Exception e)
                    {
                        context.Report.Warnings.Add("Animation curves could not be read from the bundle: " + e.Message);
                    }
                }
            }

            return context.Decoder;
        }

        private static void ExportSwapMaterials(Context context)
        {
            var decoder = EnsureDecoder(context);
            if (decoder == null)
                return;

            var wanted = decoder.ReferencedObjectIds();
            if (wanted.Count == 0)
                return;

            context.BundleMaterials = new Dictionary<long, Material>();
            foreach (var material in Resources.FindObjectsOfTypeAll<Material>())
            {
                if (material == null || !string.IsNullOrEmpty(AssetDatabase.GetAssetPath(material)))
                    continue;

                long id = BundlePathId(material);
                if (id != 0 && wanted.Contains(id) && !context.BundleMaterials.ContainsKey(id))
                    context.BundleMaterials[id] = material;
            }

            int saved = 0;
            foreach (var pair in context.BundleMaterials)
            {
                try
                {
                    RecoverMaterialTextures(pair.Value, context);
                    if (PersistMaterial(pair.Value, context) != null)
                        saved++;
                }
                catch (Exception e)
                {
                    context.Report.Warnings.Add("Could not save swapped-in material '" + pair.Value.name + "': " + e.Message);
                }
            }

            decoder.ResolveObject = id =>
            {
                Material source;
                if (context.BundleMaterials == null || !context.BundleMaterials.TryGetValue(id, out source))
                    return null;

                Material copy;
                if (!context.Materials.TryGetValue(source, out copy))
                    return null;
                return copy != null ? copy : Resurrect(source, context);
            };

            Debug.Log("[WPFMA-SDK] Material swaps: saved " + saved + " of the " + wanted.Count +
                      " materials the animations swap in" +
                      (context.BundleMaterials.Count < wanted.Count
                          ? " (" + (wanted.Count - context.BundleMaterials.Count) + " were not loaded from the bundle)."
                          : "."));
        }

        private static void RecoverMaterialTextures(Material material, Context context)
        {
            if (material == null || material.shader == null)
                return;

            foreach (var property in material.GetTexturePropertyNames())
            {
                var texture = material.GetTexture(property);
                if (texture == null || context.Textures.ContainsKey(texture))
                    continue;

                var flat = texture as Texture2D;
                var cube = texture as Cubemap;
                if (flat == null && cube == null)
                    continue;

                try
                {
                    context.Textures[texture] = flat != null
                        ? (Texture)RecoverTexture(flat, context, IsNormalMapSlot(property))
                        : RecoverCubemap(cube, context);
                    context.Report.Textures++;
                }
                catch (Exception e)
                {
                    context.Report.Warnings.Add("Could not recover texture '" + texture.name + "': " + e.Message);
                }
            }
        }

        private static void ExportAnimation(GameObject instance, Context context)
        {
            ExportSwapMaterials(context);

            foreach (var animator in instance.GetComponentsInChildren<Animator>(true))
            {
                if (animator.avatar != null)
                {
                    try
                    {
                        var copy = UnityEngine.Object.Instantiate(animator.avatar);
                        copy.name = animator.avatar.name;
                        string path = AssetDatabase.GenerateUniqueAssetPath(context.Root + "/Avatar/" + Sanitize(copy.name) + ".asset");
                        AssetDatabase.CreateAsset(copy, path);
                        animator.avatar = copy;
                        context.Report.Avatars++;
                    }
                    catch (Exception e)
                    {
                        context.Report.Warnings.Add("Could not save the humanoid avatar: " + e.Message);
                    }
                }

            }
        }

        private static void ExportComponentReferences(GameObject instance, Context context)
        {
            foreach (var component in instance.GetComponentsInChildren<Component>(true))
            {
                if (component == null)
                    continue;

                try
                {
                    RemapReferences(component, context, 0);
                }
                catch (Exception e)
                {
                    context.Report.Warnings.Add("Could not save references on '" + component.GetType().Name + "': " + e.Message);
                }
            }
        }

        private static void RemapReferences(UnityEngine.Object target, Context context, int depth)
        {
            if (target == null || depth > MaxReferenceDepth)
                return;

            bool targetIsAsset = !string.IsNullOrEmpty(AssetDatabase.GetAssetPath(target));
            var serialized = new SerializedObject(target);
            var property = serialized.GetIterator();
            bool changed = false;

            while (property.NextVisible(true))
            {
                if (property.propertyType != SerializedPropertyType.ObjectReference)
                    continue;

                var value = property.objectReferenceValue;
                if (value == null)
                    continue;

                var persisted = PersistReferenced(value, context, depth);
                if (persisted == null)
                    persisted = Resurrect(value, context);
                if (persisted != null && persisted != value)
                {
                    property.objectReferenceValue = persisted;
                    changed = true;

                    string assetPath = AssetDatabase.GetAssetPath(persisted);
                    if (!targetIsAsset && !string.IsNullOrEmpty(assetPath))
                        context.PendingSlots.Add(new SlotRecord
                        {
                            Target = target,
                            PropertyPath = property.propertyPath,
                            AssetPath = assetPath
                        });
                }
                else if (persisted == null && context.ClearedReferences.Contains(value))
                {
                    property.objectReferenceValue = null;
                    changed = true;
                }
            }

            if (changed)
            {
                serialized.ApplyModifiedPropertiesWithoutUndo();

                if (targetIsAsset)
                    AssetDatabase.SaveAssetIfDirty(target);
            }
        }

        private static UnityEngine.Object PersistReferenced(UnityEngine.Object value, Context context, int depth)
        {
            if (value is Component || value is GameObject || value is MonoScript)
                return null;

            if (!string.IsNullOrEmpty(AssetDatabase.GetAssetPath(value)))
                return null;

            UnityEngine.Object existing;
            if (context.References.TryGetValue(value, out existing))
                return existing != null ? existing : Resurrect(value, context);

            var texture = value as Texture;
            if (texture != null)
            {
                Texture recovered;
                if (context.Textures.TryGetValue(texture, out recovered))
                    return recovered != null ? recovered : Resurrect(value, context);

                var flat = texture as Texture2D;
                var cube = texture as Cubemap;
                if (flat == null && cube == null)
                    return null;

                try
                {
                    recovered = flat != null ? (Texture)RecoverTexture(flat, context, false) : RecoverCubemap(cube, context);
                    context.Textures[texture] = recovered;
                    context.Report.Textures++;
                    return recovered;
                }
                catch (Exception e)
                {
                    context.Report.Warnings.Add("Could not recover referenced texture '" + texture.name + "': " + e.Message);
                    return null;
                }
            }

            var mesh = value as Mesh;
            if (mesh != null)
                return PersistMesh(mesh, context);

            var material = value as Material;
            if (material != null)
                return PersistMaterial(material, context);

            var controller = value as RuntimeAnimatorController;
            if (controller != null)
                return PersistAnimatorController(controller, context);

            string folder;
            string extension;
            ClassifyReference(value, out folder, out extension);
            if (folder == null)
                return null;

            UnityEngine.Object copy = null;
            bool needsRebind = true;

            var scriptable = value as ScriptableObject;
            if (scriptable != null)
            {
                try
                {
                    var rebuilt = ScriptableObject.CreateInstance(scriptable.GetType());
                    if (rebuilt != null)
                    {
                        EditorUtility.CopySerializedManagedFieldsOnly(scriptable, rebuilt);
                        copy = rebuilt;
                        needsRebind = false;
                    }
                }
                catch (Exception)
                {
                    copy = null;
                }
            }

            if (copy == null)
            {
                try
                {
                    copy = UnityEngine.Object.Instantiate(value);
                }
                catch (Exception e)
                {
                    context.Report.Warnings.Add("Could not copy '" + value.name + "' (" + value.GetType().Name + "): " + e.Message);
                    return null;
                }
            }

            copy.name = value.name;

            Directory.CreateDirectory(context.Root + "/" + folder);
            string path = AssetDatabase.GenerateUniqueAssetPath(
                context.Root + "/" + folder + "/" + Sanitize(value.name) + extension);

            try
            {
                AssetDatabase.CreateAsset(copy, path);
            }
            catch (Exception e)
            {
                context.Report.Warnings.Add("Could not save '" + value.name + "' (" + value.GetType().Name + "): " + e.Message);
                return null;
            }

            if (needsRebind)
            {
                RebindScript(copy, context);
                var reloaded = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
                if (reloaded != null)
                    copy = reloaded;
                AssetDatabase.SaveAssetIfDirty(copy);
            }

            context.References[value] = copy;
            context.ReferencePaths[value] = path;

            int count;
            string key = value.GetType().Name;
            context.Report.References.TryGetValue(key, out count);
            context.Report.References[key] = count + 1;

            RemapReferences(copy, context, depth + 1);

            var fresh = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
            if (fresh != null)
            {
                context.References[value] = fresh;
                copy = fresh;
            }

            return copy;
        }

        private static UnityEngine.Object Resurrect(UnityEngine.Object source, Context context)
        {
            string path;
            if (source == null || !context.ReferencePaths.TryGetValue(source, out path))
                return null;

            var loaded = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(path);
            if (loaded == null)
                return null;

            context.References[source] = loaded;

            var sourceTexture = source as Texture;
            var loadedTexture = loaded as Texture;
            if (sourceTexture != null && loadedTexture != null)
                context.Textures[sourceTexture] = loadedTexture;

            return loaded;
        }

        private static readonly Regex BrokenScriptLine =
            new Regex(@"m_Script: \{fileID: -?\d+, guid: 0{32}, type: \d\}");

        private static void RepairScriptBindings(Context context)
        {
            int repaired = 0;

            foreach (var pair in context.ReferencePaths)
            {
                var source = pair.Key;
                string path = pair.Value;

                if (source == null || string.IsNullOrEmpty(path) ||
                    !path.EndsWith(".asset", StringComparison.OrdinalIgnoreCase))
                    continue;

                string text;
                try
                {
                    text = File.ReadAllText(path);
                }
                catch (Exception)
                {
                    continue;
                }

                if (!BrokenScriptLine.IsMatch(text))
                    continue;

                var type = source.GetType();
                if (!typeof(ScriptableObject).IsAssignableFrom(type) && !typeof(MonoBehaviour).IsAssignableFrom(type))
                    continue;

                var script = GetProjectScript(type, context);
                string guid;
                long localId;
                if (script == null || !AssetDatabase.TryGetGUIDAndLocalFileIdentifier(script, out guid, out localId))
                {
                    if (context.UnresolvedTypes.Add(type.FullName))
                        context.Report.Warnings.Add("No script asset in this project provides '" + type.FullName +
                            "', so '" + path + "' keeps a broken script reference.");
                    continue;
                }

                text = BrokenScriptLine.Replace(text,
                    "m_Script: {fileID: " + localId + ", guid: " + guid + ", type: 3}");

                try
                {
                    File.WriteAllText(path, text);
                    AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport);
                    repaired++;
                }
                catch (Exception e)
                {
                    context.Report.Warnings.Add("Could not repair the script reference on '" + path + "': " + e.Message);
                }
            }

            if (repaired > 0)
                context.Report.Warnings.Add("Repaired " + repaired +
                    " exported asset(s) whose script reference had been reverted by a mid-export reimport.");
        }

        private static void RestoreComponentReferences(Context context)
        {
            int restored = 0;

            foreach (var slot in context.PendingSlots)
            {
                if (slot.Target == null)
                    continue;

                SerializedObject serialized;
                try
                {
                    serialized = new SerializedObject(slot.Target);
                }
                catch (Exception)
                {
                    continue;
                }

                var property = serialized.FindProperty(slot.PropertyPath);
                if (property == null || property.propertyType != SerializedPropertyType.ObjectReference)
                    continue;
                if (property.objectReferenceValue != null)
                    continue;

                var asset = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(slot.AssetPath);
                if (asset == null)
                    continue;

                property.objectReferenceValue = asset;
                serialized.ApplyModifiedPropertiesWithoutUndo();
                restored++;
            }

            if (restored > 0)
                context.Report.Warnings.Add("Restored " + restored +
                    " component reference(s) whose exported copy was torn down before the prefab was saved.");
        }

        private static Dictionary<long, AnimationClip> MapClipsByPathId(long[] clipOrder,
            AnimationClip[] runtimeClips, Context context, string controllerName)
        {
            if (clipOrder == null || clipOrder.Length == 0)
                return null;

            var distinct = new List<long>();
            var seen = new HashSet<long>();
            foreach (var pathId in clipOrder)
            {
                if (pathId != 0 && seen.Add(pathId))
                    distinct.Add(pathId);
            }

            var exact = new Dictionary<long, AnimationClip>();
            foreach (var clip in runtimeClips)
            {
                long id = BundlePathId(clip);
                if (id != 0)
                    exact[id] = clip;
            }

            if (distinct.Count > 0 && distinct.TrueForAll(exact.ContainsKey))
                return exact;

            int covered = distinct.Count(exact.ContainsKey);
            context.Report.Warnings.Add("'" + controllerName + "': only " + covered + " of " + distinct.Count +
                " clips could be matched to the bundle exactly; the rest were matched by name, so states whose " +
                "clips share a name (VRCFury's \"New Clip\" and the like) may play the wrong animation.");

            if (context.ClipNames == null)
                context.ClipNames = WPFMAAnimatorGraph.ReadClipNames(context.Cab);
            var names = context.ClipNames;
            var mapping = new Dictionary<long, AnimationClip>();

            if (distinct.Count == runtimeClips.Length)
            {
                bool agrees = true;
                for (int i = 0; i < distinct.Count && agrees; i++)
                {
                    string expected;
                    if (!names.TryGetValue(distinct[i], out expected) || string.IsNullOrEmpty(expected))
                        continue;
                    if (runtimeClips[i] == null || runtimeClips[i].name != expected)
                        agrees = false;
                }

                if (agrees)
                {
                    for (int i = 0; i < distinct.Count; i++)
                        mapping[distinct[i]] = runtimeClips[i];
                    return mapping;
                }
            }

            var byName = new Dictionary<string, AnimationClip>();
            foreach (var clip in runtimeClips)
            {
                if (clip != null && !string.IsNullOrEmpty(clip.name))
                    byName[clip.name] = clip;
            }

            int unplaced = 0;
            foreach (var pathId in distinct)
            {
                string name;
                AnimationClip clip;
                if (names.TryGetValue(pathId, out name) && !string.IsNullOrEmpty(name) &&
                    byName.TryGetValue(name, out clip))
                    mapping[pathId] = clip;
                else
                    unplaced++;
            }

            if (unplaced > 0)
                context.Report.Warnings.Add("'" + controllerName + "': " + unplaced +
                    " of its " + distinct.Count + " clips could not be matched to the bundle by name, so those states were left empty.");

            return mapping;
        }

        private static string UniqueClipPath(string folder, string clipName, HashSet<string> used)
        {
            string stem = Sanitize(clipName);
            if (string.IsNullOrEmpty(stem))
                stem = "unnamed";

            string candidate = folder + "/" + stem + ".anim";
            for (int n = 1; used.Contains(candidate) || File.Exists(candidate); n++)
                candidate = folder + "/" + stem + " " + n + ".anim";

            used.Add(candidate);
            return candidate;
        }

        private static UnityEngine.Object PersistAnimatorController(RuntimeAnimatorController controller, Context context)
        {
            AnimationClip[] clips;
            try
            {
                clips = controller.animationClips ?? new AnimationClip[0];
            }
            catch (Exception)
            {
                clips = new AnimationClip[0];
            }

            var editable = controller as UnityEditor.Animations.AnimatorController;
            int layerCount = editable != null ? editable.layers.Length : 0;

            string clipFolder = "AnimationClip/" + Sanitize(controller.name);
            Directory.CreateDirectory(context.Root + "/" + clipFolder);

            int exported = 0;
            var clipClock = System.Diagnostics.Stopwatch.StartNew();
            var usedPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            AssetDatabase.StartAssetEditing();
            try
            {
                for (int i = 0; i < clips.Length; i++)
                {
                    var clip = clips[i];
                    if (clip == null)
                        continue;

                    if (i % 25 == 0)
                        Step(context.Progress, 0.93f,
                            "Saving clips for '" + controller.name + "' (" + i + "/" + clips.Length + ")");

                    UnityEngine.Object already;
                    if (context.References.TryGetValue(clip, out already))
                        continue;

                    try
                    {
                        var clipCopy = UnityEngine.Object.Instantiate(clip);
                        clipCopy.name = clip.name;
                        RestoreClipCurves(clipCopy, clip, context);
                        string clipPath = UniqueClipPath(context.Root + "/" + clipFolder, clip.name, usedPaths);
                        AssetDatabase.CreateAsset(clipCopy, clipPath);
                        context.References[clip] = clipCopy;
                        context.ReferencePaths[clip] = clipPath;
                        context.Report.Clips++;
                        exported++;
                    }
                    catch (Exception e)
                    {
                        context.Report.Warnings.Add("Could not save clip '" + clip.name + "': " + e.Message);
                    }
                }
            }
            finally
            {
                AssetDatabase.StopAssetEditing();
            }

            Debug.Log("[WPFMA-SDK] '" + controller.name + "': saved " + exported + " clips in " +
                      (clipClock.ElapsedMilliseconds / 1000f).ToString("0.0") + " s.");

            if (layerCount == 0)
            {
                var skeleton = BuildControllerSkeleton(controller, context, clipFolder, exported);
                if (skeleton != null)
                    return skeleton;

                context.ClearedReferences.Add(controller);
                context.Report.Warnings.Add("'" + controller.name + "' came from a player build and nothing about its " +
                    "layers could be read, so the playable-layer slot was left empty on purpose. Its " + exported +
                    " animation clip(s) are in " + clipFolder + " for rebuilding the layer.");
                return null;
            }

            UnityEngine.Object copy;
            try
            {
                copy = UnityEngine.Object.Instantiate(controller);
            }
            catch (Exception e)
            {
                context.Report.Warnings.Add("Could not copy animator '" + controller.name + "': " + e.Message);
                return null;
            }

            copy.name = controller.name;

            Directory.CreateDirectory(context.Root + "/AnimatorController");
            string path = AssetDatabase.GenerateUniqueAssetPath(
                context.Root + "/AnimatorController/" + Sanitize(controller.name) + ".controller");

            try
            {
                AssetDatabase.CreateAsset(copy, path);
            }
            catch (Exception e)
            {
                context.Report.Warnings.Add("Could not save animator '" + controller.name + "': " + e.Message);
                return null;
            }

            context.References[controller] = copy;
            context.ReferencePaths[controller] = path;

            int count;
            context.Report.References.TryGetValue("AnimatorController", out count);
            context.Report.References["AnimatorController"] = count + 1;
            return copy;
        }

        private static UnityEngine.Object BuildControllerSkeleton(RuntimeAnimatorController source, Context context, string clipFolder, int exportedClips)
        {
            string[] layerNames;
            float[] layerWeights;
            AnimatorControllerParameter[] parameters;

            GameObject probe = null;
            try
            {
                probe = EditorUtility.CreateGameObjectWithHideFlags(
                    "WPFMA-SDK animator probe", HideFlags.HideAndDontSave, typeof(Animator));

                var animator = probe.GetComponent<Animator>();
                animator.runtimeAnimatorController = source;

                int count = animator.layerCount;
                if (count == 0)
                    return null;

                layerNames = new string[count];
                layerWeights = new float[count];
                for (int i = 0; i < count; i++)
                {
                    layerNames[i] = animator.GetLayerName(i);
                    layerWeights[i] = animator.GetLayerWeight(i);
                }

                parameters = animator.parameters;
            }
            catch (Exception e)
            {
                context.Report.Warnings.Add("Could not read the runtime form of '" + source.name + "': " + e.Message +
                    (context.Cab != null
                        ? " Rebuilding it from the bundle's serialized data instead."
                        : " Its playable-layer slot will be left empty."));

                if (context.Cab == null)
                    return null;

                layerNames = new string[0];
                layerWeights = new float[0];
                parameters = new AnimatorControllerParameter[0];
            }
            finally
            {
                if (probe != null)
                    UnityEngine.Object.DestroyImmediate(probe);
            }

            Directory.CreateDirectory(context.Root + "/AnimatorController");
            string path = AssetDatabase.GenerateUniqueAssetPath(
                context.Root + "/AnimatorController/" + Sanitize(source.name) + ".controller");

            UnityEditor.Animations.AnimatorController rebuilt;
            try
            {
                rebuilt = UnityEditor.Animations.AnimatorController.CreateAnimatorControllerAtPath(path);
            }
            catch (Exception e)
            {
                context.Report.Warnings.Add("Could not create a controller for '" + source.name + "': " + e.Message);
                return null;
            }

            if ((parameters == null || parameters.Length == 0) && context.Cab != null)
            {
                try
                {
                    var serialized = WPFMAAnimatorGraph.ReadParameters(context.Cab, source.name, BundlePathId(source));
                    if (serialized != null && serialized.Count > 0)
                        parameters = serialized.ToArray();
                }
                catch (Exception e)
                {
                    context.Report.Warnings.Add("Could not read the parameters of '" + source.name + "' from the " +
                        "bundle's serialized data (" + e.Message + "); its conditions will have nothing to reference.");
                }
            }

            int addedParameters = 0;
            foreach (var parameter in parameters ?? new AnimatorControllerParameter[0])
            {
                if (parameter == null || string.IsNullOrEmpty(parameter.name))
                    continue;

                try
                {
                    rebuilt.AddParameter(new AnimatorControllerParameter
                    {
                        name = parameter.name,
                        type = parameter.type,
                        defaultBool = parameter.defaultBool,
                        defaultFloat = parameter.defaultFloat,
                        defaultInt = parameter.defaultInt
                    });
                    addedParameters++;
                }
                catch (Exception)
                {
                }
            }

            if (rebuilt.layers.Length > 0)
                rebuilt.RemoveLayer(0);

            bool populated = false;
            if (context.Cab != null)
            {
                try
                {
                    long controllerId = BundlePathId(source);
                    var clipOrder = WPFMAAnimatorGraph.ReadClipOrder(context.Cab, source.name, controllerId);
                    var runtimeClips = source.animationClips ?? new AnimationClip[0];
                    var clipById = MapClipsByPathId(clipOrder, runtimeClips, context, source.name);

                    Func<int, Motion> clipAt = index =>
                    {
                        AnimationClip clip = null;

                        if (clipOrder != null && clipById != null)
                        {
                            if (index < 0 || index >= clipOrder.Length)
                                return null;
                            clipById.TryGetValue(clipOrder[index], out clip);
                        }
                        else if (index >= 0 && index < runtimeClips.Length)
                        {
                            clip = runtimeClips[index];
                        }

                        if (clip == null)
                            return null;

                        UnityEngine.Object mapped;
                        if (!context.References.TryGetValue(clip, out mapped))
                            return null;

                        if (mapped == null)
                            mapped = Resurrect(clip, context);
                        return mapped as Motion;
                    };

                    var graphClock = System.Diagnostics.Stopwatch.StartNew();
                    var stats = WPFMAAnimatorGraph.Populate(rebuilt, source.name, context.Cab, clipAt, context.Report.Warnings,
                        controllerId, TransformPathResolver(context));
                    Debug.Log("[WPFMA-SDK] '" + source.name + "': state machine rebuilt in " +
                              (graphClock.ElapsedMilliseconds / 1000f).ToString("0.0") + " s.");
                    if (stats != null && stats.Layers > 0)
                    {
                        populated = true;
                        context.Report.Warnings.Add("'" + source.name + "' was fully rebuilt from the bundle's serialized data: " +
                            stats + ", " + addedParameters + " parameter(s).");
                    }
                }
                catch (Exception e)
                {
                    context.Report.Warnings.Add("State machine rebuild failed for '" + source.name + "' (" + e.Message +
                        "); falling back to layer names only.");
                }
            }

            if (!populated)
            {
                for (int i = 0; i < layerNames.Length; i++)
                {
                    rebuilt.AddLayer(layerNames[i]);
                    var current = rebuilt.layers;
                    current[current.Length - 1].defaultWeight = layerWeights[i];
                    rebuilt.layers = current;
                }

                context.Report.Warnings.Add("'" + source.name + "' was rebuilt from its runtime form: " +
                    layerNames.Length + " layer(s) and " + addedParameters + " parameter(s) recovered, but the states, " +
                    "transitions and conditions inside each layer could not be read back. Its " + exportedClips +
                    " clip(s) are in " + clipFolder + " to wire back in.");
            }

            context.References[source] = rebuilt;
            context.ReferencePaths[source] = path;

            int count2;
            context.Report.References.TryGetValue("AnimatorController", out count2);
            context.Report.References["AnimatorController"] = count2 + 1;

            return rebuilt;
        }

        private static void ClassifyReference(UnityEngine.Object value, out string folder, out string extension)
        {
            if (value is AnimationClip)
            {
                folder = "AnimationClip";
                extension = ".anim";
                return;
            }

            if (value is RuntimeAnimatorController)
            {
                folder = "AnimatorController";
                extension = ".controller";
                return;
            }

            if (value is AvatarMask)
            {
                folder = "AvatarMask";
                extension = ".mask";
                return;
            }

            if (value is Avatar)
            {
                folder = "Avatar";
                extension = ".asset";
                return;
            }

            if (value is ScriptableObject)
            {
                folder = "MonoBehaviour";
                extension = ".asset";
                return;
            }

            if (value is AudioClip || value is Shader || value is Font)
            {
                folder = null;
                extension = null;
                return;
            }

            folder = "Other";
            extension = ".asset";
        }

        private static void RebindScript(UnityEngine.Object target, Context context)
        {
            if (target == null)
                return;
            if (!(target is MonoBehaviour) && !(target is ScriptableObject))
                return;

            var serialized = new SerializedObject(target);
            var scriptProperty = serialized.FindProperty("m_Script");
            if (scriptProperty == null)
                return;

            var current = scriptProperty.objectReferenceValue as MonoScript;
            if (current != null && !string.IsNullOrEmpty(AssetDatabase.GetAssetPath(current)))
                return;

            var type = target.GetType();
            var replacement = GetProjectScript(type, context);
            if (replacement == null)
            {
                if (context.UnresolvedTypes.Add(type.FullName))
                    context.Report.Warnings.Add("No script asset in this project provides '" + type.FullName +
                        "', so those components cannot be saved. Install the package that defines it and export again.");
                return;
            }

            scriptProperty.objectReferenceValue = replacement;
            serialized.ApplyModifiedPropertiesWithoutUndo();
        }

        public static List<string> RebindSceneScripts(GameObject instance)
        {
            var warnings = new List<string>();
            if (instance == null)
                return warnings;

            var context = new Context();

            foreach (var component in instance.GetComponentsInChildren<Component>(true))
            {
                if (component == null)
                    continue;

                try
                {
                    RebindScript(component, context);
                }
                catch (Exception e)
                {
                    warnings.Add("Script rebind failed on '" + component.GetType().Name + "': " + e.Message);
                }
            }

            warnings.AddRange(context.Report.Warnings);
            return warnings;
        }

        private static MonoScript GetProjectScript(Type type, Context context)
        {
            MonoScript cached;
            if (context.ProjectScripts.TryGetValue(type, out cached))
                return cached;

            MonoScript found = null;

            if (typeof(ScriptableObject).IsAssignableFrom(type))
            {
                ScriptableObject temp = null;
                try
                {
                    temp = ScriptableObject.CreateInstance(type);
                    if (temp != null)
                        found = MonoScript.FromScriptableObject(temp);
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (temp != null)
                        UnityEngine.Object.DestroyImmediate(temp);
                }
            }
            else if (typeof(MonoBehaviour).IsAssignableFrom(type))
            {
                GameObject temp = null;
                try
                {
                    temp = EditorUtility.CreateGameObjectWithHideFlags("WPFMA-SDK script probe", HideFlags.HideAndDontSave);
                    var component = temp.AddComponent(type) as MonoBehaviour;
                    if (component != null)
                        found = MonoScript.FromMonoBehaviour(component);
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (temp != null)
                        UnityEngine.Object.DestroyImmediate(temp);
                }
            }

            if (found != null && string.IsNullOrEmpty(AssetDatabase.GetAssetPath(found)))
                found = null;

            context.ProjectScripts[type] = found;
            return found;
        }

        private static void SavePrefab(GameObject instance, Context context)
        {
            foreach (var transform in instance.GetComponentsInChildren<Transform>(true))
            {
                if (transform == null)
                    continue;

                foreach (var component in transform.GetComponents<Component>())
                {
                    if (component == null)
                    {
                        context.Report.MissingScriptPaths.Add(GetHierarchyPath(transform));
                        continue;
                    }

                    string typeName = component.GetType().Name;
                    int count;
                    context.Report.Components.TryGetValue(typeName, out count);
                    context.Report.Components[typeName] = count + 1;
                }
            }

            foreach (var transform in instance.GetComponentsInChildren<Transform>(true))
            {
                if (transform == null)
                    continue;

                context.Report.MissingScriptsStripped +=
                    GameObjectUtility.RemoveMonoBehavioursWithMissingScript(transform.gameObject);
            }

            if (context.Report.MissingScriptsStripped > 0)
            {
                var distinct = context.Report.MissingScriptPaths.Distinct().Take(10).ToList();
                context.Report.Warnings.Add("Dropped " + context.Report.MissingScriptsStripped +
                    " component(s) whose script is not installed in this project — a prefab cannot be saved with them. " +
                    "Install the package that provides them and export again. Affected: " + string.Join(", ", distinct) +
                    (context.Report.MissingScriptPaths.Distinct().Count() > 10 ? ", …" : string.Empty));
            }

            string path = AssetDatabase.GenerateUniqueAssetPath(context.Root + "/" + Sanitize(instance.name) + ".prefab");
            var prefab = PrefabUtility.SaveAsPrefabAsset(instance, path);

            if (prefab == null)
                context.Report.Warnings.Add("The prefab could not be written; the individual assets were still exported.");
            else
                context.Report.PrefabPath = path;
        }

        private static string GetHierarchyPath(Transform transform)
        {
            var parts = new List<string>();
            for (var current = transform; current != null; current = current.parent)
                parts.Add(current.name);

            parts.Reverse();
            return string.Join("/", parts);
        }

        private const int MaxNameLength = 48;

        // Windows' path limit (260 with the ending zero), and what goes on top of the export folder in its deepest file:
        // "/AnimationClip/" + controller name + "/" + clip name + " 99.anim" + ".meta" (two names of up to the name limit).
        private const int WindowsPathLimit = 259;
        private const int DeepestExtra = 15 + 1 + 8 + 5;
        // Shorter than this and names stop being readable; then the folder really is too deep.
        private const int MinNameLength = 16;

        /// <summary>
        /// How long names inside this export may be. Normally 48; in a project that sits deep in folders it's shortened
        /// just enough that every file still fits Windows' path limit, instead of refusing to export.
        /// </summary>
        private static int nameLimit = MaxNameLength;

        /// <summary>The longest export folder that still works (with the shortest names).</summary>
        private static int MaxRootPathLength
        {
            get { return WindowsPathLimit - DeepestExtra - 2 * MinNameLength; }
        }

        private static string Sanitize(string name)
        {
            if (string.IsNullOrEmpty(name))
                return "unnamed";

            name = WPFMAPaths.SafeFileName(name);
            if (name.Length == 0)
                return "unnamed";
            if (name.Length <= nameLimit)
                return name;

            string tag = "~" + StableHash(name);
            return name.Substring(0, nameLimit - tag.Length).TrimEnd(' ', '.', '_') + tag;
        }

        private static string StableHash(string text)
        {
            uint hash = 2166136261u;
            foreach (char c in text)
            {
                hash ^= c;
                hash *= 16777619u;
            }
            return hash.ToString("x8");
        }

        private const int RipFolderNameLimit = 32;

        public static string RipFolderName(string vrcaPath)
        {
            string name = WPFMAPaths.SafeFileName(Path.GetFileNameWithoutExtension(vrcaPath ?? string.Empty));
            if (string.IsNullOrEmpty(name))
                name = "rip";

            if (name.Length <= RipFolderNameLimit)
                return name;

            uint hash = 2166136261;
            unchecked
            {
                foreach (var c in name)
                {
                    hash ^= c;
                    hash *= 16777619;
                }
            }

            string head = name.Substring(0, RipFolderNameLimit - 7).TrimEnd('_', '-', '.', ' ');
            return head + "_" + hash.ToString("x8").Substring(0, 6);
        }

        private static void EnsureRootFitsPathLimit(string root)
        {
            EnsureRootFitsPathLimit(root, null);
        }

        /// <summary>
        /// Fits names inside the export to the folder's depth (see nameLimit), and refuses only a folder so deep that
        /// even short names wouldn't fit. Notes it in the report when names had to be shortened.
        /// </summary>
        private static void EnsureRootFitsPathLimit(string root, Context context)
        {
            nameLimit = MaxNameLength;
            string full;
            try
            {
                full = Path.GetFullPath(root);
            }
            catch (Exception)
            {
                return;
            }

            int room = (WindowsPathLimit - DeepestExtra - full.Length) / 2;
            if (room < MaxNameLength && room >= MinNameLength)
            {
                nameLimit = room;
                string note = "This project sits deep in folders (the export folder is " + full.Length + " characters), so names inside the export " +
                              "are kept to " + room + " characters to stay under Windows' path limit. Long names end in a short code instead.";
                Debug.Log("[WPFMA-SDK] " + note);
                if (context != null && context.Report != null)
                    context.Report.Warnings.Add(note);
            }

            if (full.Length > MaxRootPathLength)
            {
                string project = Path.GetFullPath(".");
                throw new WPFMAVrcaException("The export folder path is too long for Windows (" + full.Length +
                    " characters; the limit here is " + MaxRootPathLength + ").\n\n" +
                    "Project folder: " + project + " (" + project.Length + ")\n" +
                    "Export folder:  " + root + "\n\n" +
                    "The project's own location counts toward this, not just the export folder. Move the project " +
                    "somewhere shorter such as C:\\Unity\\MyProject, or pick a shorter export folder in " +
                    "Settings > Exporter.");
            }
        }

        private static IEnumerable<Material> EnumerateMaterials(GameObject instance)
        {
            var seen = new HashSet<Material>();

            foreach (var renderer in instance.GetComponentsInChildren<Renderer>(true))
            {
                foreach (var material in renderer.sharedMaterials)
                {
                    if (material != null && seen.Add(material))
                        yield return material;
                }
            }
        }
    }
}
#endif
