コード例 #1
0
ファイル: IconManager.cs プロジェクト: yazici/FRONTIERS
        public static void ConvertNGUIAtlasToUI(UnityEditor.MenuCommand command)
        {
            UIAtlas   atlas       = UnityEditor.Selection.activeGameObject.GetComponent <UIAtlas> ();
            Texture2D spriteSheet = atlas.texture as Texture2D;
            string    assetPath   = UnityEditor.AssetDatabase.GetAssetPath(spriteSheet.GetInstanceID());

            Debug.Log("Getting asset importer at path " + assetPath);
            UnityEditor.TextureImporter importer = UnityEditor.TextureImporter.GetAtPath(assetPath) as UnityEditor.TextureImporter;

            if (atlas == null || spriteSheet == null)
            {
                return;
            }
            List <UnityEditor.SpriteMetaData> spriteData = new List <UnityEditor.SpriteMetaData> ();

            List <string> spriteNames = atlas.GetListOfSprites();
            int           height      = spriteSheet.height;
            int           width       = spriteSheet.width;

            foreach (string spriteName in spriteNames)
            {
                UIAtlas.Sprite sprite = atlas.GetSprite(spriteName);
                //flip the positions
                Rect rect = sprite.outer;
                //Rect rect = new Rect (0, 0, 50, 50);
                rect.y = height - rect.y - rect.height;
                Vector2 pivot = new Vector2(0.5f, 0.5f);                 // = rect.center;
                //pivot.y = height - pivot.y;
                Vector4 border = Vector4.zero;

                /*if (sprite.hasPadding) {
                 *      border.w = sprite.inner.width;
                 *      border.x = sprite.paddingRight;
                 *      border.y = sprite.paddingTop;
                 *      border.z = sprite.paddingBottom;
                 * }*/
                UnityEditor.SpriteMetaData data = new UnityEditor.SpriteMetaData();
                data.border    = border;
                data.pivot     = pivot;
                data.rect      = rect;
                data.name      = spriteName;
                data.alignment = 0;
                Debug.Log("Created sprite " + spriteName + " with rect: "
                          + "xMin" + rect.xMin + ", "
                          + "xMax" + rect.xMax + ", "
                          + "yMin" + rect.yMin + ", "
                          + "yMax" + rect.yMax + "\n"
                          + "pivotx " + pivot.x + ", "
                          + "pivoty " + pivot.y);
                spriteData.Add(data);
            }

            importer.spriteImportMode = UnityEditor.SpriteImportMode.Multiple;
            importer.spritesheet      = spriteData.ToArray();

            //UnityEditor.AssetDatabase.StartAssetEditing ();
            UnityEditor.AssetDatabase.ImportAsset(importer.assetPath);
            //UnityEditor.AssetDatabase.StopAssetEditing ();
        }
コード例 #2
0
        void GetVoxelThumbnails(VoxelDefinition vd)
        {
            Texture2D top, side, bottom;

            top = side = bottom = null;
            if (vd.overrideMaterial && vd.texturesByMaterial)
            {
                Material  mat = vd.overrideMaterialNonGeo;
                Texture2D tex = (Texture2D)mat.mainTexture;
                if (tex != null)
                {
#if UNITY_EDITOR
                    string path = UnityEditor.AssetDatabase.GetAssetPath(tex);
                    if (!string.IsNullOrEmpty(path))
                    {
                        UnityEditor.TextureImporter timp = UnityEditor.AssetImporter.GetAtPath(path) as UnityEditor.TextureImporter;
                        if (timp != null && !timp.isReadable)
                        {
                            timp.isReadable = true;
                            timp.SaveAndReimport();
                        }
                    }
#endif
                    top = side = bottom = Instantiate <Texture2D> (tex);
                }
            }
            else
            {
                if (vd.renderType == RenderType.Custom && vd.textureSample != null)
                {
                    top = side = bottom = vd.textureSample;
                }
                else
                {
                    top    = vd.textureTop;
                    side   = vd.textureSide;
                    bottom = vd.textureBottom;
                }
            }
            if (top != null)
            {
                vd.textureThumbnailTop           = Instantiate(top) as Texture2D;
                vd.textureThumbnailTop.hideFlags = HideFlags.DontSave;
                TextureTools.Scale(vd.textureThumbnailTop, 64, 64, FilterMode.Point);
            }
            if (side != null)
            {
                vd.textureThumbnailSide           = Instantiate(side) as Texture2D;
                vd.textureThumbnailSide.hideFlags = HideFlags.DontSave;
                TextureTools.Scale(vd.textureThumbnailSide, 64, 64, FilterMode.Point);
            }
            if (bottom != null)
            {
                vd.textureThumbnailBottom           = Instantiate(bottom) as Texture2D;
                vd.textureThumbnailBottom.hideFlags = HideFlags.DontSave;
                TextureTools.Scale(vd.textureThumbnailBottom, 64, 64, FilterMode.Point);
            }
        }
コード例 #3
0
        private void UpdateAssets()
        {
#if UNITY_EDITOR
            for (int i = 0; i < tileCount; i++)
            {
                if (i < tileCount)
                {
                    if (UnityEditor.EditorUtility.DisplayCancelableProgressBar(
                            "Updating Textures",
                            "Reading Texture files",
                            (float)(i) / (float)tileCount))
                    {
                        Debug.Log("Baking canceled by the user");
                        UnityEditor.EditorUtility.ClearProgressBar();
                        bakeAll = false;
                        return;
                    }

                    // else UnityEditor.EditorUtility.ClearProgressBar();
                }

                bakerMask.fileName      = "Assets/CScapeCDK/Editor/Resources/" + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + "/Mask/diff_" + (i + 1).ToString("000") + ".png";
                bakerNormal.fileName    = "Assets/CScapeCDK/Editor/Resources/" + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + "/Normal/Normal_" + (i + 1).ToString("000") + ".png";
                bakerDepth.fileName     = "Assets/CScapeCDK/Editor/Resources/" + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + "/Depth/depth_" + (i + 1).ToString("000") + ".png";
                bakerOcclusion.fileName = "Assets/CScapeCDK/Editor/Resources/" + UnityEngine.SceneManagement.SceneManager.GetActiveScene().name + "/AO/ao_" + (i + 1).ToString("000") + ".png";

                UnityEditor.TextureImporter A = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(bakerNormal.fileName);
                A.isReadable         = true;
                A.sRGBTexture        = false;
                A.textureCompression = UnityEditor.TextureImporterCompression.Uncompressed;
                UnityEditor.AssetDatabase.ImportAsset(bakerNormal.fileName, UnityEditor.ImportAssetOptions.ForceUpdate);

                UnityEditor.TextureImporter B = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(bakerDepth.fileName);
                B.isReadable         = true;
                B.sRGBTexture        = false;
                B.textureCompression = UnityEditor.TextureImporterCompression.Uncompressed;
                UnityEditor.AssetDatabase.ImportAsset(bakerDepth.fileName, UnityEditor.ImportAssetOptions.ForceUpdate);

                UnityEditor.TextureImporter C = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(bakerMask.fileName);
                C.isReadable         = true;
                C.sRGBTexture        = false;
                C.textureCompression = UnityEditor.TextureImporterCompression.Uncompressed;
                UnityEditor.AssetDatabase.ImportAsset(bakerMask.fileName, UnityEditor.ImportAssetOptions.ForceUpdate);

                UnityEditor.TextureImporter D = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(bakerOcclusion.fileName);
                D.isReadable         = true;
                D.sRGBTexture        = false;
                D.textureCompression = UnityEditor.TextureImporterCompression.Uncompressed;
                UnityEditor.AssetDatabase.ImportAsset(bakerOcclusion.fileName, UnityEditor.ImportAssetOptions.ForceUpdate);
            }
            UnityEditor.EditorUtility.ClearProgressBar();
#endif
        }
コード例 #4
0
        /// <summary>
        /// Private default texture resolver. Copies the given texture into the asset database.
        /// </summary>
        private static Texture2D DefaultTextureResolver(pxr.SdfAssetPath textureAssetPath,
                                                        bool isNormalMap,
                                                        SceneImportOptions options)
        {
#if UNITY_EDITOR
            if (!File.Exists(textureAssetPath.GetResolvedPath()))
            {
                return(null);
            }

            string sourcePath = textureAssetPath.GetResolvedPath();
            string destPath   = Path.Combine(options.projectAssetPath, Path.GetFileName(sourcePath));
            string assetPath  = options.projectAssetPath + Path.GetFileName(sourcePath);

            string fullPath = destPath;
            if (fullPath.StartsWith("Assets/"))
            {
                fullPath = fullPath.Substring("Assets/".Length);
            }

            if (!File.Exists(destPath))
            {
                UnityEditor.FileUtil.CopyFileOrDirectory(sourcePath, destPath);
                UnityEditor.AssetDatabase.ImportAsset(assetPath);
                UnityEditor.TextureImporter texImporter =
                    (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(assetPath);
                if (texImporter == null)
                {
                    Debug.LogError("Failed to load asset: " + assetPath);
                    return(null);
                }
                else
                {
                    texImporter.isReadable = true;
                    if (isNormalMap)
                    {
                        texImporter.convertToNormalmap = true;
                        texImporter.textureType        = UnityEditor.TextureImporterType.NormalMap;
                    }

                    UnityEditor.EditorUtility.SetDirty(texImporter);
                    texImporter.SaveAndReimport();
                }
            }

            return((Texture2D)UnityEditor.AssetDatabase.LoadAssetAtPath(assetPath, typeof(Texture2D)));
#else
            return(null);
#endif
        }
コード例 #5
0
        /// <summary>
        /// for use only in Unity Editor in simulation mode
        /// </summary>
        public Sprite GetSprite()
        {
#if UNITY_EDITOR
            Texture2D texture = mAsset as Texture2D;
            if (texture != null && mSprite == null)
            {
                //load sprite information
                string path = UnityEditor.AssetDatabase.GetAssetPath(texture);
                UnityEditor.TextureImporter ti = UnityEditor.AssetImporter.GetAtPath(path) as UnityEditor.TextureImporter;
                ti.isReadable = true;
                mSprite       = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), ti.spritePivot, ti.spritePixelsPerUnit, 1, SpriteMeshType.Tight, ti.spriteBorder);
            }
#endif
            return(mSprite);
        }
コード例 #6
0
        private static void MenuItem_GetAssetImporterWithAssetsPath()
        {
            //事前処理。
            {
                BlueBack.AssetLib.Editor.CreateDirectoryWithAssetsPath.Create("Out");
                BlueBack.AssetLib.Editor.SaveAssetWithAssetsPath.SaveConverter(UnityEngine.Texture2D.whiteTexture, new BlueBack.AssetLib.PngConverterAssetToBinary(), "Out/test.png");
                BlueBack.AssetLib.Editor.RefreshAssetDatabase.Refresh();
            }

            //GetAssetImporterWithAssetsPath
            {
                UnityEditor.TextureImporter t_textureimporter = BlueBack.AssetLib.Editor.GetAssetImporterWithAssetsPath.Get <UnityEditor.TextureImporter>("Out/test.png");
                UnityEngine.Debug.Log(t_textureimporter.filterMode.ToString());
            }
        }
コード例 #7
0
        protected UnityEngine.Texture2D GetTexture(string texturePath)
        {
            try
            {
#if UNITY_EDITOR_MAC
                UnityEditor.TextureImporter importer = UnityEditor.AssetImporter.GetAtPath(texturePath) as UnityEditor.TextureImporter;
                importer.textureType = UnityEditor.TextureImporterType.Cursor;
                UnityEditor.AssetDatabase.WriteImportSettingsIfDirty(texturePath);
#endif
                return(UnityEditor.AssetDatabase.LoadAssetAtPath <UnityEngine.Texture2D>(texturePath));
            }
            catch (System.Exception ex)
            {
                UnityEngine.Debug.LogError(string.Format("WwiseUnity: Failed to find local texture: {0}", ex));
                return(null);
            }
        }
コード例 #8
0
        public override bool SetTextureOnMaterial(string fieldName, ImageData id, PlaytimePainter pntr)
        {
            //  if (id == null)
            //    return;

            Texture tex = id.CurrentTexture();

            if (pntr.terrain != null)
            {
                if (fieldName.Contains(PainterDataAndConfig.terrainLight))
                {
                    FindMergingTerrain(pntr);
                    if ((mergingTerrain != null) && (id != null))
                    {
                        mergingTerrain.lightTexture = id.texture2D;
                    }

#if UNITY_EDITOR
                    if (tex is Texture2D)
                    {
                        UnityEditor.TextureImporter timp = ((Texture2D)tex).GetTextureImporter();
                        if (timp != null)
                        {
                            bool needReimport = timp.WasClamped();
                            needReimport |= timp.HadNoMipmaps();

                            if (needReimport)
                            {
                                timp.SaveAndReimport();
                            }
                        }
                    }
#endif

                    Shader.SetGlobalTexture(PainterDataAndConfig.terrainLight, tex);



                    return(true);
                }
            }
            return(false);
        }
コード例 #9
0
        private void CheckTextureIsReadable()
        {
            _isReadable = true;
            if (_material == null)
            {
                return;
            }

#if !UNITY_2017_3_OR_NEWER
            if (_material is ProceduralMaterial)
            {
                _type = SurfaceTypes.Substance;
            }
            else
            {
                _type = SurfaceTypes.Material;
            }
            if (_type == SurfaceTypes.Substance)
            {
                return;
            }
#endif
#if UNITY_EDITOR
            Texture texture = material.mainTexture;
            if (texture == null)
            {
                _isReadable = false;
                return;
            }
            string texturePath = UnityEditor.AssetDatabase.GetAssetPath(texture);
            UnityEditor.TextureImporter textureImporter = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(texturePath);
            if (textureImporter == null)
            {
                _isReadable = false;
                return;
            }
            if (!textureImporter.isReadable)
            {
                _isReadable = false;
            }
#endif
        }
コード例 #10
0
        static public void SetTextureReadWrite(Texture2D tex)
        {
            if (tex == null)
            {
                return;
            }

            #if UNITY_EDITOR
            string path = UnityEditor.AssetDatabase.GetAssetPath(tex);
            UnityEditor.TextureImporter textureImporter = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(path);

            if (textureImporter != null)
            {
                if (!textureImporter.isReadable)
                {
                    textureImporter.isReadable = true;
                    UnityEditor.AssetDatabase.ImportAsset(path, UnityEditor.ImportAssetOptions.ForceUpdate);
                }
            }
            #endif
        }
コード例 #11
0
        protected static List <SpriteOutline> GenerateSpriteRectOutline(Rect rect, ITexture2D texture, float detail, byte alphaTolerance)
        {
            List <SpriteOutline> list = new List <SpriteOutline>();

            if (texture != null)
            {
                int num  = 0;
                int num2 = 0;
                UnityEditor.TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as UnityEditor.TextureImporter;
                textureImporter.GetWidthAndHeight(ref num, ref num2);
                int     width  = texture.width;
                int     height = texture.height;
                Vector2 vector = new Vector2((float)width / (float)num, (float)height / (float)num2);
                Rect    rect2  = rect;
                rect2.xMin *= vector.x;
                rect2.xMax *= vector.x;
                rect2.yMin *= vector.y;
                rect2.yMax *= vector.y;
                Vector2[][] array;
                UnityEditor.Sprites.SpriteUtility.GenerateOutline(texture, rect2, detail, alphaTolerance, true, out array);
                Rect r = default(Rect);
                r.size   = rect.size;
                r.center = Vector2.zero;
                for (int i = 0; i < array.Length; i++)
                {
                    SpriteOutline spriteOutline = new SpriteOutline();
                    Vector2[]     array2        = array[i];
                    for (int j = 0; j < array2.Length; j++)
                    {
                        Vector2 vector2 = array2[j];
                        spriteOutline.Add(SpriteOutlineModule.CapPointToRect(new Vector2(vector2.x / vector.x, vector2.y / vector.y), r));
                    }
                    list.Add(spriteOutline);
                }
            }
            return(list);
        }
コード例 #12
0
        public override bool SetTextureOnMaterial(string fieldName, ImageData id, PlaytimePainter painter)
        {
            Texture tex = id.CurrentTexture();

            if (painter.terrain != null)
            {
                if (fieldName.Contains(PainterDataAndConfig.terrainTexture))
                {
                    int no = fieldName[0].CharToInt();
                    painter.terrain.SetSplashPrototypeTexture(id.texture2D, no);
                    if (tex.GetType() != typeof(Texture2D))
                    {
                        //else
                        Debug.Log("Can only use Texture2D for Splat Prototypes. If using regular terrain may not see changes.");
                    }
                    else
                    {
#if UNITY_EDITOR
                        UnityEditor.TextureImporter timp = ((Texture2D)tex).GetTextureImporter();
                        if (timp != null)
                        {
                            bool needReimport = timp.WasClamped();
                            needReimport |= timp.HadNoMipmaps();

                            if (needReimport)
                            {
                                timp.SaveAndReimport();
                            }
                        }
#endif
                    }
                    return(true);
                }
            }
            return(false);
        }
コード例 #13
0
ファイル: Tileset.cs プロジェクト: Aye1/Herborist
        public void UpdateTilesetConfigFromAtlasImportSettings()
        {
            if (AtlasTexture != null)
            {
                string assetPath = UnityEditor.AssetDatabase.GetAssetPath(AtlasTexture);
                if (!string.IsNullOrEmpty(assetPath))
                {
                    UnityEditor.TextureImporter textureImporter = UnityEditor.AssetImporter.GetAtPath(assetPath) as UnityEditor.TextureImporter;
                    if (textureImporter != null)
                    {
                        m_pixelsPerUnit = textureImporter.spritePixelsPerUnit;
                        if (textureImporter.textureType == UnityEditor.TextureImporterType.Sprite)
                        {
                            if (textureImporter.spriteImportMode == UnityEditor.SpriteImportMode.Multiple)
                            {
                                List <Tile> tiles = new List <Tile>();
                                if (textureImporter.spritesheet.Length >= 2)
                                {
                                    UnityEditor.SpriteMetaData spr0 = textureImporter.spritesheet[0];
                                    UnityEditor.SpriteMetaData spr1 = textureImporter.spritesheet[1];
                                    TilePxSize     = textureImporter.spritesheet[0].rect.size;
                                    SliceOffset    = spr0.rect.position; SliceOffset.y = AtlasTexture.height - spr0.rect.y - spr0.rect.height;
                                    SlicePadding.x = spr1.rect.x - spr0.rect.xMax;
                                }
                                if (textureImporter.spritesheet.Length >= 2)
                                {
                                    //+++Ask before importing tiles
                                    if (m_tiles.Count == 0 || !UnityEditor.EditorUtility.DisplayDialog("Import Sprite Sheet?", "This texture atlas contains sliced sprites. Do you want to overwrite current tiles with these ones?", "Yes", "No"))
                                    //---
                                    {
                                        m_tilesetHeight = 0;
                                        foreach (UnityEditor.SpriteMetaData spriteData in textureImporter.spritesheet)
                                        {
                                            Rect rUV = new Rect(Vector2.Scale(spriteData.rect.position, AtlasTexture.texelSize), Vector2.Scale(spriteData.rect.size, AtlasTexture.texelSize));
                                            tiles.Add(new Tile()
                                            {
                                                uv = rUV
                                            });
                                            if (tiles.Count >= 2)
                                            {
                                                if (tiles[tiles.Count - 2].uv.y != tiles[tiles.Count - 1].uv.y)
                                                {
                                                    if (m_tilesetHeight == 1)
                                                    {
                                                        m_tilesetWidth = tiles.Count - 1;
                                                        SlicePadding.y = textureImporter.spritesheet[tiles.Count - 2].rect.y - textureImporter.spritesheet[tiles.Count - 1].rect.yMax;
                                                    }
                                                    ++m_tilesetHeight;
                                                }
                                            }
                                            else
                                            {
                                                ++m_tilesetHeight;
                                            }
                                        }
                                        TileRowLength = m_tilesetWidth;
                                        //Copy data from previous tiles
#if UNITY_EDITOR
                                        if (m_tiles != null && m_tiles.Count > 0 && UnityEditor.EditorUtility.DisplayDialog("Keep previous tile properties?", "Keeping previous tile properties will copy the collider and paramters of previous tiles", "Yes", "No"))
#endif
                                        {
                                            for (int i = 0; i < m_tiles.Count && i < tiles.Count; ++i)
                                            {
                                                tiles[i].collData       = m_tiles[i].collData;
                                                tiles[i].paramContainer = m_tiles[i].paramContainer;
                                                tiles[i].prefabData     = m_tiles[i].prefabData;
                                            }
                                        }
                                        m_tiles = tiles;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #14
0
 public TextureImporter(UnityEditor.TextureImporter textureImporter)
 {
     this.m_AssetImporter = textureImporter;
 }
コード例 #15
0
        /// <summary>
        /// Serialize the entire texture into the specified DataNode.
        /// </summary>

        static public void Serialize(this Texture tex, DataNode node)
        {
            if (!mFullSerialization)
            {
                return;
            }

            node.AddChild("name", tex.name);
            string path = UnityTools.LocateResource(tex);

            if (!string.IsNullOrEmpty(path))
            {
                node.AddChild("path", path);
                return;
            }

            if (tex is Texture2D)
            {
                Texture2D t2 = tex as Texture2D;

#if UNITY_EDITOR
                try
                {
                    byte[] bytes = t2.EncodeToPNG();
                    if (bytes != null)
                    {
                        node.AddChild("bytes", bytes);
                    }
                    else
                    {
                        Debug.Log(t2.name + " (" + t2.format + ")", tex);
                    }
                }
                catch (Exception)
                {
                    string assetPath = UnityEditor.AssetDatabase.GetAssetPath(tex);

                    if (!string.IsNullOrEmpty(assetPath))
                    {
                        UnityEditor.TextureImporter ti = UnityEditor.AssetImporter.GetAtPath(assetPath) as UnityEditor.TextureImporter;
                        ti.isReadable = true;
                        UnityEditor.AssetDatabase.ImportAsset(assetPath);
                        byte[] bytes = t2.EncodeToPNG();
                        if (bytes != null)
                        {
                            node.AddChild("bytes", bytes);
                        }
                        else
                        {
                            Debug.Log(t2.name + " (" + t2.format + ")", tex);
                        }
                    }
                }
#else
                node.AddChild("bytes", t2.EncodeToPNG());
#endif
                node.AddChild("filter", (int)t2.filterMode);
                node.AddChild("wrap", (int)t2.wrapMode);
                node.AddChild("af", t2.anisoLevel);
                return;
            }

            Debug.LogWarning("Unable to save a reference to texture '" + tex.name + "' because it's not in the Resources folder.", tex);
        }
コード例 #16
0
        /// <summary>
        /// Exports the given texture to the destination texture path and wires up the preview surface.
        /// </summary>
        /// <returns>
        /// Returns the path to the USD texture object.
        /// </returns>
        protected static string SetupTexture(Scene scene,
                                             string usdShaderPath,
                                             Material material,
                                             PreviewSurfaceSample surface,
                                             Vector4 scale,
                                             string destTexturePath,
                                             string textureName,
                                             string textureOutput,
                                             ConversionType conversionType = ConversionType.None)
        {
            // We have to handle multiple cases here:
            // - file exists on disk
            //   - file is a supported format => can be directly copied
            //   - file is not in a supported format => need to blit / export
            // - file is only in memory
            //   - a Texture2D
            //   - a Texture
            //   - a RenderTexture
            //   - needs special care if marked as Normal Map
            //     (can probably only be detected in an Editor context, and heuristically at runtime)
            //   => need to blit / export
            // - file is not supported at all (or not yet)
            //   - a 3D texture
            //   => needs to be ignored, log Warning

            bool textureIsExported = false;

            string filePath = null;
            string fileName = null;

            var srcTexture2d = material.GetTexture(textureName);

            bool needsConversion = false;

            switch (conversionType)
            {
            case ConversionType.None:
                break;

            case ConversionType.UnpackNormal:
#if UNITY_EDITOR
                if (UnityEditor.AssetDatabase.Contains(srcTexture2d))
                {
                    // normal needs to be converted if the one on disk isn't really a normal map
                    // (e.g. created from greyscale)
                    UnityEditor.TextureImporter importer =
                        (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(
                            UnityEditor.AssetDatabase.GetAssetPath(srcTexture2d));
                    if (importer.textureType != UnityEditor.TextureImporterType.NormalMap)
                    {
                        Debug.LogWarning("Texture " + textureName + " is set as NormalMap but isn't marked as such",
                                         srcTexture2d);
                    }

                    UnityEditor.TextureImporterSettings dst = new UnityEditor.TextureImporterSettings();
                    importer.ReadTextureSettings(dst);
                    // if this NormalMap is created from greyscale we will export the NormalMap from memory.
                    if (dst.convertToNormalMap)
                    {
                        needsConversion = true;
                        break;
                    }
                }
#endif
                break;

            default:
                needsConversion = true;
                break;
            }

#if UNITY_EDITOR
            // only export from disk if there's no need to do any type of data conversion here
            if (!needsConversion)
            {
                var srcPath = UnityEditor.AssetDatabase.GetAssetPath(srcTexture2d);

                if (!string.IsNullOrEmpty(srcPath))
                {
#if UNITY_2019_2_OR_GREATER
                    // Since textures might be inside of packages for various reasons we should support that.
                    // Usually this would just be "Path.GetFullPath(srcPath)", but USD export messes with the CWD (Working Directory)
                    // and so we have to do a bit more path wrangling here.
                    if (srcPath.StartsWith("Packages"))
                    {
                        var pi = UnityEditor.PackageManager.PackageInfo.FindForAssetPath(srcPath);
                        srcPath = pi.resolvedPath + srcPath.Substring(("Packages/" + pi.name).Length);
                    }
#endif
                    if (srcPath.StartsWith("Assets"))
                    {
                        srcPath = Application.dataPath + "/" + srcPath.Substring("Assets/".Length);
                    }

                    fileName = System.IO.Path.GetFileName(srcPath);
                    filePath = System.IO.Path.Combine(destTexturePath, fileName);

                    if (System.IO.File.Exists(srcPath))
                    {
                        // USDZ officially only supports png / jpg / jpeg
                        // https://graphics.pixar.com/usd/docs/Usdz-File-Format-Specification.html

                        var ext = System.IO.Path.GetExtension(srcPath).ToLowerInvariant();
                        if (ext == ".png" || ext == ".jpg" || ext == ".jpeg")
                        {
                            System.IO.File.Copy(srcPath, filePath, overwrite: true);
                            if (System.IO.File.Exists(filePath))
                            {
                                textureIsExported = true;
                            }
                        }
                    }
                }
            }
#endif

            if (!textureIsExported)
            {
                // Since this is a texture we can't directly export from disk, we need to blit it and output it as PNG.
                // To avoid collisions, e.g. with multiple different textures named the same, each texture gets a pseudo-random name.
                // This will also avoid collisions when exporting multiple models to the same folder, e.g. with a a RenderTexture called "RT"
                // in each of them that might look different between exports.
                // TODO Future work could, if necessary, generate a texture content hash to avoid exporting identical textures multiple times
                // (Unity's content hash isn't reliable for some types of textures unfortunately, e.g. RTs)
#if UNITY_EDITOR
                if (srcTexture2d is Texture2D)
                {
                    fileName = srcTexture2d.name + "_" + srcTexture2d.imageContentsHash.ToString();
                }
                else
                {
                    fileName = srcTexture2d.name + "_" + Random.Range(10000000, 99999999).ToString();
                }
#else
                fileName = srcTexture2d.name + "_" + Random.Range(10000000, 99999999).ToString();
#endif
                filePath = System.IO.Path.Combine(destTexturePath, fileName + ".png");

                // TODO extra care has to be taken of Normal Maps etc., since these are in a converted format in memory (for example 16 bit AG instead of 8 bit RGBA, depending on platform)
                // An example of this conversion in a shader is in Khronos' UnityGLTF implementation.
                // Basically, the blit has do be done with the right unlit conversion shader to get a proper "file-based" tangent space normal map back

                // Blit the texture and get it back to CPU
                // Note: Can't use RenderTexture.GetTemporary because that doesn't properly clear alpha channel
                bool preserveLinear = false;
                switch (conversionType)
                {
                case ConversionType.UnpackNormal:
                    preserveLinear = true;
                    break;
                }

                var rt = new RenderTexture(srcTexture2d.width, srcTexture2d.height, 0, RenderTextureFormat.ARGB32,
                                           preserveLinear ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.Default);
                var resultTex2d = new Texture2D(srcTexture2d.width, srcTexture2d.height, TextureFormat.ARGB32, true,
                                                preserveLinear ? true : false);
                var activeRT = RenderTexture.active;
                try
                {
                    RenderTexture.active = rt;
                    GL.Clear(true, true, Color.clear);

                    // conversion material
                    if (_metalGlossChannelSwapMaterial == null)
                    {
                        _metalGlossChannelSwapMaterial = new Material(Shader.Find("Hidden/USD/ChannelCombiner"));
                    }

                    if (_normalChannelMaterial == null)
                    {
                        _normalChannelMaterial = new Material(Shader.Find("Hidden/USD/NormalChannel"));
                    }

                    _metalGlossChannelSwapMaterial.SetTexture("_R", srcTexture2d);
                    _metalGlossChannelSwapMaterial.SetTexture("_G", srcTexture2d);
                    _metalGlossChannelSwapMaterial.SetTexture("_B", srcTexture2d);
                    _metalGlossChannelSwapMaterial.SetTexture("_A", srcTexture2d);

                    switch (conversionType)
                    {
                    case ConversionType.None:
                        Graphics.Blit(srcTexture2d, rt);
                        break;

                    case ConversionType.SwapRASmoothnessToBGRoughness:
                        _metalGlossChannelSwapMaterial.SetVector("_Invert",
                                                                 new Vector4(0, 1, 0, 1)); // invert resulting g channel, make sure alpha is 1
                        _metalGlossChannelSwapMaterial.SetVector("_RScale", new Vector4(0, 0, 0, 0));
                        _metalGlossChannelSwapMaterial.SetVector("_GScale",
                                                                 new Vector4(0, 0, 0, 1)); // use a channel from _G texture for resulting g
                        _metalGlossChannelSwapMaterial.SetVector("_BScale",
                                                                 new Vector4(1, 0, 0, 0)); // use r channel from _B texture for resulting b
                        _metalGlossChannelSwapMaterial.SetVector("_AScale", new Vector4(0, 0, 0, 0));

                        Graphics.Blit(srcTexture2d, rt, _metalGlossChannelSwapMaterial);
                        break;

                    case ConversionType.InvertAlpha:
                        _metalGlossChannelSwapMaterial.SetVector("_Invert",
                                                                 new Vector4(0, 0, 0, 1)); // invert alpha result
                        _metalGlossChannelSwapMaterial.SetVector("_RScale",
                                                                 new Vector4(1, 0, 0, 0)); // use all color channels as-is
                        _metalGlossChannelSwapMaterial.SetVector("_GScale", new Vector4(0, 1, 0, 0));
                        _metalGlossChannelSwapMaterial.SetVector("_BScale", new Vector4(0, 0, 1, 0));
                        _metalGlossChannelSwapMaterial.SetVector("_AScale", new Vector4(0, 0, 0, 1));

                        Graphics.Blit(srcTexture2d, rt, _metalGlossChannelSwapMaterial);
                        break;

                    case ConversionType.MaskMapToORM:
                        // Input is RGBA (Metallic, Occlusion, Detail, Smoothness)
                        // Output is RGB1 (Occlusion, Roughness = 1 - Smoothness, Metallic, 1)
                        _metalGlossChannelSwapMaterial.SetVector("_Invert",
                                                                 new Vector4(0, 1, 0, 1)); // smoothness to roughness, solid alpha
                        _metalGlossChannelSwapMaterial.SetVector("_RScale", new Vector4(0, 1, 0, 0));
                        _metalGlossChannelSwapMaterial.SetVector("_GScale", new Vector4(0, 0, 0, 1));
                        _metalGlossChannelSwapMaterial.SetVector("_BScale", new Vector4(1, 0, 0, 0));
                        _metalGlossChannelSwapMaterial.SetVector("_AScale", new Vector4(0, 0, 0, 0));

                        Graphics.Blit(srcTexture2d, rt, _metalGlossChannelSwapMaterial);
                        break;

                    case ConversionType.UnpackNormal:
                        Graphics.Blit(srcTexture2d, rt, _normalChannelMaterial);
                        break;
                    }

                    resultTex2d.ReadPixels(new Rect(0, 0, srcTexture2d.width, srcTexture2d.height), 0, 0);
                    resultTex2d.Apply();

                    System.IO.File.WriteAllBytes(filePath, resultTex2d.EncodeToPNG());
                    if (System.IO.File.Exists(filePath))
                    {
                        textureIsExported = true;
                    }
                }
                finally
                {
                    RenderTexture.active = activeRT;
                    rt.Release();
                    GameObject.DestroyImmediate(rt);
                    GameObject.DestroyImmediate(resultTex2d);
                }
            }

            if (!textureIsExported)
            {
                var tmpTex2d = new Texture2D(1, 1, TextureFormat.ARGB32, true);
                try
                {
                    tmpTex2d.SetPixel(0, 0, Color.white);
                    tmpTex2d.Apply();
                    System.IO.File.WriteAllBytes(filePath, tmpTex2d.EncodeToPNG());
                    if (System.IO.File.Exists(filePath))
                    {
                        textureIsExported = true;
                    }
                }
                finally
                {
                    GameObject.DestroyImmediate(tmpTex2d);
                }
            }

            if (textureIsExported)
            {
                // Make file path baked into USD relative to scene file and use forward slashes.
                filePath = ImporterBase.MakeRelativePath(scene.FilePath, filePath);
                filePath = filePath.Replace("\\", "/");

                var uvReader = new PrimvarReaderSample <Vector2>();
                uvReader.varname.defaultValue = new TfToken("st");
                scene.Write(usdShaderPath + "/uvReader", uvReader);
                var usdTexReader = new TextureReaderSample(filePath, usdShaderPath + "/uvReader.outputs:result");
                usdTexReader.wrapS =
                    new Connectable <TextureReaderSample.WrapMode>(
                        TextureReaderSample.GetWrapMode(srcTexture2d.wrapModeU));
                usdTexReader.wrapT =
                    new Connectable <TextureReaderSample.WrapMode>(
                        TextureReaderSample.GetWrapMode(srcTexture2d.wrapModeV));
                if (scale != Vector4.one)
                {
                    usdTexReader.scale = new Connectable <Vector4>(scale);
                }

                // usdTexReader.isSRGB = new Connectable<TextureReaderSample.SRGBMode>(TextureReaderSample.SRGBMode.Auto);
                scene.Write(usdShaderPath + "/" + textureName, usdTexReader);
                return(usdShaderPath + "/" + textureName + ".outputs:" + textureOutput);
            }
            else
            {
                Debug.LogError(
                    "Texture wasn't exported: " + srcTexture2d.name + " (" + textureName + " from material " + material,
                    srcTexture2d);
                return(null);
            }
        }