コード例 #1
0
    public override void OnInspectorGUI()
    {
        RendererShaderParams myScript = (RendererShaderParams)target;

        if (GUILayout.Button("Store Parameters"))
        {
            myScript.StoreParams();
        }

        DrawDefaultInspector();
    }
コード例 #2
0
    void OnGUI()
    {
        GUIStyle customLabel;

        customLabel             = new GUIStyle("Label");
        customLabel.fixedHeight = 50;

        GUI.Box(new Rect(0, 0, 50, 50), new GUIContent("", logotex), customLabel);


        GUILayout.BeginHorizontal();

        var customButton = new GUIStyle("Button");

        customButton.alignment = TextAnchor.MiddleCenter;
        GUILayout.FlexibleSpace();
        customButton.fontSize         = 10;
        customButton.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
        customButton.fontStyle        = FontStyle.Italic;
        customButton.fixedWidth       = 100;
        if (GUILayout.Button("Add VR Player", customButton))
        {
            var playerPrefabPath = "Assets/SteamVR/InteractionSystem/Core/Prefabs/Player.prefab";

            var file = new FileInfo(playerPrefabPath);

            string fullPath  = file.FullName.Replace(@"\", "/");
            string assetPath = "Assets" + fullPath.Replace(Application.dataPath, "");

            bool alreadyInScene = false;
            var  allRootGos     = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
            foreach (var go in allRootGos)
            {
                bool isPrefabInstance = PrefabUtility.GetPrefabParent(go) != null && PrefabUtility.GetPrefabObject(go.transform) != null;
                if (isPrefabInstance)
                {
                    UnityEngine.Object parentObject = EditorUtility.GetPrefabParent(go);
                    string             path         = AssetDatabase.GetAssetPath(parentObject);

                    if (assetPath.Equals(path))
                    {
                        alreadyInScene = true;
                        break;
                    }
                }
            }

            if (alreadyInScene)
            {
                EditorUtility.DisplayDialog("Player prefab already exists.",
                                            "\"Player\" prefab already in the scene.\n\nTo reset it you can try deleting it first then pressing this button again to create a new VR player object.", "OK");
            }
            else
            {
                UnityEngine.Object prefab = AssetDatabase.LoadMainAssetAtPath(assetPath);

                GameObject clone = PrefabUtility.InstantiatePrefab(prefab as GameObject) as GameObject;
            }
        }
        GUILayout.EndHorizontal();


        Rect r = (Rect)EditorGUILayout.BeginVertical(customLabel);

        customLabel                  = new GUIStyle("Label");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 14;
        customLabel.normal.textColor = Color.black;
        customLabel.fontStyle        = FontStyle.Bold;

        GUILayout.Label("Custom Prop Builder", customLabel);

        customLabel                  = new GUIStyle("Label");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 11;
        customLabel.normal.textColor = new Color(0.5f, 0.5f, 0.5f);
        customLabel.fontStyle        = FontStyle.Bold;

        GUILayout.Label(string.Format("Version: {0} (Lite)", BUILDER_VERSION /*Application.version*/), customLabel);

        EditorGUILayout.EndVertical();

        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 10;
        customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
        customLabel.fontStyle        = FontStyle.Italic;
        customLabel.fixedWidth       = 100;
        customLabel.normal.textColor = new Color(0.7f, 0.0f, 0.0f);

        //EditorGUILayout.LabelField("PATH WARNING!", customLabel, GUILayout.Width(100));

        if (!SystemInfo.operatingSystem.ToLower().Contains("windows 10"))
        {
            if (Application.dataPath.Length > 40)
            {
                if (GUILayout.Button("PATH WARNING!", customLabel))
                {
                    EditorUtility.DisplayDialog("Warning",
                                                string.Format(
                                                    "Your OS is: \"{0}\" which may experience issues with long paths." +
                                                    "\n\nIt would be wise to move this Builder project as close to \"C:\\\" as possible." +
                                                    "\n\nCurrent application datapath:\n{1}",
                                                    SystemInfo.operatingSystem, Application.dataPath
                                                    ),
                                                "Ok");

                    return;
                }
            }
        }

        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 14;
        customLabel.normal.textColor = new Color(0.0f, 0.0f, 1.0f);
        customLabel.fontStyle        = FontStyle.Bold;

        EditorGUILayout.LabelField("Select the .blend file to process:");

        if (GUILayout.Button(new GUIContent("Import Prop Model", "Select .blend files containing valid models. Processes the model to generate a custom assetbundle compatible with AnimationPrepStudio runtime."), customLabel))
        {
            if (!string.IsNullOrEmpty(blenderAppPath) && !File.Exists(blenderAppPath))
            {
                EditorUtility.DisplayDialog("Blender Application Is Not Set",
                                            "Please browse for and select the installed Blender application. Must be version 2.79.", "OK");
                return;
            }

            FixPlayerSettings();

            AssetDatabase.RemoveUnusedAssetBundleNames();

            var modelPath = EditorUtility.OpenFilePanel("Load model", modelPathLast, "blend,fbx");

            if (!string.IsNullOrEmpty(modelPath))
            {
                modelPathLast = Path.GetDirectoryName(modelPath);
                if (Path.GetExtension(modelPath).Equals(".blend"))
                {
                    if (!RunBatch(AnimPrepAssetPostprocessor.assetBundleVariant, modelPath, blenderAppPath))
                    {
                        EditorUtility.DisplayDialog("No AssetCreator.exe Tool",
                                                    "Please ensure the AssetCreator.exe tool in located in the AnimPrep directory.", "OK");
                        return;
                    }

                    var baseName = Path.GetFileNameWithoutExtension(modelPath);

                    modelPath = Path.Combine(
                        Path.Combine(
                            Path.GetDirectoryName(modelPath), baseName.ToLower() + string.Format("_{0}", AnimPrepAssetPostprocessor.assetBundleVariant.ToLower())
                            ),
                        baseName + ".fbx"
                        );
                }

                var uploadFolder = Path.GetDirectoryName(modelPath);

                //var userName = Path.GetFileName (SystemInfo.deviceName);

                var uploadFolderTop = new DirectoryInfo(uploadFolder).Name;

                var uploadName = System.Guid.NewGuid().ToString();                  // Path.GetFileName (uploadFolder);

                var processingPath = AnimPrepAssetPostprocessor.processingFolder;   // Path.Combine(Application.dataPath, "MakeHumanModels");
                //processingPath = Path.Combine (processingPath, userName);
                processingPath = Path.Combine(processingPath, uploadName);

                System.IO.Directory.CreateDirectory(processingPath);


                DirectoryInfo dir        = new DirectoryInfo(uploadFolder);
                FileInfo[]    modelsInfo = dir.GetFiles("*.fbx");

                if (modelsInfo.Length == 0)
                {
                    Debug.LogError("modelsInfo was empty. No .fbx file could be loaded.");
                    return;
                }

                string uid = uploadName.Replace(AnimPrepAssetPostprocessor.templateSeperator.ToString(), "");                 // uploadFolderTop.Replace("$", "");


                //Copy all model files
                foreach (FileInfo f in modelsInfo)
                {
                    var to = Path.Combine(
                        processingPath,
                        AnimPrepAssetPostprocessor.assetBundleVariant +
                        AnimPrepAssetPostprocessor.templateSeperator +                        //"$"
                        uid +
                        AnimPrepAssetPostprocessor.templateSeperator +                        //"$"
                        f.Name
                        );
                    File.Copy(f.FullName, to);
                }

                //Copy all .json files
                FileInfo[] jsonInfo = dir.GetFiles("*.json");
                foreach (FileInfo f in jsonInfo)
                {
                    var to = Path.Combine(processingPath, f.Name);
                    File.Copy(f.FullName, to);
                }

                //Copy all images files
                var textures_path = Path.Combine(uploadFolder, "textures");
                if (Directory.Exists(textures_path))
                {
                    string[] extensions = new[] { ".png", ".jpg", ".tiff", ".bmp" };

                    DirectoryInfo dir_images = new DirectoryInfo(textures_path);

                    FileInfo[] texturesInfo =
                        dir_images.GetFiles()
                        .Where(f => extensions.Contains(f.Extension.ToLower()))
                        .ToArray();

                    foreach (FileInfo f in texturesInfo)
                    {
                        var to = Path.Combine(processingPath, f.Name);
                        FileUtil.CopyFileOrDirectory(f.FullName, to);
                    }
                }

                AnimPrepAssetPostprocessor.AssetBundleUserJson userPrefs = new AnimPrepAssetPostprocessor.AssetBundleUserJson()
                {
                    created = System.DateTime.UtcNow,
                    //user = userName,
                    //uploadFolder = uploadName,
                    characterFolder = Path.GetDirectoryName(modelPath)
                };

                string json     = JsonUtility.ToJson(userPrefs);
                var    jsonPath = Path.Combine(AnimPrepAssetPostprocessor.assetBundlesFolder, uid + ".json");
                using (StreamWriter sr = new StreamWriter(jsonPath)) {                  // Create the file.
                    sr.WriteLine(json);
                }


                AssetDatabase.Refresh();

                BuildScript.BuildAssetBundles();

                AssetDatabase.Refresh();
            }
        }

        EditorGUILayout.Space();

        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 14;
        customLabel.normal.textColor = new Color(0.0f, 0.5f, 0.0f);
        customLabel.fontStyle        = FontStyle.Bold;

        EditorGUILayout.LabelField("Save changes to assetbundles:");
        if (GUILayout.Button(new GUIContent("Re-Build Assetbundles", "After making any changes to avatars, this will update the changes to the local assetbundle files."), customLabel))
        {
            FixPlayerSettings();

            var allPaths = AssetDatabase.GetAllAssetPaths();
            foreach (var assetPath in allPaths)
            {
                if (assetPath.StartsWith(AnimPrepAssetPostprocessor.prefabsFolder))
                {
                    //ensure the prefab is enabled before saving as assetbundle

                    string     modelFileName = Path.GetFileNameWithoutExtension(assetPath);
                    GameObject modelAsset    = AssetDatabase.LoadAssetAtPath <GameObject> (assetPath);                 //LOADING AN ASSET
                    if (modelAsset == null)
                    {
                        continue;
                    }

                    if (!modelAsset.activeSelf)
                    {
                        GameObject model = (GameObject)PrefabUtility.InstantiatePrefab(modelAsset);
                        model.SetActive(true);
                        PrefabUtility.SaveAsPrefabAsset(model, assetPath);
                        GameObject.DestroyImmediate(model);
                    }
                }
            }


            var allShaderKeywordParams = GameObject.FindObjectsOfType <RendererShaderParams> ();

            foreach (var shaderKeywordParams in allShaderKeywordParams)
            {
                shaderKeywordParams.StoreParams();
            }

            var allRootGos = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
            foreach (var go in allRootGos)
            {
                bool isPrefabInstance = PrefabUtility.GetPrefabParent(go) != null && PrefabUtility.GetPrefabObject(go.transform) != null;
                if (isPrefabInstance)
                {
                    RendererShaderParams.StoreAllRenderers(go);

                    PrefabUtility.ReplacePrefab(go, PrefabUtility.GetPrefabParent(go), ReplacePrefabOptions.ConnectToPrefab);
                }
            }

            AssetDatabase.Refresh();
            BuildScript.BuildAssetBundles();
            AssetDatabase.Refresh();

            ShowAssetBundlesExplorer();
        }



        EditorGUILayout.Space();

        customLabel           = new GUIStyle("Button");
        customLabel.alignment = TextAnchor.MiddleCenter;
        customLabel.fontSize  = 12;
        //customLabel.normal.textColor = new Color(0.0f,0.5f,0.0f);
        customLabel.fontStyle = FontStyle.Italic;

        EditorGUILayout.LabelField("Add processed models to scene:");

        if (GUILayout.Button(new GUIContent("Append Prefabs To Scene", "Places all prefabs into the current scene."), customLabel))
        {
            var info     = new DirectoryInfo(AnimPrepAssetPostprocessor.prefabsFolder);
            var fileInfo = info.GetFiles("*.prefab", SearchOption.TopDirectoryOnly);

            for (int i = 0; i < fileInfo.Length; i++)
            {
                var file = fileInfo[i];

                if (Path.GetExtension(file.FullName).Equals(".meta"))
                {
                    continue;
                }

                string fullPath  = file.FullName.Replace(@"\", "/");
                string assetPath = "Assets" + fullPath.Replace(Application.dataPath, "");

                bool alreadyInScene = false;
                var  allRootGos     = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
                foreach (var go in allRootGos)
                {
                    bool isPrefabInstance = PrefabUtility.GetPrefabParent(go) != null && PrefabUtility.GetPrefabObject(go.transform) != null;
                    if (isPrefabInstance)
                    {
                        UnityEngine.Object parentObject = EditorUtility.GetPrefabParent(go);
                        string             path         = AssetDatabase.GetAssetPath(parentObject);

                        if (assetPath.Equals(path))
                        {
                            alreadyInScene = true;
                            break;
                        }
                    }
                }
                if (alreadyInScene)
                {
                    continue;
                }

                UnityEngine.Object prefab = AssetDatabase.LoadMainAssetAtPath(assetPath);

                GameObject clone = PrefabUtility.InstantiatePrefab(prefab as GameObject) as GameObject;
            }
        }



        EditorGUILayout.Space();

        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 12;
        customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
        customLabel.fontStyle        = FontStyle.Italic;

        EditorGUILayout.LabelField("Show folder containing output files:");
        GUILayout.BeginHorizontal();

        if (GUILayout.Button(new GUIContent("Assetbundles", "Opens the folder containing the newly created Assetbundle files."), customLabel))
        {
            ShowAssetBundlesExplorer();
        }

        customLabel.normal.textColor = new Color(1.0f, 0.2f, 0.2f);
        if (GUILayout.Button(new GUIContent("VR_MocapAssets", "This is the destination folder where you should copy Assetbundles to for them to be included in AnimationPrepStudio runtime."), customLabel))
        {
            ShowMocapAssetsExplorer();
        }
        GUILayout.EndHorizontal();

        EditorGUILayout.Space();



        GUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Blender Application (v2.79):", GUILayout.MinWidth(0));

        customLabel           = new GUIStyle("Label");
        customLabel.alignment = TextAnchor.MiddleCenter;
        customLabel.fontStyle = FontStyle.BoldAndItalic;

        if (blenderAppExists)
        {
            customLabel.normal.textColor = new Color(0.0f, 0.5f, 0.0f);
            EditorGUILayout.LabelField("File Exists", customLabel, GUILayout.Width(100));
        }
        else
        {
            customLabel.normal.textColor = new Color(0.5f, 0.0f, 0.0f);
            EditorGUILayout.LabelField("File Missing!", customLabel, GUILayout.Width(100));

            customButton                  = new GUIStyle("Button");
            customButton.alignment        = TextAnchor.MiddleCenter;
            customButton.fontSize         = 10;
            customButton.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
            customButton.fontStyle        = FontStyle.Italic;
            customButton.fixedWidth       = 100;
            if (GUILayout.Button("Default", customButton))
            {
                blenderAppPath = blenderAppPathDefault;
            }
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();

        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 10;
        customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
        customLabel.fontStyle        = FontStyle.Italic;
        customLabel.fixedWidth       = 100;

        blenderAppPath = GUILayout.TextField(blenderAppPath, GUILayout.MinWidth(0));
        if (GUILayout.Button(new GUIContent("Browse", "Select a valid Blender v2.79b installation path by locating and selecting the \"blender.exe\" runtime application file."), customLabel))
        {
            string modelPath = EditorUtility.OpenFilePanel("Blender Application (v2.79)", Path.GetDirectoryName(blenderAppPath), "exe");
            if (!string.IsNullOrEmpty(modelPath))
            {
                blenderAppPath = modelPath;
            }
        }
        GUILayout.EndHorizontal();
        EditorGUILayout.Space();

        customLabel           = new GUIStyle("Label");
        customLabel.alignment = TextAnchor.MiddleCenter;
        customLabel.fontStyle = FontStyle.Italic;
        GUILayout.Label(string.Format("{0} - {1}", Application.unityVersion, SystemInfo.operatingSystem), customLabel);

        if (GUI.changed)
        {
            CheckBlenderAppExists();
        }

        this.Repaint();
    }
    public void runtest(RendererShaderParams myScript)
    {
        var animator          = myScript.GetComponentInParent <Animator> ();
        var childrenRenderers = animator.GetComponentsInChildren <Renderer> ();

        //ArmatureLinker linker = animator.transform.GetComponentInChildren<ArmatureLinker> ();

        MakehumanRenderer[] makehumanRenderers = new MakehumanRenderer[childrenRenderers.Length];


        List <string> bonesList = new List <string> ();

        //foreach (Renderer renderer in childrenRenderers) {

        Debug.Log(childrenRenderers.Length);

        for (int i = 0; i < childrenRenderers.Length; i++)
        {
            Renderer renderer = childrenRenderers [i];

            makehumanRenderers [i] = new MakehumanRenderer {
                renderer = renderer,
                type     = MakehumanMeshBoneType.none
            };


            var skinnedRenderer = renderer.GetComponent <SkinnedMeshRenderer> ();
            if (skinnedRenderer == null)
            {
                continue;
            }

            var weights = skinnedRenderer.sharedMesh.boneWeights;
            //var allBones = skinnedRenderer.bones;

            bonesList.Clear();

            foreach (var weight in weights)
            {
                var bIdx  = weight.boneIndex0;
                var bTran = skinnedRenderer.bones [bIdx];

                if (!bonesList.Contains(bTran.name))
                {
                    bonesList.Add(bTran.name);
                    //Debug.Log (bTran.name);
                }
            }


            if (bonesList.Count == 2 &&
                new string[] {
                "eye.R",
                "eye.L"
            }.All(n => bonesList.Contains(n)))
            {
                //Debug.Log ("I THINK THIS IS AN EYE");
                makehumanRenderers [i].type = MakehumanMeshBoneType.eyeballs;
                continue;
            }


            if (bonesList.Count == 5 &&
                new string[] {
                "head",
                "orbicularis03.R",
                "orbicularis03.L",
                "orbicularis04.R",
                "orbicularis04.L"
            }.All(n => bonesList.Contains(n)))
            {
                //Debug.Log ("I THINK THIS IS AN EYELASH");
                makehumanRenderers [i].type = MakehumanMeshBoneType.eyelashes;
                continue;
            }


            if (bonesList.Count == 3 &&
                new string[] {
                "head",
                "oculi01.R",
                "oculi01.L"
            }.All(n => bonesList.Contains(n)))
            {
                //Debug.Log ("I THINK THIS IS AN EYEBROW");
                makehumanRenderers [i].type = MakehumanMeshBoneType.eyebrows;
                continue;
            }


            if (bonesList.Count == 2 &&
                new string[] {
                "jaw",
                "head"
            }.All(n => bonesList.Contains(n)))
            {
                //Debug.Log ("I THINK THIS IS TEETH");
                makehumanRenderers [i].type = MakehumanMeshBoneType.teeth;
                continue;
            }


            if (bonesList.Count == 10 &&
                new string[] {
                "tongue07.R",
                "tongue04",
                "tongue07.L",
                "tongue03",
                "tongue06.L",
                "tongue05.L",
                "tongue02",
                "tongue01",
                "tongue06.R",
                "tongue05.R",
            }.All(n => bonesList.Contains(n)))
            {
                //Debug.Log ("I THINK THIS IS A TONGUE");
                makehumanRenderers [i].type = MakehumanMeshBoneType.tongue;
                continue;
            }
        }



        foreach (MakehumanRenderer makehumanRenderer in makehumanRenderers)
        {
            var renderer = makehumanRenderer.renderer;

            if (renderer != null)
            {
                renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
                renderer.receiveShadows    = true;

                var material = renderer.sharedMaterial;

                var mainColor = material.GetColor("_Color");
                mainColor.a = 1.0f;                 //always do this, just because unity is weird and seemingly random alpha values always appear
                material.SetColor("_Color", mainColor);



                if (makehumanRenderer.type != MakehumanMeshBoneType.none)
                {
                    renderer.reflectionProbeUsage = UnityEngine.Rendering.ReflectionProbeUsage.Off;
                    renderer.shadowCastingMode    = UnityEngine.Rendering.ShadowCastingMode.Off;


                    switch (makehumanRenderer.type)
                    {
                    case MakehumanMeshBoneType.eyeballs:
                        break;

                    case MakehumanMeshBoneType.eyebrows:
                    case MakehumanMeshBoneType.eyelashes:
                        material.shader = Shader.Find("Sprites/Default");
                        break;

                    case MakehumanMeshBoneType.teeth:
                    case MakehumanMeshBoneType.tongue:
                        //if (renderer.GetComponent<SkinnedMeshRenderer> ()) {
                        //	renderer.GetComponent<SkinnedMeshRenderer> ().updateWhenOffscreen = false;
                        //}
                        break;
                    }
                }
                else if (false)                    //blenderMaterial.key.ToLower ().Contains ("hair")) {
                {
                    material.shader = Shader.Find("Hair/Standard Two Sided Soft Blend");
                    material.SetFloat("_Cutoff", 0.05f);
                }
            }
        }
    }
コード例 #4
0
    void OnGUI()
    {
        var      customButton = new GUIStyle("Button");
        GUIStyle customLabel;

        customLabel             = new GUIStyle("Label");
        customLabel.fixedHeight = 50;

        GUI.Box(new Rect(0, 0, 50, 50), new GUIContent("", logotex), customLabel);

        Rect r = (Rect)EditorGUILayout.BeginVertical(customLabel);

        customLabel                  = new GUIStyle("Label");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 14;
        customLabel.normal.textColor = Color.black;
        customLabel.fontStyle        = FontStyle.Bold;

        GUILayout.Label("Custom Avatar Builder", customLabel);

        customLabel                  = new GUIStyle("Label");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 11;
        customLabel.normal.textColor = new Color(0.5f, 0.5f, 0.5f);
        customLabel.fontStyle        = FontStyle.Bold;

        GUILayout.Label(string.Format("Version: {0} (Lite)", Application.version), customLabel);

        EditorGUILayout.EndVertical();


        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 10;
        customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
        customLabel.fontStyle        = FontStyle.Italic;
        customLabel.fixedWidth       = 100;
        customLabel.normal.textColor = new Color(0.7f, 0.0f, 0.0f);

        //EditorGUILayout.LabelField("PATH WARNING!", customLabel, GUILayout.Width(100));

        if (!SystemInfo.operatingSystem.ToLower().Contains("windows 10"))
        {
            if (Application.dataPath.Length > 40)
            {
                if (GUILayout.Button("PATH WARNING!", customLabel))
                {
                    EditorUtility.DisplayDialog("Warning",
                                                string.Format(
                                                    "Your OS is: \"{0}\" which may experience issues with long paths." +
                                                    "\n\nIt would be wise to move this Builder project as close to \"C:\\\" as possible." +
                                                    "\n\nCurrent application datapath:\n{1}",
                                                    SystemInfo.operatingSystem, Application.dataPath
                                                    ),
                                                "Ok");

                    return;
                }
            }
        }

        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 14;
        customLabel.normal.textColor = new Color(0.0f, 0.0f, 1.0f);
        customLabel.fontStyle        = FontStyle.Bold;


        EditorGUILayout.LabelField("Select the .blend file to process:");
        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 10;
        customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
        customLabel.fontStyle        = FontStyle.Italic;
        customLabel.fixedWidth       = 100;


        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 14;
        customLabel.normal.textColor = new Color(0.0f, 0.0f, 1.0f);
        customLabel.fontStyle        = FontStyle.Bold;


        if (GUILayout.Button("Import Avatar Model", customLabel))
        {
            if (characterType == (int)ArmatureLinker.CharacterType.DEFAULT)
            {
                var enumName = System.Enum.GetName(typeof(ArmatureLinker.CharacterType), ArmatureLinker.CharacterType.DEFAULT);
                Debug.LogError(string.Format("You must specify a character type (\"{0}\" is not a valid selection)", enumName));
                EditorUtility.DisplayDialog("Error",
                                            string.Format("Character type: \"{0}\" is not a valid selection!\n\nPlease select a desired character type first.", enumName),
                                            "Ok");

                return;
            }

            if (!string.IsNullOrEmpty(blenderAppPath) && !File.Exists(blenderAppPath))
            {
                EditorUtility.DisplayDialog("Blender Application Is Not Set",
                                            "Please browse for and select the installed Blender application. Must be version 2.79b.", "OK");
                return;
            }
            PlayerSettings.colorSpace = ColorSpace.Linear;

            AssetDatabase.RemoveUnusedAssetBundleNames();

            var modelPath = EditorUtility.OpenFilePanel(string.Format("Load {0} model", getCharacterTypesArray[characterType].ToLower()), modelPathLast, "blend");

            if (!string.IsNullOrEmpty(modelPath))
            {
                modelPathLast = Path.GetDirectoryName(modelPath);
                if (Path.GetExtension(modelPath).Equals(".blend"))
                {
                    if (!RunBatch(AnimPrepAssetPostprocessor.AssetBundleVariant, modelPath, blenderAppPath))
                    {
                        EditorUtility.DisplayDialog("No AssetCreator.exe Tool",
                                                    "Please ensure the AssetCreator.exe tool in located in the AnimPrep directory.", "OK");
                        return;
                    }

                    var baseName = Path.GetFileNameWithoutExtension(modelPath);

                    modelPath = Path.Combine(
                        Path.Combine(
                            Path.GetDirectoryName(modelPath), baseName.ToLower() + string.Format("_{0}", AnimPrepAssetPostprocessor.AssetBundleVariant.ToLower())
                            ),
                        baseName + ".fbx"
                        );
                }

                var uploadFolder = Path.GetDirectoryName(modelPath);

                //var userName = Path.GetFileName (SystemInfo.deviceName);

                var uploadFolderTop = new DirectoryInfo(uploadFolder).Name;

                var uploadName = System.Guid.NewGuid().ToString();                  // Path.GetFileName (uploadFolder);

                var processingPath = AnimPrepAssetPostprocessor.processingFolder;   // Path.Combine(Application.dataPath, "MakeHumanModels");
                //processingPath = Path.Combine (processingPath, userName);
                processingPath = Path.Combine(processingPath, uploadName);

                System.IO.Directory.CreateDirectory(processingPath);


                DirectoryInfo dir        = new DirectoryInfo(uploadFolder);
                FileInfo[]    modelsInfo = dir.GetFiles("*.fbx");

                if (modelsInfo.Length == 0)
                {
                    Debug.LogError("modelsInfo was empty. No .fbx file could be loaded.");
                    return;
                }

                string uid = uploadName.Replace(AnimPrepAssetPostprocessor.templateSeperator.ToString(), "");                 // uploadFolderTop.Replace("$", "");


                //Copy all model files
                foreach (FileInfo f in modelsInfo)
                {
                    var to = Path.Combine(
                        processingPath,
                        AnimPrepAssetPostprocessor.AssetBundleVariant +
                        AnimPrepAssetPostprocessor.templateSeperator +                        //"$"
                        uid +
                        AnimPrepAssetPostprocessor.templateSeperator +                        //"$"
                        f.Name
                        );
                    FileUtil.CopyFileOrDirectory(f.FullName, to);
                }

                //Copy all .json files
                FileInfo[] jsonInfo = dir.GetFiles("*.json");
                foreach (FileInfo f in jsonInfo)
                {
                    var to = Path.Combine(processingPath, f.Name);
                    FileUtil.CopyFileOrDirectory(f.FullName, to);
                }

                //Copy all images files
                var textures_path = Path.Combine(uploadFolder, "textures");
                if (Directory.Exists(textures_path))
                {
                    string[] extensions = new[] { ".png", ".jpg", ".tiff", ".bmp" };

                    DirectoryInfo dir_images = new DirectoryInfo(textures_path);

                    FileInfo[] texturesInfo =
                        dir_images.GetFiles()
                        .Where(f => extensions.Contains(f.Extension.ToLower()))
                        .ToArray();

                    foreach (FileInfo f in texturesInfo)
                    {
                        var to = Path.Combine(processingPath, f.Name);
                        FileUtil.CopyFileOrDirectory(f.FullName, to);
                    }
                }

                AnimPrepAssetPostprocessor.AssetBundleUserJson userPrefs = new AnimPrepAssetPostprocessor.AssetBundleUserJson()
                {
                    created    = System.DateTime.UtcNow,
                    variantTag = getCharacterTypesArray[characterType],                    //use the index of the users selection to get then enum name from the chracter types //  AnimPrepAssetPostprocessor.ReallusionAssetVariantTag,
                    //user = userName,
                    //uploadFolder = uploadName,
                    characterFolder = Path.GetDirectoryName(modelPath)
                };

                string json     = JsonUtility.ToJson(userPrefs);
                var    jsonPath = Path.Combine(AnimPrepAssetPostprocessor.assetBundlesFolder, uid + ".json");
                using (StreamWriter sr = new StreamWriter(jsonPath)) {                  // Create the file.
                    sr.WriteLine(json);
                }


                AssetDatabase.Refresh();

                BuildScript.BuildAssetBundles();

                AssetDatabase.Refresh();

                Debug.Log(string.Format("Created new {0} character!\nPress \"Append Prefabs To Scene\" button to see the newly created character.", getCharacterTypesArray[characterType].ToLower()));
            }
        }
        GUILayout.BeginHorizontal();


        characterType = EditorGUILayout.Popup("Character Type:", characterType, getCharacterTypesArray, GUILayout.MinWidth(100));


        GUILayout.EndHorizontal();

        EditorGUILayout.Space();



        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 14;
        customLabel.normal.textColor = new Color(0.0f, 0.5f, 0.0f);
        customLabel.fontStyle        = FontStyle.Bold;

        EditorGUILayout.LabelField("Save changes to assetbundles:");
        if (GUILayout.Button("Re-Build Assetbundles", customLabel))
        {
            var allPaths = AssetDatabase.GetAllAssetPaths();
            foreach (var assetPath in allPaths)
            {
                if (assetPath.StartsWith(AnimPrepAssetPostprocessor.prefabsFolder))
                {
                    //ensure the prefab is enabled before saving as assetbundle

                    string     modelFileName = Path.GetFileNameWithoutExtension(assetPath);
                    GameObject modelAsset    = AssetDatabase.LoadAssetAtPath <GameObject> (assetPath);                 //LOADING AN ASSET
                    if (modelAsset == null)
                    {
                        continue;
                    }

                    if (!modelAsset.activeSelf)
                    {
                        GameObject model = (GameObject)PrefabUtility.InstantiatePrefab(modelAsset);
                        model.SetActive(true);
                        PrefabUtility.SaveAsPrefabAsset(model, assetPath);
                        GameObject.DestroyImmediate(model);
                    }
                }
            }

            var allShaderKeywordParams = GameObject.FindObjectsOfType <RendererShaderParams> ();

            foreach (var shaderKeywordParams in allShaderKeywordParams)
            {
                shaderKeywordParams.StoreParams();
            }

            var allRootGos = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
            foreach (var go in allRootGos)
            {
                //bool isPrefabInstance = PrefabUtility.GetPrefabParent(go) != null && PrefabUtility.GetPrefabObject(go.transform) != null;
                bool isPrefabInstance = PrefabUtility.GetCorrespondingObjectFromOriginalSource(go) != null && PrefabUtility.GetCorrespondingObjectFromOriginalSource(go.transform) != null;
                if (isPrefabInstance)
                {
                    RendererShaderParams.StoreAllRenderers(go);

                    //PrefabUtility.ReplacePrefab(go, PrefabUtility.GetPrefabParent(go), ReplacePrefabOptions.ConnectToPrefab);
                    PrefabUtility.SaveAsPrefabAssetAndConnect(go, PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(go), InteractionMode.AutomatedAction);
                }
            }

            AssetDatabase.Refresh();
            BuildScript.BuildAssetBundles();
            AssetDatabase.Refresh();

            ShowAssetBundlesExplorer();
        }



        EditorGUILayout.Space();

        customLabel           = new GUIStyle("Button");
        customLabel.alignment = TextAnchor.MiddleCenter;
        customLabel.fontSize  = 12;
        //customLabel.normal.textColor = new Color(0.0f,0.5f,0.0f);
        customLabel.fontStyle = FontStyle.Italic;

        EditorGUILayout.LabelField("Add processed models to scene:");

        if (GUILayout.Button("Append Prefabs To Scene", customLabel))
        {
            //Vector3 offsetSpacing = Vector3.right * 1.5f;

            var info     = new DirectoryInfo(AnimPrepAssetPostprocessor.prefabsFolder);
            var fileInfo = info.GetFiles("*.prefab", SearchOption.TopDirectoryOnly);

            for (int i = 0; i < fileInfo.Length; i++)
            {
                var file = fileInfo[i];

                if (Path.GetExtension(file.FullName).Equals(".meta"))
                {
                    continue;
                }


                string fullPath  = file.FullName.Replace(@"\", "/");
                string assetPath = "Assets" + fullPath.Replace(Application.dataPath, "");


                bool alreadyInScene = false;
                var  allRootGos     = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();
                foreach (var go in allRootGos)
                {
                    //bool isPrefabInstance = PrefabUtility.GetPrefabParent(go) != null && PrefabUtility.GetPrefabObject(go.transform) != null;
                    bool isPrefabInstance = PrefabUtility.GetCorrespondingObjectFromSource(go) != null && PrefabUtility.GetCorrespondingObjectFromSource(go.transform) != null;

                    if (isPrefabInstance)
                    {
                        //Object parentObject = EditorUtility.GetPrefabParent(go);
                        Object parentObject = PrefabUtility.GetCorrespondingObjectFromSource(go);
                        string path         = AssetDatabase.GetAssetPath(parentObject);

                        if (assetPath.Equals(path))
                        {
                            alreadyInScene = true;
                            break;
                        }
                    }
                }
                if (alreadyInScene)
                {
                    continue;
                }



                UnityEngine.Object prefab = AssetDatabase.LoadMainAssetAtPath(assetPath);

                GameObject clone = PrefabUtility.InstantiatePrefab(prefab as GameObject) as GameObject;

                //clone.transform.position = offsetSpacing * i;
            }
        }



        EditorGUILayout.Space();

        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 12;
        customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
        customLabel.fontStyle        = FontStyle.Italic;

        EditorGUILayout.LabelField("Show folder containing output files:");
        if (GUILayout.Button("Open Assetbundles Folder", customLabel))
        {
            ShowAssetBundlesExplorer();
        }


        EditorGUILayout.Space();



        GUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Blender Application (v2.79b):", GUILayout.MinWidth(0));

        customLabel           = new GUIStyle("Label");
        customLabel.alignment = TextAnchor.MiddleCenter;
        customLabel.fontStyle = FontStyle.BoldAndItalic;

        if (blenderAppExists)
        {
            customLabel.normal.textColor = new Color(0.0f, 0.5f, 0.0f);
            EditorGUILayout.LabelField("File Exists", customLabel, GUILayout.Width(100));
        }
        else
        {
            customLabel.normal.textColor = new Color(0.5f, 0.0f, 0.0f);
            EditorGUILayout.LabelField("File Missing!", customLabel, GUILayout.Width(100));

            customButton                  = new GUIStyle("Button");
            customButton.alignment        = TextAnchor.MiddleCenter;
            customButton.fontSize         = 10;
            customButton.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
            customButton.fontStyle        = FontStyle.Italic;
            customButton.fixedWidth       = 100;
            if (GUILayout.Button("Default", customButton))
            {
                blenderAppPath = blenderAppPathDefault;
            }
        }
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();

        customLabel                  = new GUIStyle("Button");
        customLabel.alignment        = TextAnchor.MiddleCenter;
        customLabel.fontSize         = 10;
        customLabel.normal.textColor = new Color(0.2f, 0.2f, 0.2f);
        customLabel.fontStyle        = FontStyle.Italic;
        customLabel.fixedWidth       = 100;

        blenderAppPath = GUILayout.TextField(blenderAppPath, GUILayout.MinWidth(0));
        if (GUILayout.Button("Browse", customLabel))
        {
            string modelPath = EditorUtility.OpenFilePanel("Blender Application (v2.79b)", Path.GetDirectoryName(blenderAppPath), "exe");
            if (!string.IsNullOrEmpty(modelPath))
            {
                blenderAppPath = modelPath;
            }
        }
        GUILayout.EndHorizontal();
        EditorGUILayout.Space();

        customLabel           = new GUIStyle("Label");
        customLabel.alignment = TextAnchor.MiddleCenter;
        customLabel.fontStyle = FontStyle.Italic;
        GUILayout.Label(string.Format("{0} - {1}", Application.unityVersion, SystemInfo.operatingSystem), customLabel);

        if (GUI.changed)
        {
            CheckBlenderAppExists();
        }

        this.Repaint();
    }
コード例 #5
0
    static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        foreach (string importedAssetPath in importedAssets)
        {
            Debug.Log("AOnPostprocessAllAssets " + importedAssetPath);
            if (Path.GetExtension(importedAssetPath) == ".meta")
            {
                continue;
            }

            string assetPath = importedAssetPath.Replace('/', Path.DirectorySeparatorChar);              //fix the path so that it uses the correct seperator for this system

            string   assetFileName = Path.GetFileName(assetPath);
            string[] split         = assetFileName.Split(templateSeperator);

            if (split.Length != 3)
            {
                continue;
            }

            string uuid      = split[1];
            string assetName = split[2];

            string assetFolder = Path.GetDirectoryName(assetPath);



            if (assetPath.StartsWith(processingFolder))               //Looking for the copied .fbx file that resides in the projects processing/prefab folder


            {
                if (!assetPath.EndsWith(".fbx", StringComparison.OrdinalIgnoreCase))                   //only check if .fbx is in the processing folder
                {
                    continue;
                }
                GameObject modelAsset = AssetDatabase.LoadAssetAtPath <GameObject> (assetPath);                //LOADING AN ASSET

                string jsonPath = Path.Combine(assetBundlesFolder, uuid + ".json");

                if (!File.Exists(jsonPath))
                {
                    Debug.LogError("SKIPPING - The JSON file did not exist at path: " + jsonPath);
                    continue;
                }

                ModelImporter modelImporter = ModelImporter.GetAtPath(assetPath) as ModelImporter;

                string jsonTxt = File.ReadAllText(jsonPath);
                AssetBundleUserJson userPrefs = (AssetBundleUserJson)JsonUtility.FromJson(jsonTxt, typeof(AssetBundleUserJson));

                //RE-IMPORTED SECTION (SECOND-IMPORT):
                if (!Directory.Exists(prefabsFolder))
                {
                    Directory.CreateDirectory(prefabsFolder);
                }

                string modelFileName   = Path.GetFileNameWithoutExtension(assetPath);
                string destinationPath = Path.Combine(prefabsFolder, modelFileName + ".prefab");

                GameObject model = (GameObject)PrefabUtility.InstantiatePrefab(modelAsset);
                GameObject real  = GameObject.Instantiate(model);                //this is a game object that we can re-arange and change parenting or objects, then save as the original prefab later on
                real.SetActive(true);

                real.name = model.name;                 //remove "(clone) or any other discrepancies from name"
                GameObject.DestroyImmediate(model);     //destroy the prefab as it will be overwritten by "real"

                var defaultController = Resources.Load <RuntimeAnimatorController>("DefaultAnimationController");
                if (defaultController != null)
                {
                    real.transform.root.GetComponentInChildren <Animator> ().runtimeAnimatorController = defaultController;
                }


                //Build the prop and set all data arrays
                var buildProp = real.AddComponent <BuildProp> ();
                buildProp.CreateEmptyContianers(real.name);
                GameObject.DestroyImmediate(buildProp);                  //no long need this component, so destroy it.



                string blenderJsonPath = Path.Combine(assetFolder, "blender.json");

                Dictionary <string, MaterialsJson> materialsJson = null;

                if (File.Exists(blenderJsonPath))
                {
                    BlenderJsonObject blenderJsonArray = JsonUtility.FromJson <BlenderJsonObject> (
                        File.ReadAllText(blenderJsonPath)
                        );

                    materialsJson = BuildMaterialsDict(blenderJsonArray.materials);
                }

                var childrenRenderers = real.GetComponentsInChildren <Renderer>();

                foreach (Renderer renderer in childrenRenderers)
                {
                    if (renderer == null)
                    {
                        continue;
                    }

                    renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
                    renderer.receiveShadows    = true;

                    foreach (var material in renderer.sharedMaterials)
                    {
                        //var material = renderer.sharedMaterial;

                        var mainColor = material.GetColor("_Color");
                        mainColor.a = 1.0f;                         //always do this, just because unity is weird and seemingly random alpha values always appear
                        material.SetColor("_Color", mainColor);


                        if (materialsJson != null)
                        {
                            //THE NEW WAY (USING BLENDER MATERIALS JSON)
                            //var textureFileName = Path.GetFileName (AssetDatabase.GetAssetPath (material.mainTexture)); //takes a full path to an texture asset, and returs the filename with extension (which is used as key for materials json)
                            var was          = Path.GetFileName(AssetDatabase.GetAssetPath(material.mainTexture));
                            var materialName = material.name;                            // Path.GetFileName (AssetDatabase.GetAssetPath (material.mainTexture)); //takes a full path to an texture asset, and returs the filename with extension (which is used as key for materials json)
                            if (material.mainTexture != null)
                            {
                                materialName = Path.GetFileName(AssetDatabase.GetAssetPath(material.mainTexture));                                   //takes a full path to an texture asset, and returs the filename with extension (which is used as key for materials json)
                            }
                            materialName = Path.GetFileNameWithoutExtension(materialName);

                            if (materialsJson.ContainsKey(materialName))
                            {
                                //if (materialsJson.ContainsKey (textureFileName)) {

                                //var blenderMaterial = materialsJson [textureFileName];
                                var blenderMaterial = materialsJson [materialName];


                                Texture2D diffTex     = null;
                                Texture2D bumpTex     = null;
                                Texture2D specularTex = null;
                                Texture2D emissionTex = null;

                                bool  enableAlpha = false;
                                float emit_factor = 0;

                                var use_map_color_diffuse = false;
                                var use_map_bump          = false;
                                var use_map_specular      = false;
                                var use_map_emit          = false;

                                foreach (var slot in blenderMaterial.texture_slots)                                   //check all slots to see if there are any spec or emmit textures
                                {
                                    if (slot.use_map_color_diffuse)
                                    {
                                        //var texPath = AssetDatabase.GetAssetPath (material.mainTexture);
                                        var texPath = Path.Combine(Path.GetDirectoryName(assetPath), slot.filename);
                                        if (File.Exists(texPath))
                                        {
                                            var folder = Path.GetDirectoryName(texPath);
                                            diffTex = AssetDatabase.LoadAssetAtPath(Path.Combine(folder, slot.filename), typeof(Texture2D)) as Texture2D;

                                            TextureImporter A = (TextureImporter)AssetImporter.GetAtPath(Path.Combine(folder, slot.filename));
                                            enableAlpha = blenderMaterial.use_transparency && A.DoesSourceTextureHaveAlpha();
                                        }
                                    }
                                    if (slot.use_map_normal)
                                    {
                                        //Debug.Log("use_map_normal " + slot.filename);
                                        //var texPath = AssetDatabase.GetAssetPath (material.mainTexture);
                                        var texPath = Path.Combine(Path.GetDirectoryName(assetPath), slot.filename);
                                        if (File.Exists(texPath))
                                        {
                                            var folder = Path.GetDirectoryName(texPath);
                                            bumpTex = AssetDatabase.LoadAssetAtPath(Path.Combine(folder, slot.filename), typeof(Texture2D)) as Texture2D;
                                        }
                                    }
                                    if (slot.use_map_specular)
                                    {
                                        //Debug.Log("use_map_specular " + slot.filename);
                                        //var texPath = AssetDatabase.GetAssetPath (material.mainTexture);
                                        var texPath = Path.Combine(Path.GetDirectoryName(assetPath), slot.filename);
                                        if (File.Exists(texPath))
                                        {
                                            var folder = Path.GetDirectoryName(texPath);
                                            specularTex = AssetDatabase.LoadAssetAtPath(Path.Combine(folder, slot.filename), typeof(Texture2D)) as Texture2D;
                                        }
                                    }
                                    if (slot.use_map_emit)
                                    {
                                        //Debug.Log("use_map_emit " + slot.filename);
                                        //var texPath = AssetDatabase.GetAssetPath (material.mainTexture);
                                        var texPath = Path.Combine(Path.GetDirectoryName(assetPath), slot.filename);
                                        if (File.Exists(texPath))
                                        {
                                            var folder = Path.GetDirectoryName(texPath);
                                            emissionTex = AssetDatabase.LoadAssetAtPath(Path.Combine(folder, slot.filename), typeof(Texture2D)) as Texture2D;
                                        }
                                        emit_factor = slot.emit_factor;
                                    }

                                    use_map_color_diffuse |= slot.use_map_color_diffuse;
                                    use_map_bump          |= slot.use_map_normal;
                                    use_map_specular      |= slot.use_map_specular;
                                    use_map_emit          |= slot.use_map_emit;
                                }

                                var specIsBlack =
                                    (blenderMaterial.specular_color.r * blenderMaterial.specular_intensity) == 0
                                    &&
                                    (blenderMaterial.specular_color.g * blenderMaterial.specular_intensity) == 0
                                    &&
                                    (blenderMaterial.specular_color.b * blenderMaterial.specular_intensity) == 0;

                                if (!specIsBlack || use_map_specular)
                                {
                                    material.shader = Shader.Find("Standard (Specular setup)");                                          //the default fallback shader
                                    material.SetColor("_SpecColor", new Color(
                                                          blenderMaterial.specular_color.r * blenderMaterial.specular_intensity * 0.25f, //default values are way too high for Standard shader so multiply by 0.25
                                                          blenderMaterial.specular_color.g * blenderMaterial.specular_intensity * 0.25f,
                                                          blenderMaterial.specular_color.b * blenderMaterial.specular_intensity * 0.25f
                                                          ));
                                }

                                if (use_map_color_diffuse)                                   //set all white and adjust brightness based on diffuse intensity set from blender
                                {
                                    material.SetColor("_Color", new Color(
                                                          blenderMaterial.diffuse_color.r * blenderMaterial.diffuse_intensity,
                                                          blenderMaterial.diffuse_color.g * blenderMaterial.diffuse_intensity,
                                                          blenderMaterial.diffuse_color.b * blenderMaterial.diffuse_intensity,
                                                          blenderMaterial.alpha
                                                          ));
                                }
                                else
                                {
                                    material.SetColor("_Color", new Color(                                      // has no texture, thus pass through the color and adjust on diffuse intensity set from blender
                                                          mainColor.r * blenderMaterial.diffuse_intensity,
                                                          mainColor.g * blenderMaterial.diffuse_intensity,
                                                          mainColor.b * blenderMaterial.diffuse_intensity,
                                                          blenderMaterial.alpha
                                                          ));

                                    if (blenderMaterial.use_transparency)                                       //has no texture but alpha was set, so ensure to honor that
                                    {
                                        enableAlpha = true;
                                    }
                                }

                                if (enableAlpha)                                  //change to opaque https://sassybot.com/blog/swapping-rendering-mode-in-unity-5-0/

                                {
                                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                                    material.SetInt("_ZWrite", 0);
                                    material.DisableKeyword("_ALPHATEST_ON");
                                    material.DisableKeyword("_ALPHABLEND_ON");
                                    material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
                                    material.renderQueue = 3000;
                                }
                                else                                     //OPAQUE

                                {
                                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                                    material.SetInt("_ZWrite", 1);
                                    material.DisableKeyword("_ALPHATEST_ON");
                                    material.DisableKeyword("_ALPHABLEND_ON");
                                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                                    material.renderQueue = -1;
                                }

                                if (use_map_color_diffuse)
                                {
                                    material.SetTexture("_MainTex", diffTex);
                                }
                                if (use_map_bump)
                                {
                                    material.SetTexture("_BumpMap", bumpTex);
                                }
                                if (use_map_emit)
                                {
                                    material.EnableKeyword("_EMISSION");                                      //You must enable the correct Keywords for your required Standard Shader variant
                                    material.SetTexture("_EmissionMap", emissionTex);
                                    material.SetColor("_EmissionColor", new Color(
                                                          emit_factor,
                                                          emit_factor,
                                                          emit_factor
                                                          ));
                                }

                                if (use_map_specular)
                                {
                                    material.EnableKeyword("_SPECGLOSSMAP");                                      //You must enable the correct Keywords for your required Standard Shader variant
                                    material.SetTexture("_SpecGlossMap", specularTex);
                                }

                                material.SetFloat("_GlossMapScale", blenderMaterial.specular_hardness / 511f);
                                material.SetFloat("_Glossiness", blenderMaterial.specular_hardness / 511f);
                                material.SetFloat("_Shininess", blenderMaterial.specular_hardness / 511f);                                  //synonmus with _Glossiness if using legacy shaders

                                if (!use_map_specular && !use_map_emit)
                                {
                                    /*if (blenderMaterial.key.ToLower ().Contains ("hair")) {
                                     *      material.shader = Shader.Find ("Hair/Standard Two Sided Soft Blend");
                                     *      material.SetFloat ("_Cutoff", 0.05f);
                                     * } else if (
                                     *      blenderMaterial.key.ToLower ().Contains ("eye") && (
                                     *              blenderMaterial.key.ToLower ().Contains ("lash")
                                     ||
                                     ||             blenderMaterial.key.ToLower ().Contains ("brow")
                                     ||     )) { //if its hair sprites
                                     ||     material.shader = Shader.Find ("Sprites/Default");
                                     ||     continue; //it's no longer a stander shader, nothing more to be done
                                     ||}*/

                                    if (blenderMaterial.key.ToLower().Contains("hair"))
                                    {
                                        material.shader = Shader.Find("Hair/Standard Two Sided Soft Blend");
                                        material.SetFloat("_Cutoff", 0.05f);
                                    }
                                }
                            }
                        }
                        else
                        {
                            /*
                             * material.shader = Shader.Find ("Standard (Specular setup)"); //the default fallback shader
                             * //THE OLD WAY - USE KEYWORDS IN MATERIAL NAME TO CONTROL SHADER KEYWORDS
                             *
                             * var color222 = material.GetColor ("_Color");
                             *
                             * color222.a = 1.0f; //always do this, just because unity is weird and seemingly random alpha values always appear
                             * material.SetColor ("_Color", color222);
                             *
                             * if (material.mainTexture != null) {
                             *
                             *      string path = AssetDatabase.GetAssetPath (material.mainTexture);
                             *      TextureImporter A = (TextureImporter)AssetImporter.GetAtPath (path);
                             *
                             *      if (!A.DoesSourceTextureHaveAlpha ()) {//change to opaque https://sassybot.com/blog/swapping-rendering-mode-in-unity-5-0/
                             *              material.SetInt ("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                             *              material.SetInt ("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                             *              material.SetInt ("_ZWrite", 1);
                             *              material.DisableKeyword ("_ALPHATEST_ON");
                             *              material.DisableKeyword ("_ALPHABLEND_ON");
                             *              material.DisableKeyword ("_ALPHAPREMULTIPLY_ON");
                             *              material.renderQueue = -1;
                             *      }
                             *
                             *      var matTextureName = material.mainTexture.name.ToLower ();
                             *      //Debug.Log ("MAT NAME " + matTextureName);
                             *      var texPath = AssetDatabase.GetAssetPath (material.mainTexture);
                             *      var texName = Path.GetFileNameWithoutExtension (texPath);
                             *
                             *      //Debug.Log ("matTextureName" + matTextureName);
                             *      //Debug.Log ("Texture Path" + texPath);
                             *
                             *      Texture specularTex = GetFileByKeywords (texPath, new[] {
                             *              "_Spec",
                             *              "_spec",
                             *              "_Specularity",
                             *              "_specularity",
                             *              "_Specular",
                             *              "_specular"
                             *      });
                             *      Texture metallicTex = GetFileByKeywords (texPath, new[] { "_Metallic", "_metallic" });
                             *
                             *      if (specularTex != null) {
                             *              //Debug.Log ("JUST SET SPECULAR SETUP!! " + specularTex);
                             *              material.shader = Shader.Find ("Standard (Specular setup)");
                             *              material.EnableKeyword ("_SPECGLOSSMAP"); //You must enable the correct Keywords for your required Standard Shader variant
                             *              material.SetTexture ("_SpecGlossMap", specularTex);
                             *              material.SetColor ("_SpecColor", Color.white);
                             *      } else {
                             *              if (metallicTex != null) {
                             *                      material.EnableKeyword ("_METALLICGLOSSMAP"); //You must enable the correct Keywords for your required Standard Shader variant
                             *                      material.SetTexture ("_MetallicGlossMap", metallicTex);
                             *              }
                             *      }
                             *
                             *      Texture emissionTex = GetFileByKeywords (texPath, new[] { "_Emission", "_emission" });
                             *      if (emissionTex != null) {
                             *              material.EnableKeyword ("_EMISSION"); //You must enable the correct Keywords for your required Standard Shader variant
                             *              material.SetTexture ("_EmissionMap", emissionTex);
                             *              material.SetColor ("_EmissionColor", Color.white);
                             *      }
                             *
                             *      if (specularTex == null && emissionTex == null) {
                             *              if (matTextureName.Contains ("_hair")) {
                             *                      material.shader = Shader.Find ("Custom/Standard Two Sided Soft Blend");
                             *                      material.SetFloat ("_Cutoff", 0.05f);
                             *              } else if (
                             *                      matTextureName.Contains ("eyelash") ||
                             *                      matTextureName.Contains ("eyebrow")) { //if its hair sprites
                             *                      material.shader = Shader.Find ("Sprites/Default");
                             *                      continue; //it's no longer a stander shader, nothing more to be done
                             *              }
                             *      }
                             * }
                             *
                             *
                             * if (material.HasProperty ("_Mode") && material.GetFloat ("_Mode").Equals (3)) { //if the exported material has transparency
                             *      //Debug.Log ("MODE 3 " + material);
                             *      if (color222.a >= 0.9f) { //because blender/unity are weird, and setting blender to 1 results in unity using opaque mode
                             *              color222.a = 1.0f;
                             *              material.SetColor ("_Color", color222);
                             *      }
                             *      //material.SetFloat("_Mode", 3);
                             *      //material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                             *      //material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                             *      //material.SetInt("_ZWrite", 0);
                             *      //material.DisableKeyword("_ALPHATEST_ON");
                             *      //material.EnableKeyword("_ALPHABLEND_ON");
                             *      //material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                             *      //material.renderQueue = 3000;
                             * }
                             */
                        }
                    }

                    //var shaderParams = renderer.gameObject.AddComponent<RendererShaderParams> ();
                    //shaderParams.StoreParams (); //NOW USING RendererShaderParams.StoreAllRenderers (real);
                }


                RendererShaderParams.StoreAllRenderers(real);

                if (modelImporter.userData.Contains(processedTag))
                {
                    string json = JsonUtility.ToJson(userPrefs);
                    using (StreamWriter sr = new StreamWriter(jsonPath))                     // Create the file.
                    {
                        sr.WriteLine(json);
                    }
                }

                PrefabUtility.SaveAsPrefabAsset(real, destinationPath);

                GameObject.DestroyImmediate(real);
            }
            else if (assetPath.StartsWith(prefabsFolder))                  //ASSET BUNDLE FINAL PROCESSING
            {
                Debug.Log("ASSET BUNDLE FINAL PROCESSING 1");
                var assetImport = AssetImporter.GetAtPath(assetPath);
                assetImport.SetAssetBundleNameAndVariant(Path.GetFileNameWithoutExtension(assetPath), assetBundleVariant);
            }
            else if (assetPath.StartsWith(assetBundlesFolder))                  //ASSET BUNDLE FINAL PROCESSING

            {
                if (!Path.GetExtension(assetPath).Contains(assetBundleVariant))
                {
                    continue;                     //might be a .meta file, just ignore it
                }

                var rootObjs = new List <GameObject>();
                foreach (var item in UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects())
                {
                    if (item.activeSelf)                       //only store active go's, so that we may disable them during portrait pictures, them re-enable them
                    {
                        rootObjs.Add(item);
                    }
                }

                string assetDestFolder = Path.Combine(assetBundlesFolder, Path.GetFileNameWithoutExtension(assetPath).ToLower());
                string jsonPath        = Path.Combine(assetFolder, uuid + ".json");

                /*if (!File.Exists (jsonPath)) {
                 *
                 *      if (Path.GetDirectoryName (assetPath).Equals(assetBundlesFolder)) {
                 *
                 *              if (Directory.Exists (assetDestFolder)) {
                 *                      FileUtil.DeleteFileOrDirectory( Path.Combine (assetDestFolder, assetFileName));
                 *                      File.Move(assetPath, Path.Combine (assetDestFolder, assetFileName));
                 *
                 *                      var thumbnailFolderAbs = Path.Combine (assetDestFolder, "thumbnails");
                 *                      TakePortraitPictures (assetFileName, rootObjs, thumbnailFolderAbs); //update the portrait pictures
                 *
                 *                      AssetDatabase.Refresh ();
                 *                      continue;
                 *              }
                 *
                 *      } else {
                 *              continue;
                 *      }
                 *
                 *      Debug.LogWarning ("SKIPPING - The JSON file did not exist at path: " + jsonPath);
                 *      continue;
                 * }*/

                if (!File.Exists(jsonPath))
                {
                    if (Path.GetDirectoryName(assetPath).Equals(assetBundlesFolder))
                    {
                        //if (Path.GetFullPath(Path.GetDirectoryName (assetPath)).Equals(Path.GetFullPath(assetBundlesFolder))) {
                        if (Directory.Exists(assetDestFolder))
                        {
                            FileUtil.DeleteFileOrDirectory(Path.Combine(assetDestFolder, assetFileName));
                            File.Move(assetPath, Path.Combine(assetDestFolder, assetFileName));

                            var thumbnailFolderAbs = Path.Combine(assetDestFolder, "thumbnails");
                            TakePortraitPictures(assetFileName, rootObjs, thumbnailFolderAbs);                              //update the portrait pictures

                            AssetDatabase.Refresh();
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }

                    Debug.LogWarning("SKIPPING - The JSON file did not exist at path: " + jsonPath);
                    continue;
                }

                string jsonTxt = File.ReadAllText(jsonPath);
                AssetBundleUserJson userPrefs = (AssetBundleUserJson)JsonUtility.FromJson(jsonTxt, typeof(AssetBundleUserJson));
                File.Delete(jsonPath);                 //no longer needed

                var to = Path.Combine(assetDestFolder, assetFileName);
                if (!Directory.Exists(Path.GetDirectoryName(to)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(to));
                }

                if (File.Exists(to))
                {
                    File.Delete(to);
                }

                FileUtil.MoveFileOrDirectory(assetPath, to);

                DirectoryInfo dir  = new DirectoryInfo(Path.GetDirectoryName(assetPath));
                FileInfo[]    info = dir.GetFiles(Path.GetFileNameWithoutExtension(assetFileName) + ".*");
                foreach (FileInfo f in info)
                {
                    File.Delete(f.FullName);
                }

                var thumbnailFolder = Path.Combine(assetDestFolder, "thumbnails");
                TakePortraitPictures(assetFileName, rootObjs, thumbnailFolder);                  //take the initial portrait pictures

                //copy the .blend character file to the final assetbundle directory if it exists
                DirectoryInfo dir_blend = new DirectoryInfo(userPrefs.characterFolder);
                FileInfo      blendInfo = dir_blend.GetFiles(Path.GetFileNameWithoutExtension(assetName) + ".blend").FirstOrDefault();

                if (blendInfo == null)
                {
                    Debug.LogWarning(String.Format("{0}.blend file could be copied.", Path.GetFileNameWithoutExtension(assetName)));
                }
                else
                {
                    ZipFile.Compress(new FileInfo(blendInfo.FullName));

                    if (File.Exists(blendInfo.FullName + ".gz"))
                    {
                        var path_blend_gz = Path.Combine(assetDestFolder, Path.GetFileNameWithoutExtension(assetFileName) + ".blend.gz");

                        FileUtil.MoveFileOrDirectory(blendInfo.FullName + ".gz", path_blend_gz);
                    }
                }

                AssetDatabase.Refresh();

                AnimPrepAssetBuilder.ShowExplorer(assetDestFolder);
            }
            else
            {
                Debug.LogWarning(assetPath + " - WAS NOT A MEMBER OF FOLDERS: " + assetBundlesFolder + " - OR - " + processingFolder);
            }

            EditorUtility.UnloadUnusedAssetsImmediate();
            System.GC.Collect();
        }
    }