Пример #1
0
        /// <summary>
        /// used for packing an alpha channel into an existing RGB texture. Uses native Unity API calls, can't be multithreaded, and is considerably slower than our own method.
        /// Currently has to run if using Mac OSX as there is no support for the system.imaging library on that operating system.
        /// Will fail if textures aren't the same resolution.
        /// </summary>
        /// <param name="cPixels"></param>
        /// <param name="invertAlpha"></param>
        /// <returns></returns>
        public static void ImportTerrainNormal(string sourcepath, string destPath)
        {
            try
            {
                if (sourcepath == null)
                {
                    return;
                }
                UnityEngine.Color[] rgbCols = ImportJPG(sourcepath) != null?ImportJPG(sourcepath).GetPixels() : null;

                UnityEngine.Color[] rgbaCols = new UnityEngine.Color[width * height];
                for (int i = 0; i < width * height; ++i)
                {
                    rgbaCols[i]   = rgbCols != null ? rgbCols[i] : new UnityEngine.Color(1.0f, 1.0f, 1.0f);
                    rgbaCols[i].g = 1.0f - rgbaCols[i].g;
                    rgbaCols[i].a = 1.0f;
                }
                Texture2D tex = new Texture2D(width, height, TextureFormat.RGBAFloat, false);
                tex.SetPixels(rgbaCols);
                File.WriteAllBytes(destPath, tex.EncodeToPNG());
                AssetDatabase.ImportAsset(destPath);
                TextureImportSetup(destPath, true, false);
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansImageUtils::Generate Terrain Normal:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
            }
        }
Пример #2
0
        /// <summary>
        /// used for packing an alpha channel into an existing RGB texture. Uses native Unity API calls, can't be multithreaded, and is considerably slower than our own method.
        /// Currently has to run if using Mac OSX as there is no support for the system.imaging library on that operating system.
        /// Will fail if textures aren't the same resolution.
        /// </summary>
        /// <param name="cPixels"></param>
        /// <param name="aPixels"></param>
        /// <param name="invertAlpha"></param>
        /// <returns></returns>
        public static Texture2D PackTextures(string rgbPath, string aPath, string savePath, bool invertAlpha = false)
        {
            try
            {
                if ((rgbPath == null) && (aPath == null))
                {
                    return(null);
                }
                UnityEngine.Color[] rgbCols = ImportJPG(rgbPath) != null?ImportJPG(rgbPath).GetPixels() : null;

                UnityEngine.Color[] aCols = ImportJPG(aPath) != null?ImportJPG(aPath).GetPixels() : null;

                UnityEngine.Color[] rgbaCols = new UnityEngine.Color[width * height];
                for (int i = 0; i < width * height; ++i)
                {
                    rgbaCols[i]   = rgbCols != null ? rgbCols[i] : new UnityEngine.Color(1.0f, 1.0f, 1.0f);
                    rgbaCols[i].a = aCols != null ? ((aCols[i].r + aCols[i].g + aCols[i].b) / 3.0f) : 1.0f;
                    rgbaCols[i].a = invertAlpha ? 1.0f - rgbaCols[i].a : rgbaCols[i].a;
                }
                Texture2D tex = new Texture2D(width, height, TextureFormat.RGBAFloat, false);
                tex.SetPixels(rgbaCols);
                File.WriteAllBytes(savePath, tex.EncodeToPNG());
                AssetDatabase.ImportAsset(savePath);
                DestroyImmediate(tex);
                return(TextureImportSetup(savePath, false));
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansImageUtils::Channel Pack RGB + A:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
                return(null);
            }
        }
Пример #3
0
 /// <summary>
 /// reads a texture file straight from hard drive absolute path, converts it to a Unity texture.
 /// </summary>
 /// <param name="sourcePath"></param>
 /// <param name="width"></param>
 /// <param name="height"></param>
 /// <returns></returns>
 public static Texture2D ImportJPG(string sourcePath)
 {
     try
     {
         if (sourcePath == null)
         {
             return(null);
         }
         if (!File.Exists(sourcePath))
         {
             Debug.LogWarning("Could not find " + sourcePath + "\nPlease make sure it is downloaded.");
             return(null);
         }
         byte[]    texData = File.ReadAllBytes(sourcePath);
         Texture2D tex     = new Texture2D(2, 2, TextureFormat.RGBAFloat, true);
         tex.LoadImage(texData);
         width  = tex.width;
         height = tex.height;
         return(tex);
     }
     catch (Exception ex)
     {
         Debug.Log("Exception::MegascansImageUtils::Import JPG:: " + ex.ToString());
         MegascansUtilities.HideProgressBar();
         return(null);
     }
 }
Пример #4
0
        /// <summary>
        /// Invert green channel of the selected texture 2D
        /// </summary>
        public static void FlipGreenChannel()
        {
            try
            {
                string sourcePath = MegascansUtilities.GetSelectedTexture();

                if (sourcePath == null)
                {
                    return;
                }

                EditorUtility.DisplayProgressBar("Bridge Plugin", "Flipping green channel...", 0.5f);
                UnityEngine.Color[] rgbCols  = ImportJPG(sourcePath).GetPixels();
                UnityEngine.Color[] rgbaCols = new UnityEngine.Color[width * height];
                for (int i = 0; i < width * height; ++i)
                {
                    rgbaCols[i]   = rgbCols != null ? rgbCols[i] : new UnityEngine.Color(1.0f, 1.0f, 1.0f);
                    rgbaCols[i].g = 1.0f - rgbaCols[i].g;
                    rgbaCols[i].a = 1.0f;
                }
                Texture2D tex = new Texture2D(width, height, TextureFormat.RGBAFloat, false);
                tex.SetPixels(rgbaCols);
                File.WriteAllBytes(sourcePath, tex.EncodeToPNG());
                AssetDatabase.ImportAsset(sourcePath);
                MegascansUtilities.HideProgressBar();
                Debug.Log("Successfully flipped green channel.");
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansImageUtils::Flip Green Channel:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
            }
        }
Пример #5
0
 static void ImportMesh(string sourcePath, string destPath)
 {
     try
     {
         MegascansUtilities.UpdateProgressBar(1.0f, "Importing Megascans Asset", "Importing Mesh...");
         if (File.Exists(sourcePath))
         {
             File.Copy(sourcePath, destPath, true);
             AssetDatabase.ImportAsset(destPath);
         }
     }
     catch (Exception ex)
     {
         Debug.Log("Exception::MegascansMeshUtils::Importing Mesh:: " + ex.ToString());
         MegascansUtilities.HideProgressBar();
     }
 }
Пример #6
0
        /// <summary>
        /// This function attempts to create a folder name
        /// </summary>
        void GetAssetFolderName(JObject objectList)
        {
            assetName       = (string)objectList["name"];
            id              = (string)objectList["id"];
            assetResolution = "";
            try {
                string namingConvention = (string)objectList["namingConvention"];
                finalName = namingConvention;
                if (namingConvention != "" && namingConvention != null)
                {
                    if (namingConvention.Contains("$id"))
                    {
                        finalName = finalName.Replace("$id", id);
                    }

                    if (namingConvention.Contains("$name"))
                    {
                        finalName = finalName.Replace("$name", assetName);
                    }

                    //Add support for $matName when it is finalized.
                    if (namingConvention.Contains("$matName"))
                    {
                        finalName = finalName.Replace("$matName", "");
                    }

                    if (namingConvention.Contains("$type"))
                    {
                        finalName = finalName.Replace("$type", (string)objectList["type"]);
                    }

                    if (namingConvention.Contains("$resolution"))
                    {
                        assetResolution = (string)objectList["resolution"];
                    }
                    return;
                }
            } catch (Exception ex) {
                Debug.Log(ex);
                MegascansUtilities.HideProgressBar();
            }

            finalName = finalName.Replace("__", "_").Replace(".", "");
            finalName = MegascansUtilities.FixSpaces(new string[] { assetName.Replace(" ", "_"), id });
        }
Пример #7
0
 /// <summary>
 /// literally just write the file to disk.
 /// </summary>
 /// <param name="tex"></param>
 /// <param name="assetPath"></param>
 public static void CreateTexture(string tex, string assetPath)
 {
     try
     {
         if ((tex == null) || (File.Exists(tex) == false))
         {
             return;
         }
         Texture2D t = ImportJPG(tex);
         File.WriteAllBytes(assetPath, t.EncodeToPNG());
         AssetDatabase.ImportAsset(assetPath);
     }
     catch (Exception ex)
     {
         Debug.Log("Exception::MegascansImageUtils::Create Texture:: " + ex.ToString());
         MegascansUtilities.HideProgressBar();
     }
 }
Пример #8
0
        static GameObject SavePrefab(GameObject prefabGo, string savePath, bool addAssetToScene = false)
        {
            try
            {
                //Set all children objects of the prefab to static
                Transform[] allChildren = prefabGo.GetComponentsInChildren <Transform>();
                foreach (Transform child in allChildren)
                {
                    child.gameObject.isStatic = true;
                }

                GameObject newPrefabObject = prefabGo;
                MegascansUtilities.UpdateProgressBar(1.0f, "Importing Megascans Asset", "Creating Prefab...");
#if UNITY_5 || UNITY_2017 || UNITY_2018
                UnityEngine.Object existingPrefab = AssetDatabase.LoadAssetAtPath(savePath, typeof(UnityEngine.Object));
                if (!existingPrefab)
                {
                    PrefabUtility.CreatePrefab(savePath, prefabGo);
                }
                else
                {
                    PrefabUtility.ReplacePrefab(prefabGo, existingPrefab, ReplacePrefabOptions.ReplaceNameBased);
                }
#else
                PrefabUtility.SaveAsPrefabAsset(prefabGo, savePath);
#endif
                DestroyImmediate(prefabGo);
                if (addAssetToScene)
                {
                    UnityEngine.Object prefabObject = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(savePath);
                    newPrefabObject          = (GameObject)PrefabUtility.InstantiatePrefab(prefabObject);
                    newPrefabObject.isStatic = true;
                }
                return(newPrefabObject);
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansMeshUtils::Saving Prefab:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
                return(null);
            }
        }
Пример #9
0
        public static void CreateTerrainLayerFromMat()
        {
            try {
                Material selectedMat = MegascansUtilities.GetSelectedMaterial();
                if (!selectedMat)
                {
                    return;
                }

                Debug.Log("Here");
                createTerrainLayer(selectedMat, 1f);

                Debug.Log("Successfully created the terrain layer.");
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansImageUtils::Flip Green Channel:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
            }
        }
Пример #10
0
        /// <summary>
        /// This function attempts to create a folder name
        /// </summary>
        void GetAssetFolderName(JObject objectList)
        {
            try {
                assetResolution = "";
                string namingConvention = (string)objectList["namingConvention"];
                finalName = namingConvention;
                if (namingConvention != "" && namingConvention != null)
                {
                    if (namingConvention.Contains("$id"))
                    {
                        finalName = finalName.Replace("$id", (string)objectList["id"]);
                    }

                    if (namingConvention.Contains("$name"))
                    {
                        finalName = finalName.Replace("$name", (string)objectList["name"]);
                    }

                    if (namingConvention.Contains("$type"))
                    {
                        finalName = finalName.Replace("$type", (string)objectList["type"]);
                    }

                    if (namingConvention.Contains("$resolution"))
                    {
                        assetResolution = (string)objectList["resolution"];
                    }
                    return;
                }
            } catch (Exception ex) {
                Debug.Log(ex);
                MegascansUtilities.HideProgressBar();
            }

            //then create a unique subfolder for the asset.
            assetName = (string)objectList["name"];
            id        = (string)objectList["id"];
            finalName = MegascansUtilities.FixSpaces(new string[] { assetName.Replace(" ", "_"), id });
            Debug.Log("Final name:" + finalName);
        }
Пример #11
0
        static GameObject SavePrefab(GameObject prefabGo, string savePath, bool addAssetToScene = false)
        {
            try
            {
                GameObject newPrefabObject = prefabGo;
                MegascansUtilities.UpdateProgressBar(1.0f, "Importing Megascans Asset", "Creating Prefab...");
#if UNITY_2019
                PrefabUtility.SaveAsPrefabAsset(prefabGo, savePath);
                DestroyImmediate(prefabGo);
                if (addAssetToScene)
                {
                    UnityEngine.Object prefabObject = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(savePath);
                    newPrefabObject = (GameObject)PrefabUtility.InstantiatePrefab(prefabObject);
                }
#else
                UnityEngine.Object existingPrefab = AssetDatabase.LoadAssetAtPath(savePath, typeof(UnityEngine.Object));
                if (!existingPrefab)
                {
                    PrefabUtility.CreatePrefab(savePath, prefabGo);
                }
                else
                {
                    PrefabUtility.ReplacePrefab(prefabGo, existingPrefab, ReplacePrefabOptions.ReplaceNameBased);
                }

                if (!addAssetToScene)
                {
                    DestroyImmediate(prefabGo);
                }
#endif
                return(newPrefabObject);
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansMeshUtils::Saving Prefab:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
                return(null);
            }
        }
Пример #12
0
 /// <summary>
 /// Sets the import settings for textures, normalmap, sRGB etc.
 /// </summary>
 /// <param name="assetPath"></param>
 /// <param name="normalMap"></param>
 /// <param name="sRGB"></param>
 public static Texture2D TextureImportSetup(string assetPath, bool normalMap, bool sRGB = true)
 {
     try
     {
         TextureImporter tImp = AssetImporter.GetAtPath(assetPath) as TextureImporter;
         if (tImp == null)
         {
             return(null);
         }
         int importResolution = Convert.ToInt32(Math.Pow(2, 9 + EditorPrefs.GetInt("QuixelDefaultImportResolution", 4)));
         tImp.maxTextureSize = importResolution;
         tImp.sRGBTexture    = sRGB;
         tImp.textureType    = normalMap ? TextureImporterType.NormalMap : TextureImporterType.Default;
         AssetDatabase.ImportAsset(assetPath);
         return(AssetDatabase.LoadAssetAtPath <Texture2D>(assetPath));
     }
     catch (Exception ex)
     {
         Debug.Log("Exception::MegascansImageUtils::Texture Import Setup:: " + ex.ToString());
         MegascansUtilities.HideProgressBar();
         return(null);
     }
 }
Пример #13
0
        /// <summary>
        /// Takes an imported JSON object, and breaks it into relevant components and data.
        /// Then calls relevant functions for actual import of asset.
        /// </summary>
        /// <param name="objectList"></param>
        public string ImportMegascansAssets(JObject objectList)
        {
            var    startTime = System.DateTime.Now;
            string activeLOD = (string)objectList["activeLOD"];
            string minLOD    = (string)objectList["minLOD"];

            isAlembic           = false;
            plant               = false;
            highPoly            = false;
            hasBillboardLOD     = false;
            hasBillboardLODOnly = false;
            mapName             = "";

            //get texture components from the current object.
            JArray textureComps = (JArray)objectList["components"];

            //get mesh components from the current object.
            JArray meshComps = (JArray)objectList["meshList"];

            //Map name overrides.
            mapNames = (JObject)objectList["mapNameOverride"];
            //run a check to see if we're using Unity 5 or below, and then if we're trying to import a high poly mesh. if so, let the user know we are aborting the import.
            if (meshComps.Count > 0)
            {
                isAlembic = Path.GetExtension((string)meshComps[0]["path"]) == ".abc";
            }

            hasBillboardLOD = MegascansMeshUtils.ContainsLowestLOD((JArray)objectList["lodList"], minLOD);

            assetType = (int)objectList["meshVersion"];
            type      = (string)objectList["type"];
            if (type.ToLower().Contains("3dplant"))
            {
                plant = true;
                if (minLOD == activeLOD)
                {
                    hasBillboardLODOnly = true;
                }
            }

            try {
                LoadPreferences();
                MegascansUtilities.CalculateNumberOfOperations(objectList, dispType, texPack, shaderType, generateTerrainNormal, hasBillboardLODOnly);
                path = ConstructPath(objectList);

                if (path == null || path == "")
                {
                    Debug.Log("Asset: " + (string)objectList["name"] + " already exist in the Project. Please delete/rename the existing folder and re-import this asset.");
                    AssetDatabase.Refresh();
                    return(null);
                }

                GetShaderType();
            } catch (Exception ex) {
                Debug.Log("Error setting import path.");
                Debug.Log(ex.ToString());
                MegascansUtilities.HideProgressBar();
            }

            try {
                //process textures
                ProcessTextures(textureComps);
                if (finalMat == null && !(plant && hasBillboardLODOnly))
                {
                    Debug.Log("The import path is incorrect. Asset import aborted.");
                    return(null);
                }
                else
                {
                    if (type.ToLower().Contains("surface") && applyToSelection)
                    {
                        foreach (MeshRenderer render in MegascansUtilities.GetSelectedMeshRenderers())
                        {
                            render.material = finalMat;
                        }
                    }
                }
            } catch (Exception ex) {
                Debug.Log("Error importing textures.");
                Debug.Log(ex.ToString());
                MegascansUtilities.HideProgressBar();
            }

            //process meshes
            if (meshComps == null && !type.Contains("surface"))
            {
                Debug.LogError("No meshes found. Please double check your export settings.");
                Debug.Log("Import failed.");
                return(null);
            }

            if (meshComps.Count > 0)
            {
                if (activeLOD == "high")
                {
                    //detect if we're trying to import a high poly mesh...
                    string msg = "You are about to import a high poly mesh. \nThese meshes are usually millions of polygons and can cause instability to your project. \nWould you like to proceed?";
                    if (EditorUtility.DisplayDialog("WARNING!", msg, "Yes", "No"))
                    {
#if UNITY_EDITOR_WIN
                        hpMat = new Material(finalMat.shader);
                        hpMat.CopyPropertiesFromMaterial(finalMat);
                        hpMat.SetTexture("_NormalMap", null);
                        hpMat.SetTexture("_BumpMap", null);
                        hpMat.DisableKeyword("_NORMALMAP_TANGENT_SPACE");
                        hpMat.DisableKeyword("_NORMALMAP");
                        hpMat.name = MegascansUtilities.FixSpaces(new string[] { hpMat.name, "HighPoly" });
                        string hpMatDir = MegascansUtilities.FixSpaces(new string[] { matPath, "HighPoly.mat" });
                        AssetDatabase.CreateAsset(hpMat, hpMatDir);
#endif
                        highPoly = true;
                    }
                }
                try {
                    //process meshes and prefabs
                    PrefabData prefData = new PrefabData(path, finalName, lodFadeMode, highPoly, addAssetToScene, setupCollision, hasBillboardLOD, isAlembic, false, finalMat, hpMat, billboardMat, new List <string>(), new List <List <string> >());
                    MegascansMeshUtils.ProcessMeshes(objectList, path, highPoly, plant, prefData);
                } catch (Exception ex) {
                    Debug.Log("Error importing meshes.");
                    Debug.Log(ex.ToString());
                    MegascansUtilities.HideProgressBar();
                }
            }

            var endTime   = System.DateTime.Now;
            var totalTime = endTime - startTime;
            Debug.Log("Asset Import Time: " + totalTime);
            AssetDatabase.Refresh();
            MegascansUtilities.HideProgressBar();
            //Application.GarbageCollectUnusedAssets();
            return(path);
        }
Пример #14
0
        void ImportAllTextures(Material mat, JArray texturesList)
        {
            try {
                List <string> typesOfTexturesAvailable = new List <string>();
                for (int i = 0; i < texturesList.Count; i++)
                {
                    typesOfTexturesAvailable.Add((string)texturesList[i]["type"]);
                }

                string    destTexPath;
                Texture2D tex;

                for (int i = 0; i < texturesList.Count; i++)
                {
                    mapName = (string)texturesList[i]["type"];
                    MegascansUtilities.UpdateProgressBar(1.0f, "Processing Asset " + assetName, "Importing texture: " + mapName);

                    if ((string)texturesList[i]["type"] == "albedo" || ((string)texturesList[i]["type"] == "diffuse" && !typesOfTexturesAvailable.Contains("albedo")))
                    {
                        destTexPath = Path.Combine(texPath, (string)texturesList[i]["nameOverride"]);
                        MegascansTextureProcessor texPrcsr = new MegascansTextureProcessor((string)texturesList[i]["path"], destTexPath);
                        tex = texPrcsr.ImportTexture();

                        mat.SetTexture("_MainTex", tex);
                        mat.SetTexture("_BaseColorMap", tex);

                        if (shaderType == 1)
                        {
                            mat.SetTexture("_BaseMap", tex);
                            mat.SetColor("_BaseColor", Color.white);
                        }

                        if (MegascansUtilities.AlbedoHasOpacity((JObject)texturesList[i]["channelsData"]))
                        {
                            float alphaCutoff = 0.33f;
                            texPrcsr.AdjustAlphaCutoff();

                            if (shaderType > 0)
                            {
                                mat.SetFloat("_AlphaClip", 1);
                                mat.SetFloat("_Cutoff", 0.1f);
                                mat.SetFloat("_Mode", 1);
                                mat.SetFloat("_Cull", 0);
                                mat.EnableKeyword("_ALPHATEST_ON");
                            }
                            else
                            {
                                mat.SetInt("_AlphaCutoffEnable", 1);
                                mat.SetFloat("_AlphaCutoff", alphaCutoff);
                                mat.SetInt("_DoubleSidedEnable", 1);

                                mat.SetOverrideTag("RenderType", "TransparentCutout");
                                mat.SetInt("_ZTestGBuffer", (int)UnityEngine.Rendering.CompareFunction.Equal);
                                mat.SetInt("_CullMode", (int)UnityEngine.Rendering.CullMode.Off);
                                mat.SetInt("_CullModeForward", (int)UnityEngine.Rendering.CullMode.Back);
                                mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                                mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                                mat.SetInt("_ZWrite", 1);
                                mat.renderQueue = 2450;
                                mat.SetInt("_ZTestGBuffer", (int)UnityEngine.Rendering.CompareFunction.Equal);

                                mat.EnableKeyword("_ALPHATEST_ON");
                                mat.EnableKeyword("_DOUBLESIDED_ON");
                                mat.DisableKeyword("_BLENDMODE_ALPHA");
                                mat.DisableKeyword("_SURFACE_TYPE_TRANSPARENT");
                            }
                        }
                    }
                    else if ((string)texturesList[i]["type"] == "specular")
                    {
                        if (texPack > 0)
                        {
                            destTexPath = Path.Combine(texPath, (string)texturesList[i]["nameOverride"]);
                            MegascansTextureProcessor texPrcsr = new MegascansTextureProcessor((string)texturesList[i]["path"], destTexPath);
                            tex = texPrcsr.ImportTexture();

                            mat.SetTexture("_SpecGlossMap", tex);
                            mat.SetTexture("_SpecularColorMap", tex);
                            mat.SetColor("_SpecColor", new UnityEngine.Color(1.0f, 1.0f, 1.0f));
                            mat.SetColor("_SpecularColor", new UnityEngine.Color(1.0f, 1.0f, 1.0f));
                            mat.SetFloat("_WorkflowMode", 0);
                            mat.SetFloat("_MaterialID", 4);
                            mat.EnableKeyword("_METALLICSPECGLOSSMAP");
                            mat.EnableKeyword("_SPECGLOSSMAP");
                            mat.EnableKeyword("_SPECULAR_SETUP");
                            mat.EnableKeyword("_SPECULARCOLORMAP");
                            mat.EnableKeyword("_MATERIAL_FEATURE_SPECULAR_COLOR");
                        }
                    }
                    else if ((string)texturesList[i]["type"] == "masks")
                    {
                        if (texPack < 1 || shaderType < 1)
                        {
                            destTexPath = Path.Combine(texPath, (string)texturesList[i]["nameOverride"]);
                            MegascansTextureProcessor texPrcsr = new MegascansTextureProcessor((string)texturesList[i]["path"], destTexPath, false, false);
                            tex = texPrcsr.ImportTexture();

                            mat.SetTexture("_MaskMap", tex);
                            mat.SetTexture("_MetallicGlossMap", tex);
                            mat.EnableKeyword("_MASKMAP");
                            mat.SetFloat("_MaterialID", 1);
                            mat.EnableKeyword("_METALLICSPECGLOSSMAP");
                            mat.EnableKeyword("_METALLICGLOSSMAP");

                            bool hasMetalness;
                            bool hasAO;
                            bool hasGloss;

                            MegascansUtilities.MaskMapComponents((JObject)texturesList[i]["channelsData"], out hasMetalness, out hasAO, out hasGloss);

                            if (!hasMetalness)
                            {
                                mat.SetFloat("_Metallic", 1.0f);
                            }

                            if (hasAO)
                            {
                                mat.SetTexture("_OcclusionMap", tex);
                                mat.EnableKeyword("_OCCLUSIONMAP");
                            }
                        }
                    }
                    else if ((string)texturesList[i]["type"] == "normal")
                    {
                        string normalMapPath = (string)texturesList[i]["path"];
                        if (activeLOD == "high" && !normalMapPath.Contains("NormalBump"))
                        {
                            for (int x = 0; x < 10; x++)
                            {
                                string n = normalMapPath.Replace("_LOD" + x.ToString(), "Bump");
                                if (File.Exists(n))
                                {
                                    normalMapPath = n;
                                    break;
                                }
                            }
                            if (normalMapPath.Contains("NormalBump"))
                            {
                                continue;
                            }
                        }

                        destTexPath = Path.Combine(texPath, (string)texturesList[i]["nameOverride"]);
                        MegascansTextureProcessor texPrcsr = new MegascansTextureProcessor(normalMapPath, destTexPath, true, false);
                        tex = texPrcsr.ImportTexture();
                        mat.SetTexture("_BumpMap", tex);
                        mat.SetTexture("_NormalMap", tex);
                        mat.EnableKeyword("_NORMALMAP_TANGENT_SPACE");
                        mat.EnableKeyword("_NORMALMAP");
                    }
                    else if ((string)texturesList[i]["type"] == "ao" && texPack > 0)
                    {
                        destTexPath = Path.Combine(texPath, (string)texturesList[i]["nameOverride"]);
                        MegascansTextureProcessor texPrcsr = new MegascansTextureProcessor((string)texturesList[i]["path"], destTexPath, false, false);
                        tex = texPrcsr.ImportTexture();
                        mat.SetTexture("_OcclusionMap", tex);
                        mat.EnableKeyword("_OCCLUSIONMAP");
                    }
                    else if ((string)texturesList[i]["type"] == "displacement")
                    {
                        if (dispType > 0)
                        {
                            destTexPath = Path.Combine(texPath, (string)texturesList[i]["nameOverride"]);
                            MegascansTextureProcessor texPrcsr = new MegascansTextureProcessor((string)texturesList[i]["path"], destTexPath, false, false);
                            tex = texPrcsr.ImportTexture();
                            mat.SetTexture("_HeightMap", tex);
                            mat.SetTexture("_ParallaxMap", tex);
                            mat.EnableKeyword("_DISPLACEMENT_LOCK_TILING_SCALE");
                            if (shaderType == 0)
                            {
                                mat.EnableKeyword("_HEIGHTMAP");
                            }
                            if (dispType == 1)
                            {
                                mat.EnableKeyword("_VERTEX_DISPLACEMENT");
                                mat.EnableKeyword("_VERTEX_DISPLACEMENT_LOCK_OBJECT_SCALE");
                            }
                            else if (dispType == 2)
                            {
                                mat.EnableKeyword("_PARALLAXMAP");
                                mat.EnableKeyword("_PIXEL_DISPLACEMENT");
                                mat.EnableKeyword("_PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE");
                            }
                        }
                    }
                    else if ((string)texturesList[i]["type"] == "translucency")
                    {
                        destTexPath = Path.Combine(texPath, (string)texturesList[i]["nameOverride"]);
                        MegascansTextureProcessor texPrcsr = new MegascansTextureProcessor((string)texturesList[i]["path"], destTexPath);
                        tex = texPrcsr.ImportTexture();

                        mat.SetTexture("_SubsurfaceMaskMap", tex);
                        mat.EnableKeyword("_SUBSURFACE_MASK_MAP");
                        mat.SetInt("_DiffusionProfile", 1);
                        mat.SetFloat("_EnableSubsurfaceScattering", 1);
                        if (!typesOfTexturesAvailable.Contains("transmission"))
                        {
                            mat.SetTexture("_ThicknessMap", tex);
                            mat.EnableKeyword("_THICKNESSMAP");
                        }
                        if (plant)
                        {
                            mat.SetInt("_DiffusionProfile", 2);
                            mat.SetFloat("_CoatMask", 0.0f);
                            mat.SetInt("_EnableWind", 1);
                            mat.EnableKeyword("_VERTEX_WIND");
                        }
                        MegascansMaterialUtils.AddSSSSettings(mat, shaderType);
                    }
                    else if ((string)texturesList[i]["type"] == "transmission")
                    {
                        destTexPath = Path.Combine(texPath, (string)texturesList[i]["nameOverride"]);
                        MegascansTextureProcessor texPrcsr = new MegascansTextureProcessor((string)texturesList[i]["path"], destTexPath, false, false);
                        tex = texPrcsr.ImportTexture();

                        mat.SetTexture("_ThicknessMap", tex);
                        mat.EnableKeyword("_THICKNESSMAP");
                        mat.SetInt("_DiffusionProfile", 2);
                        MegascansMaterialUtils.AddSSSSettings(mat, shaderType);
                    }
                    else if (importAllTextures)
                    {
                        mapName = (string)texturesList[i]["type"];
                        string mapPath        = (string)texturesList[i]["path"];
                        string otherTexFolder = MegascansUtilities.ValidateFolderCreate(texPath, "Others");
                        destTexPath = Path.Combine(otherTexFolder, (string)texturesList[i]["nameOverride"]);
                        MegascansTextureProcessor texPrcsr = new MegascansTextureProcessor(mapPath, destTexPath);
                        tex = texPrcsr.ImportTexture();
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansImporter::ImportAllTextures:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
            }
        }
Пример #15
0
        /// <summary>
        /// Creates prefabs for the 3D Scatter assets.
        /// </summary>
        /// <param name="hasBillboard"></param>
        /// <returns></returns>
        public static void CreatePrefabsScatter(PrefabData prefabData)
        {
            try
            {
                string            prefabPath         = MegascansUtilities.ValidateFolderCreate(prefabData.assetPath, "Prefabs");
                int               numberOfVariations = MegascansUtilities.GetMeshChildrenCount(prefabData.importedGeometryPaths3D);
                List <GameObject> prefabObjects      = new List <GameObject>();

                for (int i = 0; i < numberOfVariations; i++)
                {
                    string prefabName = prefabData.finalAssetName.Replace("$mapName", "").Replace("$resolution", "").Replace("$lod", "").Replace("$variation", "");
                    string varName    = "Var" + (i + 1).ToString();
                    prefabName = prefabName.Contains("$variation") ? prefabName.Replace("$variation", "Var" + varName) : prefabName + varName;

                    //Setting up prefab gameobject
                    GameObject prefabGameObject = new GameObject();
                    prefabGameObject.name     = prefabName;
                    prefabGameObject.isStatic = true;
                    if (prefabData.setupLODs)
                    {
                        prefabGameObject.AddComponent <LODGroup>();
                        prefabGameObject.GetComponent <LODGroup>().fadeMode           = (LODFadeMode)prefabData.lodFadeMode; //Casting lod fade mode to enum.
                        prefabGameObject.GetComponent <LODGroup>().animateCrossFading = true;
                    }

                    List <LOD> lodsForPrefab = new List <LOD>();
                    int        numberOfFiles = prefabData.importedGeometryPaths3D.Count;

                    List <float> lodHeights = MegascansUtilities.getLODHeightList(numberOfFiles);
                    //Instantiate all the meshes in the scene, add them to the material/collider to them.
                    for (int x = 0; (x < numberOfFiles && x < 8); x++)
                    {
                        UnityEngine.Object loadedGeometry = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(prefabData.importedGeometryPaths3D[x]);
                        //Highpoly mesh check.
                        if (loadedGeometry.name.ToLower().Contains("highpoly") && !prefabData.highpoly)
                        {
                            continue;
                        }
                        GameObject geometryObject = Instantiate(loadedGeometry) as GameObject;
                        Renderer[] r;
                        if (prefabData.isAlembic) //if the instantiated mesh is an alembic asset.
                        {
                            //Get all variations in a LOD
                            List <Transform> varsInLOD = new List <Transform>();
                            foreach (Transform var in geometryObject.transform)
                            {
                                varsInLOD.Add(var);
                            }
                            //Delete all the other variations in the LOD object
                            for (int y = 0; y < varsInLOD.Count; y++)
                            {
                                //If variation does not match one currently being processed.
                                if (y != i)
                                {
                                    DestroyImmediate(varsInLOD[y].gameObject);
                                }
                            }
                            //Parent the child gameobject (geometry) to the prefab game object.
                            geometryObject.transform.parent        = prefabGameObject.transform;
                            geometryObject.transform.localPosition = Vector3.zero;
                            geometryObject.name = geometryObject.name.Replace("(Clone)", "");
                            r = geometryObject.GetComponentsInChildren <Renderer>();
                        }
                        else//if the instantiated mesh is a scatter type asset.
                        {
                            //Get all variations in a LOD
                            List <Transform> varsInLOD = new List <Transform>();
                            foreach (Transform var in geometryObject.transform)
                            {
                                varsInLOD.Add(var);
                            }
                            //Delete all the other variations in the LOD object
                            for (int y = 0; y < varsInLOD.Count; y++)
                            {
                                //If variation does not match one currently being processed.
                                if (y != i)
                                {
                                    DestroyImmediate(varsInLOD[y].gameObject);
                                }
                            }
                            //Parent the child gameobject (geometry) to the prefab game object.
                            geometryObject.transform.parent        = prefabGameObject.transform;
                            geometryObject.transform.localPosition = Vector3.zero;
                            geometryObject.name = geometryObject.name.Replace("(Clone)", "");
                            r = geometryObject.GetComponentsInChildren <Renderer>();
                        }

                        foreach (Renderer ren in r)
                        {
                            ren.material = prefabData.finalMat;
                            //Apply highpoly material if the mesh was highpoly and highpoly filter is enabled.
                            if (loadedGeometry.name.ToLower().Contains("highpoly") && prefabData.highpoly)
                            {
                                ren.material = prefabData.highpolyMat;
#if UNITY_EDITOR_OSX
                                ren.material = prefabData.finalMat;
#endif
                            }
                            //Apply collision
                            if (prefabData.setupCollision)
                            {
                                ren.gameObject.AddComponent <MeshCollider>().sharedMesh = ren.gameObject.GetComponent <MeshFilter>().sharedMesh;
                            }
                        }

                        if (prefabData.setupLODs)
                        {
                            lodsForPrefab.Add(new LOD(lodHeights[0], r));
                            lodHeights.RemoveAt(0);
                        }
                        else
                        {
                            break;
                        }
                    }
                    //Set LODs in the LOD group
                    if (prefabData.setupLODs)
                    {
                        prefabGameObject.GetComponent <LODGroup>().SetLODs(lodsForPrefab.ToArray());
                        prefabGameObject.GetComponent <LODGroup>().RecalculateBounds();
                    }
                    //Prefab saving
                    string prefLocation = prefabPath + "/" + prefabName + ".prefab";
                    prefLocation = prefLocation.Replace("(Clone)", "");
                    GameObject prefabObject = SavePrefab(prefabGameObject, prefLocation, prefabData.addAssetToScene);
                    if (prefabObject)
                    {
                        prefabObjects.Add(prefabObject);
                    }
                }

                //Setting up variation holder gameobject
                GameObject scatterParent = new GameObject(prefabData.assetName);
                scatterParent.isStatic = true;
                foreach (GameObject variation in prefabObjects)
                {
                    variation.transform.parent = scatterParent.transform;
                }
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansMeshUtils::3D Asset Prefab:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
            }
        }
Пример #16
0
        /// <summary>
        /// Creates prefabs from the newer assets on bridge, has an option for billboard materials on plants.
        /// </summary>
        /// <param name="hasBillboard"></param>
        /// <returns></returns>
        public static void CreatePrefab3DPlant(PrefabData prefabData)
        {
            try
            {
                string            prefabPath     = MegascansUtilities.ValidateFolderCreate(prefabData.assetPath, "Prefabs");
                string            tempPrefabName = prefabData.finalAssetName.Replace("$mapName", "").Replace("$resolution", "").Replace("$lod", "");
                List <GameObject> prefabObjects  = new List <GameObject>();

                for (int i = 0; i < prefabData.importedGeometryPaths3DPlant.Count; i++)
                {
                    string variation  = "Var" + (i + 1).ToString();
                    string prefabName = tempPrefabName.Contains("$variation") ? tempPrefabName.Replace("$variation", variation) : tempPrefabName + "_" + variation; //Prefab saving
                                                                                                                                                                    //Setting up prefab gameobject
                    GameObject prefabGameObject = new GameObject();
                    prefabGameObject.name     = prefabName;
                    prefabGameObject.isStatic = true;

                    if (prefabData.setupLODs)
                    {
                        prefabGameObject.AddComponent <LODGroup>();
                        prefabGameObject.GetComponent <LODGroup>().fadeMode           = (LODFadeMode)prefabData.lodFadeMode; //Casting lod fade mode to enum.
                        prefabGameObject.GetComponent <LODGroup>().animateCrossFading = true;
                    }

                    List <LOD> lodsForPrefab = new List <LOD>();
                    int        numberOfFiles = prefabData.importedGeometryPaths3DPlant[i].Count;

                    List <float> lodHeights = MegascansUtilities.getLODHeightList(numberOfFiles);
                    //Instantiate all the meshes in the scene, add them to the material/collider to them.
                    for (int x = 0; (x < numberOfFiles && x < 8); x++)
                    {
                        UnityEngine.Object loadedGeometry = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(prefabData.importedGeometryPaths3DPlant[i][x]);
                        //Highpoly mesh check.
                        if (loadedGeometry.name.ToLower().Contains("highpoly") && !prefabData.highpoly)
                        {
                            continue;
                        }
                        GameObject geometryObject = Instantiate(loadedGeometry) as GameObject;
                        Renderer[] r;
                        //Parent all the objects to the prefab game object.
                        if (geometryObject.transform.childCount > 0 && !prefabData.isAlembic)
                        {
                            r = new Renderer[geometryObject.transform.childCount];
                            for (int j = 0; j < geometryObject.transform.childCount; ++j)
                            {
                                //Parent the child gameobject (geometry) to the prefab game object.
                                GameObject geometryChildObject = geometryObject.transform.GetChild(j).gameObject; //Cache a reference to the child gameobject of the geometry.
                                geometryChildObject.transform.parent        = prefabGameObject.transform;
                                geometryChildObject.transform.localPosition = Vector3.zero;
                                geometryChildObject.name = geometryChildObject.name.Replace("(Clone)", "");
                                r[j] = geometryChildObject.GetComponent <Renderer>();
                            }
                            //Destroy the empty parent container which was holding the meshes.
                            DestroyImmediate(geometryObject);
                        }
                        else if (prefabData.isAlembic) //if the instantiated mesh is an alembic asset.
                        {
                            //Parent the child gameobject (geometry) to the prefab game object.
                            geometryObject.transform.parent        = prefabGameObject.transform;
                            geometryObject.transform.localPosition = Vector3.zero;
                            geometryObject.name = geometryObject.name.Replace("(Clone)", "");
                            r = geometryObject.GetComponentsInChildren <Renderer>();
                        }
                        else //if the instantiated mesh does not have any children
                        {
                            r = new Renderer[1];
                            //Parent the child gameobject (geometry) to the prefab game object.
                            geometryObject.transform.parent        = prefabGameObject.transform;
                            geometryObject.transform.localPosition = Vector3.zero;
                            geometryObject.name = geometryObject.name.Replace("(Clone)", "");
                            r[0] = geometryObject.GetComponent <Renderer>();
                        }

                        foreach (Renderer ren in r)
                        {
                            ren.material = prefabData.finalMat;
                            //Apply highpoly material if the mesh was highpoly and highpoly filter is enabled.
                            if (loadedGeometry.name.ToLower().Contains("highpoly") && prefabData.highpoly)
                            {
                                ren.material = prefabData.highpolyMat;
#if UNITY_EDITOR_OSX
                                ren.material = prefabData.finalMat;
#endif
                            }
                            //Billboard material application
                            if (prefabData.hasBillboardLOD && x == (numberOfFiles - 1))
                            {
                                ren.material = prefabData.billboardMat;
                            }

                            //Apply collision
                            if (prefabData.setupCollision)
                            {
                                ren.gameObject.AddComponent <MeshCollider>().sharedMesh = ren.gameObject.GetComponent <MeshFilter>().sharedMesh;
                            }
                        }

                        if (prefabData.setupLODs)
                        {
                            lodsForPrefab.Add(new LOD(lodHeights[0], r));
                            lodHeights.RemoveAt(0);
                        }
                        else
                        {
                            break;
                        }
                    }
                    //Set LODs in the LOD group
                    if (prefabData.setupLODs)
                    {
                        prefabGameObject.GetComponent <LODGroup>().SetLODs(lodsForPrefab.ToArray());
                        prefabGameObject.GetComponent <LODGroup>().RecalculateBounds();
                    }
                    //Prefab saving
                    string prefLocation = prefabPath + "/" + prefabName + ".prefab";
                    prefLocation = prefLocation.Replace("(Clone)", "");
                    GameObject prefabObject = SavePrefab(prefabGameObject, prefLocation, prefabData.addAssetToScene);
                    if (prefabObject)
                    {
                        prefabObjects.Add(prefabObject);
                    }
                }

                //Setting up variation holder gameobject
                GameObject plantsParent = new GameObject(prefabData.assetName);
                plantsParent.isStatic = true;
                foreach (GameObject variation in prefabObjects)
                {
                    variation.transform.parent = plantsParent.transform;
                }
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansMeshUtils::3D Plant Prefab:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
            }
        }
Пример #17
0
        /// <summary>
        /// Import meshes, start from highest LOD and import the chain.
        /// </summary>
        public static void ProcessMeshes(JObject assetJson, string assetFolderPath, bool highpoly, bool hasVariations, PrefabData prefabData)
        {
            try
            {
                bool createPrefabs = EditorPrefs.GetBool("QuixelDefaultSetupPrefabs", true);
                bool importLODs    = EditorPrefs.GetBool("QuixelDefaultImportLODs", true);
                bool setupLODs     = EditorPrefs.GetBool("QuixelDefaultSetupLOD", true);
                prefabData.setupLODs = (importLODs && setupLODs); //Only do LOD setup if lower lods were imported and LOD grouping is enabled.

                //get mesh components from the current object. Also, meshComps.Count can give us the number of variations ;)
                JArray meshComps = (JArray)assetJson["meshList"];

                JArray lodList   = (JArray)assetJson["lodList"];
                string activeLOD = (string)assetJson["activeLOD"];
                string minLOD    = (string)assetJson["minLOD"];

                string modelsFolderPath = MegascansUtilities.ValidateFolderCreate(assetFolderPath, "Models");

                if (hasVariations)
                {
                    List <List <string> > importedGeometryPaths3DPlant = new List <List <string> >();

                    for (int i = 1; i <= meshComps.Count; i++)
                    {
                        List <string> importedGeometryPaths = new List <string>();
                        bool          lodMatched            = false; // This flag helps to import the lower lods once the active lod is found.
                        foreach (JObject mesh in lodList)
                        {
                            if ((int)mesh["variation"] == i)
                            {
                                string currentLOD = (string)mesh["lod"];
                                if (lodMatched || currentLOD == activeLOD || highpoly)
                                {
                                    lodMatched = true;
                                    if ((currentLOD == "high") && !highpoly)
                                    {
                                        continue;
                                    }
                                    //get the path of the highest LOD to be imported.
                                    string sourcePath = (string)mesh["path"];
                                    string destPath   = Path.Combine(modelsFolderPath, (string)mesh["nameOverride"]);
                                    ImportMesh(sourcePath, destPath);
                                    importedGeometryPaths.Add(destPath);
                                    if (!importLODs)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        importedGeometryPaths3DPlant.Add(importedGeometryPaths);
                    }
                    prefabData.importedGeometryPaths3DPlant = importedGeometryPaths3DPlant;
                    if (createPrefabs)
                    {
                        CreatePrefab3DPlant(prefabData);
                    }
                }
                else
                {
                    List <string> importedGeometryPaths3D = new List <string>();
                    bool          lodMatched = false; // This flag helps to import the lower lods once the active lod is found.
                    foreach (JObject mesh in lodList)
                    {
                        string currentLOD = (string)mesh["lod"];
                        if (lodMatched || (currentLOD == activeLOD) || highpoly)
                        {
                            lodMatched = true;
                            if ((currentLOD == "high") && !highpoly)
                            {
                                continue;
                            }
                            //get the path of the highest LOD to be imported.
                            string sourcePath = (string)mesh["path"];
                            string destPath   = Path.Combine(modelsFolderPath, (string)mesh["nameOverride"]);
                            ImportMesh(sourcePath, destPath);
                            importedGeometryPaths3D.Add(destPath);
                            if (!importLODs)
                            {
                                break;
                            }
                        }
                    }
                    prefabData.importedGeometryPaths3D = importedGeometryPaths3D;
                    if (createPrefabs)
                    {
                        if (MegascansUtilities.isScatterAsset(assetJson, importedGeometryPaths3D))
                        {
                            CreatePrefabsScatter(prefabData);
                        }
                        else
                        {
                            CreatePrefab3D(prefabData);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansMeshUtils::Processing Meshes:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
            }
        }
Пример #18
0
        /// <summary>
        /// Generates prefabs from imported meshes.
        /// Used for normal 3D assets
        /// </summary>
        public static void CreatePrefab3D(PrefabData prefabData)
        {
            try {
                string prefabPath = MegascansUtilities.ValidateFolderCreate(prefabData.assetPath, "Prefabs");
                string prefabName = prefabData.modelNamingConvention;

                //Setting up prefab gameobject
                GameObject prefabGameObject = new GameObject();
                prefabGameObject.name     = prefabName;
                prefabGameObject.isStatic = true;
                if (prefabData.setupLODs)
                {
                    prefabGameObject.AddComponent <LODGroup>();
                    prefabGameObject.GetComponent <LODGroup>().fadeMode           = (LODFadeMode)prefabData.lodFadeMode; //Casting lod fade mode to enum.
                    prefabGameObject.GetComponent <LODGroup>().animateCrossFading = true;
                }

                List <LOD> lodsForPrefab = new List <LOD>();
                int        numberOfFiles = prefabData.importedGeometryPaths3D.Count;

                List <float> lodHeights = MegascansUtilities.getLODHeightList(numberOfFiles);
                //Instantiate all the meshes in the scene, add them to the material/collider to them.
                for (int x = 0; (x < numberOfFiles && x < 8); x++)
                {
                    UnityEngine.Object loadedGeometry = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(prefabData.importedGeometryPaths3D[x]);
                    //Highpoly mesh check.
                    if (loadedGeometry.name.ToLower().Contains("highpoly") && !prefabData.highpoly)
                    {
                        continue;
                    }
                    GameObject geometryObject = Instantiate(loadedGeometry) as GameObject;
                    Renderer[] r;
                    //Parent all the objects to the prefab game object.
                    if (geometryObject.transform.childCount > 0 && !prefabData.isAlembic)
                    {
                        r = new Renderer[geometryObject.transform.childCount];
                        for (int j = 0; j < geometryObject.transform.childCount; ++j)
                        {
                            //Parent the child gameobject (geometry) to the prefab game object.
                            GameObject geometryChildObject = geometryObject.transform.GetChild(j).gameObject; //Cache a reference to the child gameobject of the geometry.
                            geometryChildObject.transform.parent        = prefabGameObject.transform;
                            geometryChildObject.transform.localPosition = Vector3.zero;
                            geometryChildObject.name = geometryChildObject.name.Replace("(Clone)", "");
                            r[j] = geometryChildObject.GetComponentInChildren <Renderer>();
                        }
                        //Destroy the empty parent container which was holding the meshes.
                        DestroyImmediate(geometryObject);
                    }
                    else if (prefabData.isAlembic) //if the instantiated mesh is an alembic asset.
                    {
                        //Parent the child gameobject (geometry) to the prefab game object.
                        geometryObject.transform.parent        = prefabGameObject.transform;
                        geometryObject.transform.localPosition = Vector3.zero;
                        geometryObject.name = geometryObject.name.Replace("(Clone)", "");
                        r = geometryObject.GetComponentsInChildren <Renderer>();
                    }
                    else //if the instantiated mesh does not have any children
                    {
                        //Parent the child gameobject (geometry) to the prefab game object.
                        geometryObject.transform.parent        = prefabGameObject.transform;
                        geometryObject.transform.localPosition = Vector3.zero;
                        geometryObject.name = geometryObject.name.Replace("(Clone)", "");
                        r = geometryObject.GetComponentsInChildren <Renderer>();
                    }

                    foreach (Renderer ren in r)
                    {
                        ren.material = prefabData.finalMat;
                        //Apply collision
                        if (prefabData.setupCollision)
                        {
                            ren.gameObject.AddComponent <MeshCollider>().sharedMesh = ren.gameObject.GetComponent <MeshFilter>().sharedMesh;
                        }
                    }

                    if (prefabData.setupLODs)
                    {
                        lodsForPrefab.Add(new LOD(lodHeights[0], r));
                        lodHeights.RemoveAt(0);
                    }
                    else   //We only set the prefab with 1 LOD if setup LODs is unchecked.
                    {
                        break;
                    }
                }
                //Set LODs in the LOD group
                if (prefabData.setupLODs)
                {
                    prefabGameObject.GetComponent <LODGroup>().SetLODs(lodsForPrefab.ToArray());
                    prefabGameObject.GetComponent <LODGroup>().RecalculateBounds();
                }
                //Prefab saving
                string prefLocation = prefabPath + "/" + prefabName + ".prefab";
                prefLocation = prefLocation.Replace("(Clone)", "");
                SavePrefab(prefabGameObject, prefLocation, prefabData.addAssetToScene);
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansMeshUtils::3D Asset Prefab:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
            }
        }
Пример #19
0
        /// <summary>
        /// Creates materials needed for the asset.
        /// </summary>
        /// <returns></returns>
        Material CreateMaterial()
        {
            MegascansUtilities.UpdateProgressBar(1.0f, "Processing Asset " + assetName, "Creating material...");
            if ((shaderType == 0 || shaderType == 1) && isAlembic)
            {
                Debug.Log("Alembic files are not supported in LWRP/HDRP. Please change your export file format in Bridge or change your SRP in Unity.");
                return(null);
            }

            try {
                string   rp  = matPath + ".mat";
                Material mat = (Material)AssetDatabase.LoadAssetAtPath(rp, typeof(Material));
                if (!mat)
                {
                    mat = new Material(Shader.Find("Standard"));
                    AssetDatabase.CreateAsset(mat, rp);
                    AssetDatabase.Refresh();
                    if (shaderType < 1)
                    {
                        mat.shader = Shader.Find("HDRenderPipeline/Lit");
#if UNITY_2018_3 || UNITY_2019
                        mat.shader = Shader.Find("HDRP/Lit");
#endif
                        mat.SetInt("_DisplacementMode", dispType);
                    }
                    if (shaderType > 0)
                    {
                        if (MegascansUtilities.isLegacy())
                        {
                            mat.shader = Shader.Find("LightweightPipeline/Standard (Physically Based)");
                        }
                        else
                        {
                            mat.shader = Shader.Find("Lightweight Render Pipeline/Lit");
                        }
                    }
                    if (shaderType > 1)
                    {
                        if (isAlembic)
                        {
                            mat.shader = Shader.Find("Alembic/Standard");
                            if (texPack > 0)
                            {
                                mat.shader = Shader.Find("Alembic/Standard (Specular setup)");
                            }
                        }
                        else
                        {
                            mat.shader = Shader.Find("Standard");
                            if (texPack > 0)
                            {
                                mat.shader = Shader.Find("Standard (Specular setup)");
                            }
                        }
                    }
                }
                return(mat);
            } catch (Exception ex) {
                Debug.Log("Exception: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
                return(null);
            }
        }
Пример #20
0
        /// <summary>
        /// Previous version of the importer would loop through a list of texture paths, and use a bunch of if-statements and do things accordingly.
        /// This version just takes in every texture path and if it's not null, does the thing. Less looping, better overall performance.
        /// </summary>
        /// <param name="albedo"></param>
        /// <param name="opacity"></param>
        /// <param name="normals"></param>
        /// <param name="metallic"></param>
        /// <param name="specular"></param>
        /// <param name="AO"></param>
        /// <param name="gloss"></param>
        /// <param name="displacement"></param>
        /// <param name="roughness"></param>
        /// <param name="translucency"></param>
        Material ReadWriteAllTextures(string albedo, string opacity, string normals, string metallic, string specular, string AO, string gloss, string displacement, string roughness, string translucency)
        {
            try {
                Material mat = CreateMaterial();

                if (mat == null)
                {
                    return(null);
                }

                //create a new work thread for each texture to be processed.
                //Pack the opacity into the alpha channel of albedo if it exists.
                string texMapName = (string)mapNames["Albedo"];
                tempTexName = texPath.Contains("$mapName")? texPath.Replace("$mapName", texMapName): texPath + texMapName;
                string p = tempTexName + ".png";
                mapName = opacity != null ? "Albedo + Alpha" : "Albedo";
                MegascansUtilities.UpdateProgressBar(1.0f, "Processing Asset " + assetName, "Importing texture: " + mapName);
                Texture2D tex = MegascansImageUtils.PackTextures(albedo, opacity, p);

                mat.SetTexture("_MainTex", tex);
                mat.SetTexture("_BaseColorMap", tex);

                if (shaderType == 1)
                {
                    mat.SetTexture("_BaseMap", tex);
                    mat.SetColor("_BaseColor", Color.white);
                }

                if (opacity != null)
                {
                    if (shaderType > 0)
                    {
                        mat.SetFloat("_AlphaClip", 1);
                        mat.SetFloat("_Mode", 1);
                        mat.SetFloat("_Cull", 1);
                        mat.EnableKeyword("_ALPHATEST_ON");
                    }
                    else
                    {
                        mat.SetInt("_AlphaCutoffEnable", 1);
                        mat.SetFloat("_AlphaCutoff", 0.333f);
                        mat.SetInt("_DoubleSidedEnable", 1);

                        mat.SetOverrideTag("RenderType", "TransparentCutout");
                        mat.SetInt("_ZTestGBuffer", (int)UnityEngine.Rendering.CompareFunction.Equal);
                        mat.SetInt("_CullMode", (int)UnityEngine.Rendering.CullMode.Off);
                        mat.SetInt("_CullModeForward", (int)UnityEngine.Rendering.CullMode.Back);
                        mat.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                        mat.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                        mat.SetInt("_ZWrite", 1);
                        mat.renderQueue = 2450;
                        mat.SetInt("_ZTestGBuffer", (int)UnityEngine.Rendering.CompareFunction.Equal);

                        mat.EnableKeyword("_ALPHATEST_ON");
                        mat.EnableKeyword("_DOUBLESIDED_ON");
                        mat.DisableKeyword("_BLENDMODE_ALPHA");
                        mat.DisableKeyword("_SURFACE_TYPE_TRANSPARENT");
                    }
                }

                //test to see if gloss is absent but roughness is present...
                bool useRoughness = (gloss == null && roughness != null);
                if (texPack < 1 || shaderType < 1)
                {
                    mapName = "Masks";
                    MegascansUtilities.UpdateProgressBar(1.0f, "Processing Asset " + assetName, "Importing texture: " + mapName);
                    tempTexName = texPath.Contains("$mapName") ? texPath.Replace("$mapName", "Masks"): texPath + "Masks";
                    p           = tempTexName + ".png";
                    mat.SetFloat("_Metallic", 1.0f);
                    tex = MegascansImageUtils.PackTextures(metallic, AO, displacement, useRoughness ? roughness : gloss, p, useRoughness);
                    mat.SetTexture("_MaskMap", tex);
                    mat.EnableKeyword("_MASKMAP");
                    mat.SetFloat("_MaterialID", 1);
                    mat.SetTexture("_MetallicGlossMap", tex);
                    mat.EnableKeyword("_METALLICSPECGLOSSMAP");
                    mat.EnableKeyword("_METALLICGLOSSMAP");
                }

                //do we need to process a specular map?
                if (texPack > 0 && specular != null)
                {
                    texMapName = (string)mapNames["Specular"];
                    mapName    = "Specular + Gloss";
                    MegascansUtilities.UpdateProgressBar(1.0f, "Processing Asset " + assetName, "Importing texture: " + mapName);
                    tempTexName = texPath.Contains("$mapName") ? texPath.Replace("$mapName", texMapName): texPath + texMapName;
                    p           = tempTexName + ".png";
                    tex         = MegascansImageUtils.PackTextures(specular, useRoughness ? roughness : gloss, p, useRoughness);
                    mat.SetTexture("_SpecGlossMap", tex);
                    mat.SetColor("_SpecColor", new UnityEngine.Color(1.0f, 1.0f, 1.0f));
                    mat.SetColor("_SpecularColor", new UnityEngine.Color(1.0f, 1.0f, 1.0f));
                    mat.SetFloat("_WorkflowMode", 0);
                    mat.SetFloat("_MaterialID", 4);
                    mat.SetTexture("_SpecularColorMap", tex);
                    mat.EnableKeyword("_METALLICSPECGLOSSMAP");
                    mat.EnableKeyword("_SPECGLOSSMAP");
                    mat.EnableKeyword("_SPECULAR_SETUP");
                    mat.EnableKeyword("_SPECULARCOLORMAP");
                    mat.EnableKeyword("_MATERIAL_FEATURE_SPECULAR_COLOR");
                }

                //handle any textures which can just be converted in place.
                if (normals != null)
                {
                    texMapName = (string)mapNames["Normal"];
                    mapName    = "Normals";
                    MegascansUtilities.UpdateProgressBar(1.0f, "Processing Asset " + assetName, "Importing texture: " + mapName);
                    tempTexName = texPath.Contains("$mapName") ? texPath.Replace("$mapName", texMapName): texPath + texMapName;
                    p           = tempTexName + ".png";
                    MegascansImageUtils.CreateTexture(normals, p);
                    tex = MegascansImageUtils.TextureImportSetup(p, true, false);
                    mat.SetTexture("_BumpMap", tex);
                    mat.SetTexture("_NormalMap", tex);
                    mat.EnableKeyword("_NORMALMAP_TANGENT_SPACE");
                    mat.EnableKeyword("_NORMALMAP");

                    mapName     = "Normals_Terrain";
                    tempTexName = texPath.Contains("$mapName") ? texPath.Replace("$mapName", texMapName + "_Terrain"): texPath + texMapName + "_Terrain";
                    p           = tempTexName + ".png";

                    if (generateTerrainNormal && type.ToLower().Contains("surface"))
                    {
                        MegascansImageUtils.ImportTerrainNormal(normals, p);
                    }
                }

                if (displacement != null && dispType > 0)
                {
                    texMapName = (string)mapNames["Displacement"];
                    mapName    = "Displacement";
                    MegascansUtilities.UpdateProgressBar(1.0f, "Processing Asset " + assetName, "Importing texture: " + mapName);
                    tempTexName = texPath.Contains("$mapName") ? texPath.Replace("$mapName", texMapName): texPath + texMapName;
                    p           = tempTexName + ".png";
                    MegascansImageUtils.CreateTexture(displacement, p);
                    tex = MegascansImageUtils.TextureImportSetup(p, false, false);
                    mat.SetTexture("_HeightMap", tex);
                    mat.SetTexture("_ParallaxMap", tex);
                    mat.EnableKeyword("_DISPLACEMENT_LOCK_TILING_SCALE");
                    if (dispType == 1)
                    {
                        mat.EnableKeyword("_VERTEX_DISPLACEMENT");
                        mat.EnableKeyword("_VERTEX_DISPLACEMENT_LOCK_OBJECT_SCALE");
                    }
                    if (dispType == 2)
                    {
                        mat.EnableKeyword("_PIXEL_DISPLACEMENT");
                        mat.EnableKeyword("_PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE");
                    }
                }

                //occlusion may or may not need to be packed, depending on the shader used.
                if (shaderType > 1 && AO != null)
                {
                    texMapName = (string)mapNames["AO"];
                    mapName    = "AO";
                    MegascansUtilities.UpdateProgressBar(1.0f, "Processing Asset " + assetName, "Importing texture: " + mapName);
                    tempTexName = texPath.Contains("$mapName") ? texPath.Replace("$mapName", texMapName): texPath + texMapName;
                    p           = tempTexName + ".png";
                    MegascansImageUtils.CreateTexture(AO, p);
                    tex = MegascansImageUtils.TextureImportSetup(p, false, false);
                    mat.SetTexture("_OcclusionMap", tex);
                    mat.EnableKeyword("_OCCLUSIONMAP");
                }

                if (translucency != null)
                {
                    texMapName = (string)mapNames["Translucency"];
                    mapName    = "Translucency";
                    MegascansUtilities.UpdateProgressBar(1.0f, "Processing Asset " + assetName, "Importing texture: " + mapName);
                    tempTexName = texPath.Contains("$mapName") ? texPath.Replace("$mapName", texMapName): texPath + texMapName;
                    p           = tempTexName + ".png";
                    tex         = MegascansImageUtils.PackTextures(translucency, translucency, translucency, null, p);
                    mat.SetInt("_MaterialID", 0);
                    mat.SetInt("_DiffusionProfile", 1);
                    mat.SetFloat("_EnableSubsurfaceScattering", 1);
                    mat.SetTexture("_SubsurfaceMaskMap", tex);
                    mat.SetTexture("_ThicknessMap", tex);
                    if (plant)
                    {
                        mat.SetInt("_DiffusionProfile", 2);
                        mat.SetFloat("_CoatMask", 0.0f);
                        mat.SetInt("_EnableWind", 1);
                        mat.EnableKeyword("_VERTEX_WIND");
                    }
                    mat.EnableKeyword("_SUBSURFACE_MASK_MAP");
                    mat.EnableKeyword("_THICKNESSMAP");
                    mat.EnableKeyword("_MATERIAL_FEATURE_TRANSMISSION");
                }
                return(mat);
            } catch (Exception ex) {
                Debug.Log("Exception: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
                return(null);
            }
        }
Пример #21
0
        /// <summary>
        /// Takes an imported JSON object, and breaks it into relevant components and data.
        /// Then calls relevant functions for actual import of asset.
        /// </summary>
        /// <param name="objectList"></param>
        public string ImportMegascansAssets(JObject objectList)
        {
            var startTime = System.DateTime.Now;

            activeLOD = (string)objectList["activeLOD"];
            string minLOD = (string)objectList["minLOD"];

            assetName = (string)objectList["name"];
            type      = (string)objectList["type"];

            isAlembic              = false;
            plant                  = false;
            highPoly               = false;
            hasBillboardLOD        = false;
            hasBillboardLODOnly    = false;
            mapName                = "";
            folderNamingConvention = (string)objectList["folderNamingConvention"];

            //get mesh components from the current object.
            JArray meshComps = (JArray)objectList["meshList"];

            //run a check to see if we're using Unity 5 or below, and then if we're trying to import a high poly mesh. if so, let the user know we are aborting the import.
            if (meshComps.Count > 0)
            {
                isAlembic = Path.GetExtension((string)meshComps[0]["path"]) == ".abc";
            }

            hasBillboardLOD = MegascansMeshUtils.ContainsLowestLOD((JArray)objectList["lodList"], minLOD, activeLOD);

            if (type.ToLower().Contains("3dplant"))
            {
                plant = true;
                if (minLOD == activeLOD)
                {
                    hasBillboardLODOnly = true;
                }
            }

            try {
                LoadPreferences();
                shaderType = MegascansUtilities.GetShaderType();
                MegascansUtilities.CalculateNumberOfOperations(objectList, dispType, texPack, shaderType, hasBillboardLODOnly);
                path = ConstructPath(objectList);

                if (path == null || path == "")
                {
                    Debug.Log("Asset: " + (string)objectList["name"] + " already exist in the Project. Please delete/rename the existing folder and re-import this asset.");
                    AssetDatabase.Refresh();
                    return(null);
                }
            } catch (Exception ex) {
                Debug.Log("Error setting import path.");
                Debug.Log(ex.ToString());
                MegascansUtilities.HideProgressBar();
            }

            try {
                //process textures
                ProcessTextures(objectList);
                if (finalMat == null && !(plant && hasBillboardLODOnly))
                {
                    Debug.Log("Could not import the textures and create the material.");
                    return(null);
                }
                else
                {
                    if (type.ToLower().Contains("surface") && applyToSelection)
                    {
                        foreach (MeshRenderer render in MegascansUtilities.GetSelectedMeshRenderers())
                        {
                            render.material = finalMat;
                        }
                    }
                }
            } catch (Exception ex) {
                Debug.Log("Error importing textures.");
                Debug.Log(ex.ToString());
                MegascansUtilities.HideProgressBar();
            }

            //process meshes
            if (meshComps == null && !type.Contains("surface"))
            {
                Debug.LogError("No meshes found. Please double check your export settings.");
                Debug.Log("Import failed.");
                return(null);
            }

            if (meshComps.Count > 0)
            {
                if (activeLOD == "high")
                {
                    //detect if we're trying to import a high poly mesh...
                    string msg = "You are about to import a high poly mesh. \nThese meshes are usually millions of polygons and can cause instability to your project. \nWould you like to proceed?";
                    highPoly = EditorUtility.DisplayDialog("WARNING!", msg, "Yes", "No");
                }
                try {
                    //process meshes and prefabs
                    PrefabData prefData = new PrefabData(path, assetName, folderNamingConvention, lodFadeMode, highPoly, addAssetToScene, setupCollision, hasBillboardLOD, isAlembic, false, false, finalMat, billboardMat, new List <string>(), new List <List <string> >());
                    MegascansMeshUtils.ProcessMeshes(objectList, path, highPoly, plant, prefData);
                } catch (Exception ex) {
                    Debug.Log("Error importing meshes.");
                    Debug.Log(ex.ToString());
                    MegascansUtilities.HideProgressBar();
                }
            }

            var endTime   = System.DateTime.Now;
            var totalTime = endTime - startTime;

            Debug.Log("Asset Import Time: " + totalTime);
            AssetDatabase.Refresh();
            MegascansUtilities.HideProgressBar();
            Resources.UnloadUnusedAssets();
            GC.Collect();
            return(path);
        }
Пример #22
0
        /// <summary>
        /// Generates prefabs from imported meshes.
        /// Used for normal 3D assets
        /// </summary>
        public static void CreatePrefab3D(PrefabData prefabData)
        {
            try {
                string prefabPath = MegascansUtilities.ValidateFolderCreate(prefabData.assetPath, "Prefabs");
                string prefabName = prefabData.finalAssetName.Replace("$mapName", "").Replace("$resolution", "").Replace("$lod", "").Replace("$variation", "");

                //Setting up prefab gameobject
                GameObject prefabGameObject = new GameObject();
                prefabGameObject.name = prefabName;
                prefabGameObject.AddComponent <LODGroup>();
                prefabGameObject.GetComponent <LODGroup>().fadeMode           = (LODFadeMode)prefabData.lodFadeMode; //Casting lod fade mode to enum.
                prefabGameObject.GetComponent <LODGroup>().animateCrossFading = true;
                prefabGameObject.isStatic = true;

                float lodHeight = 1.0f;

                List <LOD> lodsForPrefab = new List <LOD>();
                int        numberOfFiles = prefabData.importedGeometryPaths3D.Count;
                //Instantiate all the meshes in the scene, add them to the material/collider to them.
                for (int x = 0; x < numberOfFiles; x++)
                {
                    UnityEngine.Object loadedGeometry = AssetDatabase.LoadAssetAtPath <UnityEngine.Object>(prefabData.importedGeometryPaths3D[x]);
                    //Highpoly mesh check.
                    if (loadedGeometry.name.ToLower().Contains("highpoly") && !prefabData.highpoly)
                    {
                        continue;
                    }
                    GameObject geometryObject = Instantiate(loadedGeometry) as GameObject;
                    Renderer[] r;
                    //Parent all the objects to the prefab game object.
                    if (geometryObject.transform.childCount > 0 && !prefabData.isAlembic)
                    {
                        r = new Renderer[geometryObject.transform.childCount];
                        for (int j = 0; j < geometryObject.transform.childCount; ++j)
                        {
                            //Parent the child gameobject (geometry) to the prefab game object.
                            GameObject geometryChildObject = geometryObject.transform.GetChild(j).gameObject; //Cache a reference to the child gameobject of the geometry.
                            geometryChildObject.transform.parent        = prefabGameObject.transform;
                            geometryChildObject.transform.localPosition = Vector3.zero;
                            geometryChildObject.name = geometryChildObject.name.Replace("(Clone)", "");
                            //Get reference to the renderer components to apply material later.
                            r[j] = geometryChildObject.GetComponentInChildren <Renderer>();
                        }
                        //Destroy the empty parent container which was holding the meshes.
                        DestroyImmediate(geometryObject);
                    }
                    else if (prefabData.isAlembic) //if the instantiated mesh is an alembic asset.
                    {
                        //Parent the child gameobject (geometry) to the prefab game object.
                        geometryObject.transform.parent        = prefabGameObject.transform;
                        geometryObject.transform.localPosition = Vector3.zero;
                        geometryObject.name = geometryObject.name.Replace("(Clone)", "");
                        //Get reference to the renderer components to apply material later.
                        r = geometryObject.GetComponentsInChildren <Renderer>();
                    }
                    else //if the instantiated mesh does not have any children
                    {
                        //Parent the child gameobject (geometry) to the prefab game object.
                        geometryObject.transform.parent        = prefabGameObject.transform;
                        geometryObject.transform.localPosition = Vector3.zero;
                        geometryObject.name = geometryObject.name.Replace("(Clone)", "");
                        //Get reference to the renderer component to apply material later.
                        r = geometryObject.GetComponentsInChildren <Renderer>();
                    }

                    foreach (Renderer ren in r)
                    {
                        ren.material = prefabData.finalMat;
                        //Apply highpoly material if the mesh was highpoly and highpoly filter is enabled.
                        if (loadedGeometry.name.ToLower().Contains("highpoly") && prefabData.highpoly)
                        {
                            ren.material = prefabData.highpolyMat;
#if UNITY_EDITOR_OSX
                            ren.material = prefabData.finalMat;
#endif
                        }
                        //Apply collision
                        if (prefabData.setupCollision)
                        {
                            ren.gameObject.AddComponent <MeshCollider>().sharedMesh = ren.gameObject.GetComponent <MeshFilter>().sharedMesh;
                        }
                    }

                    if (numberOfFiles > 2)
                    {
                        lodHeight *= ((x + 1) >= (numberOfFiles / 2)) ? 0.75f : 0.5f;
                    }
                    else
                    {
                        lodHeight *= (x + 1) < 1 ? 0.75f : 0.15f;
                    }

                    lodsForPrefab.Add(new LOD(lodHeight, r));
                }
                //Set LODs in the LOD group
                prefabGameObject.GetComponent <LODGroup>().SetLODs(lodsForPrefab.ToArray());
                prefabGameObject.GetComponent <LODGroup>().RecalculateBounds();
                //Prefab saving
                string prefLocation = prefabPath + "/" + prefabName + ".prefab";
                prefLocation = prefLocation.Replace("(Clone)", "");
                SavePrefab(prefabGameObject, prefLocation, prefabData.addAssetToScene);
            }
            catch (Exception ex)
            {
                Debug.Log("Exception::MegascansMeshUtils::3D Asset Prefab:: " + ex.ToString());
                MegascansUtilities.HideProgressBar();
            }
        }