Наследование: AssetImporter
Пример #1
0
    private static void ExportSplat()
    {
        int length = m_terrain.get_terrainData().get_splatPrototypes().Length;

        for (int i = 0; i < length; i++)
        {
            SplatPrototype prototype           = m_terrain.get_terrainData().get_splatPrototypes()[i];
            Texture2D      textured            = prototype.get_texture();
            string         assetPath           = UnityEditor.AssetDatabase.GetAssetPath(textured.GetInstanceID());
            UnityEditor.TextureImporter atPath = UnityEditor.AssetImporter.GetAtPath(assetPath) as UnityEditor.TextureImporter;
            atPath.isReadable         = true;
            atPath.textureCompression = UnityEditor.TextureImporterCompression.Uncompressed;
            UnityEditor.AssetDatabase.ImportAsset(assetPath);
            FileStream output = File.Open(m_saveLocation + "/" + textured.get_name().ToLower() + ".jpg", System.IO.FileMode.Create);
            new BinaryWriter(output).Write(ImageConversion.EncodeToJPG(textured));
            output.Close();
            if (prototype.get_normalMap() != null)
            {
                textured = prototype.get_normalMap();
                string path = UnityEditor.AssetDatabase.GetAssetPath(textured.GetInstanceID());
                UnityEditor.TextureImporter importer2 = UnityEditor.AssetImporter.GetAtPath(path) as UnityEditor.TextureImporter;
                importer2.isReadable         = true;
                importer2.textureCompression = UnityEditor.TextureImporterCompression.Uncompressed;
                UnityEditor.AssetDatabase.ImportAsset(path);
                FileStream stream2 = File.Open(m_saveLocation + "/" + textured.get_name().ToLower() + ".jpg", System.IO.FileMode.Create);
                new BinaryWriter(stream2).Write(ImageConversion.EncodeToJPG(textured));
                stream2.Close();
            }
        }
    }
Пример #2
0
        public void AnalyzerTexture()
        {
            this.width = this.texture.width;
            this.height = this.texture.height;
            this.size = CalculateTextureSizeBytes(this.texture);
            this.ti = AssetImporter.GetAtPath(path) as TextureImporter;
            if (ti != null)
            {
                this.isRW = ti.isReadable;

                androidPlatSetting.isSetting = ti.GetPlatformTextureSettings(TexturePlatSetting.PLAT_ANDROID,
                        out androidPlatSetting.maxSize, out androidPlatSetting.textureFormat);

                iosPlatSetting.isSetting = ti.GetPlatformTextureSettings(TexturePlatSetting.PLAT_IPHONE,
                        out iosPlatSetting.maxSize, out iosPlatSetting.textureFormat);

                standalonePlatSetting.isSetting = ti.GetPlatformTextureSettings(TexturePlatSetting.PLAT_STANDALONE,
                        out standalonePlatSetting.maxSize, out standalonePlatSetting.textureFormat);

                this.isMipmap = ti.mipmapEnabled;
                this.isLightmap = ti.lightmap;
                this.anisoLevel = ti.anisoLevel;
            }

            CheckValid();
        }
Пример #3
0
        public static void SetTextureInfo(TextureImporterType textureType, bool alphaIsTransparency,
                                          TextureImporterNPOTScale npotScale, TextureWrapMode wrapMode, int textureSize,
                                          Action <UnityEditor.TextureImporter> customAction)
        {
            Texture[] selections = Selection.GetFiltered <Texture>(SelectionMode.Assets);
            if (selections == null || selections.Length == 0)
            {
                Debug.Log("Please select some assets first");
                return;
            }

            foreach (var asset in selections)
            {
                string path = AssetDatabase.GetAssetPath(asset);
                UnityEditor.TextureImporter tex = UnityEditor.TextureImporter.GetAtPath(path) as UnityEditor.TextureImporter;
                tex.textureType         = textureType;
                tex.alphaIsTransparency = alphaIsTransparency;
                tex.npotScale           = npotScale;
                tex.wrapMode            = wrapMode;
                tex.maxTextureSize      = textureSize;

                customAction?.Invoke(tex);

                AssetDatabase.ImportAsset(path);
                Debug.Log($"TextureImporter  {path}");
            }
        }
Пример #4
0
    public override void AssetRailsOnPreprocessTexture()
    {
        // Debug.Log("Import:categoryName:" + categoryName);
        // Debug.Log("Import:bundleName:" + bundleName);


        // run import settings for specific category.
        if (categoryName == "characters")
        {
            UnityEditor.TextureImporter importer = assetImporter as UnityEditor.TextureImporter;
            importer.textureType   = UnityEditor.TextureImporterType.Image;
            importer.textureFormat = TextureImporterFormat.ARGB16;
        }


        if (categoryName == "images")
        {
            UnityEditor.TextureImporter importer = assetImporter as UnityEditor.TextureImporter;
            importer.textureType         = UnityEditor.TextureImporterType.Advanced;
            importer.npotScale           = TextureImporterNPOTScale.None;
            importer.isReadable          = true;
            importer.alphaIsTransparency = true;
            importer.mipmapEnabled       = false;
            importer.wrapMode            = TextureWrapMode.Repeat;
            importer.filterMode          = FilterMode.Bilinear;
            importer.textureFormat       = TextureImporterFormat.ARGB16;
            return;
        }
    }
Пример #5
0
    private Vector2 GetOriginalTextureSize(Texture2D texture)
    {
                #if UNITY_EDITOR
        string path = UnityEditor.AssetDatabase.GetAssetPath(texture);
        UnityEditor.TextureImporter importer = UnityEditor.AssetImporter.GetAtPath(path) as UnityEditor.TextureImporter;

        if (importer != null)
        {
            UnityEditor.TextureImporterNPOTScale lastScale = importer.npotScale;
            int lastSize = importer.maxTextureSize;
            importerSize = lastSize;
            //pixels2Unity = importer.spritePixelsToUnits;
            pixels2Unity            = importer.spritePixelsPerUnit;
            importer.npotScale      = UnityEditor.TextureImporterNPOTScale.None;
            importer.maxTextureSize = 4096;
            UnityEditor.AssetDatabase.ImportAsset(path, UnityEditor.ImportAssetOptions.ForceUpdate);

            int width  = texture.width;
            int height = texture.height;

            importer.npotScale      = lastScale;
            importer.maxTextureSize = lastSize;
            UnityEditor.AssetDatabase.ImportAsset(path, UnityEditor.ImportAssetOptions.ForceUpdate);

            return(new Vector2(width, height));
        }
        else
        {
            Debug.LogError("TextureImporter is null!");
            return(Vector2.zero);
        }
#else
        return(Vector2.zero);
#endif
    }
Пример #6
0
 public void OnPreprocessTexture()
 {
     UnityEditor.TextureImporter importer = this.assetImporter as UnityEditor.TextureImporter;
     if (importer.assetPath.Contains("/BundleEditing/UI/"))
     {
         importer.textureType   = TextureImporterType.Sprite;
         importer.mipmapEnabled = false;
     }
 }
Пример #7
0
 protected void SetTextureNonReadable(string _Path)
 {
     UnityEditor.TextureImporter importer = UnityEditor.AssetImporter.GetAtPath(_Path) as UnityEditor.TextureImporter;
     if (importer.isReadable == true)
     {
         importer.isReadable = false;
         AssetDatabase.ImportAsset(_Path);
     }
 }
 private static SpriteMetaData GetMetaDataInMultipleMode(string name, TextureImporter textureImporter)
 {
   SpriteMetaData[] spritesheet = textureImporter.spritesheet;
   for (int index = 0; index < spritesheet.Length; ++index)
   {
     if (spritesheet[index].name.Equals(name))
       return spritesheet[index];
   }
   return new SpriteMetaData();
 }
Пример #9
0
    private void UpdateAssets()
    {
#if UNITY_EDITOR
        UnityEditor.TextureImporter A = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(fileName);
        A.isReadable         = true;
        A.sRGBTexture        = false;
        A.textureCompression = UnityEditor.TextureImporterCompression.Uncompressed;
        UnityEditor.AssetDatabase.ImportAsset(fileName, UnityEditor.ImportAssetOptions.ForceUpdate);
#endif
    }
        static void CheckPalette()
        {
            if (paletteSource != null)
            {
                string texturePath = UnityEditor.AssetDatabase.GetAssetPath(paletteSource);
                UnityEditor.TextureImporter textureImporter = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(texturePath);
                paletteIsReadable = textureImporter.isReadable;

                paletteIsSmall = paletteSource.width + paletteSource.height < 200;
            }
        }
Пример #11
0
    public static Atlas GetAtlas(Sprite s)
    {
        string path = UnityEditor.AssetDatabase.GetAssetPath(s);

        UnityEditor.TextureImporter ti = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(path);
        if (!string.IsNullOrEmpty(ti.spritePackingTag))
        {
            return(GetAtlas(ti.spritePackingTag));
        }
        return(null);
    }
Пример #12
0
 public override void AssetGraphOnPreprocessTexture()
 {
     UnityEditor.TextureImporter importer = assetImporter as UnityEditor.TextureImporter;
     importer.textureType         = UnityEditor.TextureImporterType.Advanced;
     importer.npotScale           = TextureImporterNPOTScale.None;
     importer.isReadable          = true;
     importer.alphaIsTransparency = true;
     importer.mipmapEnabled       = false;
     importer.wrapMode            = TextureWrapMode.Repeat;
     importer.filterMode          = FilterMode.Bilinear;
     importer.textureFormat       = TextureImporterFormat.ARGB16;
 }
Пример #13
0
		private static SpriteMetaData GetMetaDataInMultipleMode(string name, TextureImporter textureImporter)
		{
			SpriteMetaData[] spritesheet = textureImporter.spritesheet;
			for (int i = 0; i < spritesheet.Length; i++)
			{
				if (spritesheet[i].name.Equals(name))
				{
					return spritesheet[i];
				}
			}
			return default(SpriteMetaData);
		}
 private static SpriteMetaData GetMetaDataInSingleMode(string name, TextureImporter textureImporter)
 {
   SpriteMetaData spriteMetaData = new SpriteMetaData();
   spriteMetaData.border = textureImporter.spriteBorder;
   spriteMetaData.name = name;
   spriteMetaData.pivot = textureImporter.spritePivot;
   spriteMetaData.rect = new Rect(0.0f, 0.0f, 1f, 1f);
   TextureImporterSettings dest = new TextureImporterSettings();
   textureImporter.ReadTextureSettings(dest);
   spriteMetaData.alignment = dest.spriteAlignment;
   return spriteMetaData;
 }
Пример #15
0
		private static SpriteMetaData GetMetaDataInSingleMode(string name, TextureImporter textureImporter)
		{
			SpriteMetaData result = default(SpriteMetaData);
			result.border = textureImporter.spriteBorder;
			result.name = name;
			result.pivot = textureImporter.spritePivot;
			result.rect = new Rect(0f, 0f, 1f, 1f);
			TextureImporterSettings textureImporterSettings = new TextureImporterSettings();
			textureImporter.ReadTextureSettings(textureImporterSettings);
			result.alignment = textureImporterSettings.spriteAlignment;
			return result;
		}
Пример #16
0
 public BabylonTextureImporter(string path)
 {
     try
     {
         texturePath = path;
         textureImporter = AssetImporter.GetAtPath(texturePath) as TextureImporter;
         previousIsReadable = textureImporter.isReadable;
     }
     catch (Exception ex)
     {
         UnityEngine.Debug.LogException(ex);
     }
 }
Пример #17
0
        public static void SaveTex(Texture2D source, Texture2D newImage)
        {
            var    bytes       = newImage.EncodeToPNG();
            string source_path = UnityEditor.AssetDatabase.GetAssetPath(source);
            string path        = //System.IO.Path.GetFileNameWithoutExtension(path);
                                 UnityEditor.AssetDatabase.GenerateUniqueAssetPath(source_path);

            System.IO.File.WriteAllBytes(path, bytes);

            UnityEditor.AssetDatabase.Refresh();
            //---
            string copyFromPath = UnityEditor.AssetDatabase.GetAssetPath(source);

            UnityEditor.TextureImporter ti1 = UnityEditor.AssetImporter.GetAtPath(copyFromPath) as UnityEditor.TextureImporter;
            if (ti1.spriteImportMode == UnityEditor.SpriteImportMode.Multiple)
            {
                bool previousReadable = ti1.isReadable;
                ti1.isReadable = true;

                string copyToPath = path;
                UnityEditor.TextureImporter ti2 = UnityEditor.AssetImporter.GetAtPath(copyToPath) as UnityEditor.TextureImporter;
                ti2.isReadable = true;

                ti2.spriteImportMode    = UnityEditor.SpriteImportMode.Multiple;
                ti2.spritePixelsPerUnit = ti1.spritePixelsPerUnit;

                string previousName = System.IO.Path.GetFileNameWithoutExtension(source_path);
                string newName      = System.IO.Path.GetFileNameWithoutExtension(path);
                List <UnityEditor.SpriteMetaData> newData = new List <UnityEditor.SpriteMetaData>();
                for (int i = 0; i < ti1.spritesheet.Length; i++)
                {
                    UnityEditor.SpriteMetaData d = ti1.spritesheet[i];
                    d.name = d.name.Replace(previousName, newName);
                    newData.Add(d);
                }
                ti2.spritesheet = newData.ToArray();

                ti1.isReadable = previousReadable;
                ti2.isReadable = previousReadable;

                UnityEditor.AssetDatabase.ImportAsset(copyToPath, UnityEditor.ImportAssetOptions.ForceUpdate);
            }
            //---
            Texture2D newFile = AssetDatabase.LoadAssetAtPath <Texture2D>(path);

            EditorGUIUtility.PingObject(newFile);
            Debug.Log("[Color Swapper] Saved at " + path, newFile);
        }
Пример #18
0
    void ShowImage()
    {
        string path = "Assets/" + "Resources/screenshot" + pictureTime.ToString() + ".png";

        UnityEditor.AssetDatabase.Refresh();
        UnityEditor.AssetDatabase.ImportAsset(path);
        UnityEditor.TextureImporter importer = UnityEditor.AssetImporter.GetAtPath(path) as TextureImporter;
        importer.textureType = UnityEditor.TextureImporterType.Sprite;
        AssetDatabase.WriteImportSettingsIfDirty(path);
        UnityEditor.AssetDatabase.Refresh();
        Sprite         NewSprite = Resources.Load <Sprite>("screenshot" + pictureTime.ToString());
        SpriteRenderer sr        = Image.GetComponent <SpriteRenderer>();

        sr.sprite = NewSprite;
        Image.SetActive(true);
    }
    //-------------------------------------------------------------------------
    public bool SetTextureReadable(Texture2D texture, bool readable)
    {
#if UNITY_EDITOR
        string texturePath = UnityEditor.AssetDatabase.GetAssetPath(texture);
        if (!System.IO.File.Exists(texturePath))
        {
            SetLastError("Aborting Generation: Texture at path " + texturePath + " not found while changing import settings - did you delete it?");
            return(false);
        }

        UnityEditor.TextureImporter textureImporter = (UnityEditor.TextureImporter)UnityEditor.AssetImporter.GetAtPath(texturePath);
        textureImporter.isReadable = readable;
        UnityEditor.AssetDatabase.ImportAsset(texturePath);
#endif
        return(true);
    }
		public static bool IsSameTextureSetting (TextureImporter target, TextureImporter compareBase) {
			if (target.anisoLevel != compareBase.anisoLevel) return false;
			if (target.borderMipmap != compareBase.borderMipmap) return false;
			if (target.compressionQuality != compareBase.compressionQuality) return false;
			if (target.convertToNormalmap != compareBase.convertToNormalmap) return false;
			if (target.fadeout != compareBase.fadeout) return false;
			if (target.filterMode != compareBase.filterMode) return false;
			if (target.generateCubemap != compareBase.generateCubemap) return false;
			if (target.generateMipsInLinearSpace != compareBase.generateMipsInLinearSpace) return false;
			if (target.grayscaleToAlpha != compareBase.grayscaleToAlpha) return false;
			if (target.heightmapScale != compareBase.heightmapScale) return false;
			if (target.isReadable != compareBase.isReadable) return false;
			if (target.lightmap != compareBase.lightmap) return false;
			if (target.linearTexture != compareBase.linearTexture) return false;
			if (target.maxTextureSize != compareBase.maxTextureSize) return false;
			if (target.mipMapBias != compareBase.mipMapBias) return false;
			if (target.mipmapEnabled != compareBase.mipmapEnabled) return false;
			if (target.mipmapFadeDistanceEnd != compareBase.mipmapFadeDistanceEnd) return false;
			if (target.mipmapFadeDistanceStart != compareBase.mipmapFadeDistanceStart) return false;
			if (target.mipmapFilter != compareBase.mipmapFilter) return false;
			if (target.normalmap != compareBase.normalmap) return false;
			if (target.normalmapFilter != compareBase.normalmapFilter) return false;
			if (target.npotScale != compareBase.npotScale) return false;
			// if (target.qualifiesForSpritePacking != compareBase.qualifiesForSpritePacking) return false;
			if (target.spriteBorder != compareBase.spriteBorder) return false;
			if (target.spriteImportMode != compareBase.spriteImportMode) return false;
			if (target.spritePackingTag != compareBase.spritePackingTag) return false;
			if (target.spritePivot != compareBase.spritePivot) return false;
			if (target.spritePixelsPerUnit != compareBase.spritePixelsPerUnit) return false;

			// spritesheet
			{
				if (target.spritesheet.Length != compareBase.spritesheet.Length) return false;
				for (int i = 0; i < target.spritesheet.Length; i++) {
					if (target.spritesheet[i].alignment != compareBase.spritesheet[i].alignment) return false;
					if (target.spritesheet[i].border != compareBase.spritesheet[i].border) return false;
					if (target.spritesheet[i].name != compareBase.spritesheet[i].name) return false;
					if (target.spritesheet[i].pivot != compareBase.spritesheet[i].pivot) return false;
					if (target.spritesheet[i].rect != compareBase.spritesheet[i].rect) return false;
				}
			}

			if (target.textureFormat != compareBase.textureFormat) return false;
			if (target.textureType != compareBase.textureType) return false;
			if (target.wrapMode != compareBase.wrapMode) return false;
			return true;
		}
    /// <summary>
    /// 把纹理放到编辑器中去
    /// </summary>
    /// <param name="ps"></param>
    private static Texture2D AssembleTexture(ParticleSystem ps, Dictionary <int, object> resource)
    {
        Texture2D tex2D = null;
        Texture3D tex   = resource[ps.TexId] as Texture3D;

        if (tex.IsATF)
        {
        }
        else
        {
            //实例化一个Texture2D,宽和高设置可以是任意的,因为当使用LoadImage方法会对Texture2D的宽和高会做相应的调整
            //Texture2D tex2D = new Texture2D(1,1);
            //tex2D.LoadImage(tex.Data);
            var fileName = string.Empty;
            //if (!File.Exists(SceneFileCopy.GetAbsoluteTextureDir() + tex.Name))
            {
                fileName = tex.Name;
                ps.UnityResourceParam.Texture2DPath = SceneFileCopy.GetRelativeTextureDir(ps.RootFileName) + fileName;
            }
            //else
            //{
            //    fileName = tex.Name.Substring(0, UnityEngine.Mathf.Max(0, tex.Name.Length - 4)) + "_" + Guid.NewGuid().ToString() + tex.Name.Substring(tex.Name.Length - 4, 4);
            //    ps.UnityResourceParam.Texture2DPath = SceneFileCopy.GetRelativeTextureDir() + fileName;
            //}
            ps.UnityResourceParam.Texture2DPath = SceneFileCopy.GetRelativeTextureDir(ps.RootFileName) + fileName;
            SaveFile(SceneFileCopy.GetAbsoluteTextureDir(ps.RootFileName) + fileName, tex.Data);
            tex2D = UnityEditor.AssetDatabase.LoadAssetAtPath(ps.UnityResourceParam.Texture2DPath, typeof(Texture2D)) as Texture2D;
            UnityEditor.TextureImporter         textureImporter = UnityEditor.AssetImporter.GetAtPath(ps.UnityResourceParam.Texture2DPath) as UnityEditor.TextureImporter;
            UnityEditor.TextureImporterSettings settings        = new UnityEditor.TextureImporterSettings();
            textureImporter.ReadTextureSettings(settings);
            settings.ApplyTextureType(UnityEditor.TextureImporterType.Default);
            textureImporter.SetTextureSettings(settings);
            textureImporter.textureType = UnityEditor.TextureImporterType.Default;
            //使用透明度
            textureImporter.alphaIsTransparency = true;
            textureImporter.isReadable          = true;
            textureImporter.filterMode          = (UnityEngine.FilterMode)tex.FilterMode;
            textureImporter.wrapMode            = (UnityEngine.TextureWrapMode)tex.WrapMode;
            textureImporter.mipmapEnabled       = tex.MipMode > 0;
            UnityEditor.AssetDatabase.ImportAsset(ps.UnityResourceParam.Texture2DPath);
        }
        UnityEditor.AssetDatabase.Refresh();
        return(tex2D);
    }
Пример #22
0
    private void OnPostprocessTexture(Texture2D texture)
    {
        Debug.Log("OnPostprocessTexture");

        if (assetPath.Contains("/Tile/AutoTile/"))
        {
            UnityEditor.TextureImporter _mI = (UnityEditor.TextureImporter)assetImporter;
            _mI.filterMode          = FilterMode.Point;
            _mI.mipmapEnabled       = false;
            _mI.textureType         = TextureImporterType.Sprite;
            _mI.spriteImportMode    = SpriteImportMode.Multiple;
            _mI.spritePixelsPerUnit = 32;
            _mI.spritePackingTag    = "map";
            _mI.textureFormat       = TextureImporterFormat.RGB24;
            string[] split = assetPath.Split('/');
            string   name  = split[split.Length - 1];
            name            = name.Replace(".png", "");
            _mI.spritesheet = CreateSpriteMetaDataArray(name, texture, texture.width / 16, texture.height / 16);
        }
    }
Пример #23
0
        private static void postProcessTextureDelayed(string _TexturePath, TextureImporter _Importer)
        {
            var texture = AssetDatabase.LoadAssetAtPath(_TexturePath, typeof(Texture2D)) as Texture2D;

            m_Resources.RemoveAll(resource => resource == null || !resource.isValid);

            foreach (var resource in m_Resources)
            {
                if (resource.currentDataPath == Path.GetDirectoryName(_TexturePath) + "/")
                {
                    var data = resource.missingData.Find(_data => _data.name == texture.name);
                    if (data != null)
                    {
                        if (hasCorrectImportSettings(_Importer, resource))
                        {
                            data.set(texture, getSharedMaterial(texture));
                            m_ImportList.Remove(_TexturePath);
                            EditorUtility.SetDirty(resource);
                        }
                        else
                        {
                            changeTextureImportSettings(_Importer, resource);
                            AssetDatabase.ImportAsset(_Importer.assetPath, ImportAssetOptions.ForceUpdate);
                        }
                    }
                }
            }
        }
Пример #24
0
        public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
        {
            Texture2D textured;

            if (!ShaderUtil.hardwareSupportsRectRenderTexture)
            {
                return(null);
            }
            Texture target = this.target as Texture;

            if (this.IsCubemap())
            {
                return(this.m_CubemapPreview.RenderStaticPreview(target, width, height));
            }
            TextureImporter atPath = AssetImporter.GetAtPath(assetPath) as TextureImporter;

            if ((atPath != null) && (atPath.spriteImportMode == SpriteImportMode.Polygon))
            {
                Sprite sprite = subAssets[0] as Sprite;
                if (sprite != null)
                {
                    return(SpriteInspector.BuildPreviewTexture(width, height, sprite, null, true));
                }
            }
            PreviewHelpers.AdjustWidthAndHeightForStaticPreview(target.width, target.height, ref width, ref height);
            RenderTexture active                    = RenderTexture.active;
            Rect          rawViewportRect           = ShaderUtil.rawViewportRect;
            bool          flag                      = !TextureUtil.GetLinearSampled(target);
            RenderTexture dest                      = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, !flag ? RenderTextureReadWrite.Linear : RenderTextureReadWrite.sRGB);
            Material      materialForSpecialTexture = EditorGUI.GetMaterialForSpecialTexture(target);

            GL.sRGBWrite = QualitySettings.activeColorSpace == ColorSpace.Linear;
            if (materialForSpecialTexture != null)
            {
                if (Unsupported.IsDeveloperBuild())
                {
                    materialForSpecialTexture = new Material(materialForSpecialTexture);
                }
                Graphics.Blit(target, dest, materialForSpecialTexture);
            }
            else
            {
                Graphics.Blit(target, dest);
            }
            GL.sRGBWrite         = false;
            RenderTexture.active = dest;
            Texture2D textured2 = this.target as Texture2D;

            if ((textured2 != null) && textured2.alphaIsTransparency)
            {
                textured = new Texture2D(width, height, TextureFormat.ARGB32, false);
            }
            else
            {
                textured = new Texture2D(width, height, TextureFormat.RGB24, false);
            }
            textured.ReadPixels(new Rect(0f, 0f, (float)width, (float)height), 0, 0);
            textured.Apply();
            RenderTexture.ReleaseTemporary(dest);
            EditorGUIUtility.SetRenderTextureNoViewport(active);
            ShaderUtil.rawViewportRect = rawViewportRect;
            if ((materialForSpecialTexture != null) && Unsupported.IsDeveloperBuild())
            {
                Object.DestroyImmediate(materialForSpecialTexture);
            }
            return(textured);
        }
        /**
         * Changes the "Max Size" of a texture, acording to its original size and a factor defined by TextureResizingFactor.
         * It only changes the meta file of the texture.
         */
        static void ResizeTexture(Texture2D texture, TextureImporter textureImporter)
        {
            TextureImporterSettings textureImporterSettings = new TextureImporterSettings();
            textureImporter.ReadTextureSettings(textureImporterSettings);
           
            //grabbing the max texture dimension for use in size calculation
            float size = Mathf.Max(texture.width, texture.height);

            string s = "Memory Optimizer: Original size = " + size + "; Original max size = " + textureImporterSettings.maxTextureSize;

            // Getting the smallest texture size between original texture size, to be resized  by TextureResizingFactor, and maxTextureSize set in asset importer settings:
            size = Mathf.Min(Mathf.Pow(2f, Mathf.Floor(Mathf.Log(size, 2f)) - TextureResizingFactor), textureImporterSettings.maxTextureSize);

            Debug.Log(s + "; New max size = " + size);

            // we won't make any changes if the calculate size is lesser than the minimum on Unity dropdown box (32):
            if (size >= 32)
            {
                textureImporterSettings.maxTextureSize = (int)size;
                textureImporter.SetTextureSettings(textureImporterSettings);
            }
        }
Пример #26
0
 public void InvalidatePropertiesCache()
 {
     if (this.m_RectsCache != null)
     {
         this.m_RectsCache.ClearAll();
         UnityEngine.Object.DestroyImmediate(this.m_RectsCache);
     }
     if (base.m_Texture != null)
     {
         UnityEngine.Object.DestroyImmediate(base.m_Texture);
     }
     this.m_OriginalTexture = null;
     this.m_TextureImporter = null;
     this.m_TextureImporterSO = null;
     this.m_TextureImporterSprites = null;
     s_AlphaPixelCache = null;
 }
Пример #27
0
		public static void GetWidthAndHeight(TextureImporter textureImporter, ref int width, ref int height)
		{
			MethodInfo methodInfo = typeof(TextureImporter).GetMethod("GetWidthAndHeight", BindingFlags.Instance | BindingFlags.NonPublic);
			
			if(methodInfo != null)
			{
				object[] parameters = new object[] { null, null };
				methodInfo.Invoke(textureImporter,parameters);
				width = (int)parameters[0];
				height = (int)parameters[1];
			}
		}
    protected override void FillTexture(Texture2D texture)
    {
        if (Data == null || Source == null) return;
        bool isReadable = false;
#if UNITY_EDITOR
        string path = UnityEditor.AssetDatabase.GetAssetPath(Source);
        UnityEditor.TextureImporter ti = (UnityEditor.TextureImporter)UnityEditor.TextureImporter.GetAtPath(path);
        if (ti != null)
            isReadable = ti.isReadable;
#endif
        if (!isReadable) return;

        Data.BeginInputInit();
        _in0 = Data.CteateInput(ValueType.Color, "In 0");
        _in1 = Data.CteateInput(ValueType.Color, "In 1");
        _in2 = Data.CteateInput(ValueType.Color, "In 2");
        _in3 = Data.CteateInput(ValueType.Color, "In 3");
        _original = Data.CteateInput(ValueType.Color, "Original");

        _pos = Data.CteateInput(ValueType.Vector2, "Position");
        _mipPos = Data.CteateInput(ValueType.Float, "Mip Position");
        _mipCount = Data.CteateInput(ValueType.Float, "Mip Count");

        _out = Data.CteateOutput(ValueType.Color, "Color");
        Data.EndInputInit();

        if (Input == null) Input = new NodeDataInput();
        Input.InitializeFrom(Data);
        Input.SetTo(Data);


        int mipmapCount = 1 + (int)Mathf.Log(Mathf.Max(Source.width, Source.height), 2);
        Color[] lastColors = null;

        Data.SetFloat(_mipCount, mipmapCount);
        for (int mI = 0; mI < mipmapCount; mI++)
        {
            int mipWidth = Mathf.Max(texture.width >> mI, 1);
            int mipHeight = Mathf.Max(texture.height >> mI, 1);
            int lastMipWidth = Mathf.Max(texture.width >> (mI - 1), 1);
            int lastMipHeight = Mathf.Max(texture.height >> (mI - 1), 1);
            int mipDelta = lastMipWidth > mipWidth ? 2 : 1;
            int mipDeltaY = mipDelta * (lastMipHeight > mipHeight ? 2 : 1);

            Data.SetFloat(_mipPos, mI / (float)mipmapCount);

            Color[] colors = lastColors == null || Source.mipmapCount == mipmapCount ? Source.GetPixels(mI) : new Color[mipWidth * mipHeight];

            if (lastColors != null)
            {
                for (int i = 0; i < colors.Length; i++)
                {
                    int y = i / mipWidth;
                    int x = i - y * mipWidth;
                    int i2 = x * mipDelta + y * mipWidth * mipDeltaY;
                    if (lastColors.Length < 4) lastMipWidth = 0;


                    Data.SetVector2(_pos, new Vector2(x / (float)mipWidth, y / (float)mipHeight));
                    Data.SetColor(_in0, lastColors[i2]);
                    Data.SetColor(_in1, lastColors[i2 + 1]);
                    Data.SetColor(_in2, lastColors[i2 + lastMipWidth]);
                    Data.SetColor(_in3, lastColors[i2 + lastMipWidth + 1]);
                    Data.SetColor(_original, colors[i]);

                    Data.Process();
                    colors[i] = Data.GetColor(_out);
                }


            }

            texture.SetPixels(colors, mI);
            lastColors = colors;
        }
        texture.Apply(false);
    }
 private void SetLUTImportSettings(TextureImporter importer)
 {
     importer.textureType = TextureImporterType.Advanced;
     importer.anisoLevel = 0;
     importer.mipmapEnabled = false;
     importer.linearTexture = true;
     importer.textureFormat = TextureImporterFormat.RGB24;
     importer.SaveAndReimport();
 }
Пример #30
0
        public static void preProcessTexture(TextureImporter _Importer)
        {
            var textureName = Path.GetFileNameWithoutExtension(_Importer.assetPath);

            m_Resources.RemoveAll(resource => resource == null || !resource.isValid);

            foreach (var resource in m_Resources)
            {
                if (resource.currentDataPath == Path.GetDirectoryName(_Importer.assetPath) + "/")
                {
                    var data = resource.missingData.Find(_data => _data.name == textureName);
                    if (data != null)
                    {
                        if (!hasCorrectImportSettings(_Importer, resource))
                        {
                            changeTextureImportSettings(_Importer, resource);
                        }
                    }
                }
            }
        }
Пример #31
0
        public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
        {
            if (!ShaderUtil.hardwareSupportsRectRenderTexture)
            {
                return(null);
            }

            Texture texture = target as Texture;

            if (IsCubemap())
            {
                return(m_CubemapPreview.RenderStaticPreview(texture, width, height));
            }

            TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;

            if (textureImporter != null && textureImporter.textureType == TextureImporterType.Sprite && textureImporter.spriteImportMode == SpriteImportMode.Polygon)
            {
                // If the texture importer is a Sprite of primitive, use the sprite inspector for generating preview/icon.
                if (subAssets.Length > 0)
                {
                    Sprite sprite = subAssets[0] as Sprite;
                    if (sprite)
                    {
                        return(SpriteInspector.BuildPreviewTexture(width, height, sprite, null, true));
                    }
                }
                else
                {
                    return(null);
                }
            }

            PreviewHelpers.AdjustWidthAndHeightForStaticPreview(texture.width, texture.height, ref width, ref height);

            RenderTexture savedRT       = RenderTexture.active;
            Rect          savedViewport = ShaderUtil.rawViewportRect;

            RenderTexture tmp = RenderTexture.GetTemporary(
                width, height,
                0,
                SystemInfo.GetGraphicsFormat(DefaultFormat.LDR));
            Material mat = EditorGUI.GetMaterialForSpecialTexture(texture);

            if (mat != null)
            {
                Graphics.Blit(texture, tmp, mat);
            }
            else
            {
                Graphics.Blit(texture, tmp);
            }

            RenderTexture.active = tmp;
            Texture2D copy;
            Texture2D tex2d = target as Texture2D;

            if (tex2d != null && tex2d.alphaIsTransparency)
            {
                copy = new Texture2D(width, height, TextureFormat.RGBA32, false);
            }
            else
            {
                copy = new Texture2D(width, height, TextureFormat.RGB24, false);
            }
            copy.ReadPixels(new Rect(0, 0, width, height), 0, 0);
            copy.Apply();
            RenderTexture.ReleaseTemporary(tmp);

            EditorGUIUtility.SetRenderTextureNoViewport(savedRT);
            ShaderUtil.rawViewportRect = savedViewport;

            return(copy);
        }
 public void RefreshPropertiesCache()
 {
   this.m_OriginalTexture = this.GetSelectedTexture2D();
   if ((UnityEngine.Object) this.m_OriginalTexture == (UnityEngine.Object) null)
     return;
   this.m_TextureImporter = AssetImporter.GetAtPath(this.m_SelectedAssetPath) as TextureImporter;
   if ((UnityEngine.Object) this.m_TextureImporter == (UnityEngine.Object) null)
     return;
   this.m_TextureImporterSO = new SerializedObject((UnityEngine.Object) this.m_TextureImporter);
   this.m_TextureImporterSprites = this.m_TextureImporterSO.FindProperty("m_SpriteSheet.m_Sprites");
   this.m_SpriteSheetOutline = this.m_TextureImporterSO.FindProperty("m_SpriteSheet.m_Outline");
   if ((UnityEngine.Object) this.m_RectsCache != (UnityEngine.Object) null)
     this.selected = this.m_TextureImporterSprites.arraySize <= 0 ? (SpriteRect) null : this.m_RectsCache.RectAt(0);
   int width = 0;
   int height = 0;
   this.m_TextureImporter.GetWidthAndHeight(ref width, ref height);
   this.m_Texture = this.CreateTemporaryDuplicate(AssetDatabase.LoadMainAssetAtPath(this.m_TextureImporter.assetPath) as Texture2D, width, height);
   if ((UnityEngine.Object) this.m_Texture == (UnityEngine.Object) null)
     return;
   this.m_Texture.filterMode = UnityEngine.FilterMode.Point;
 }
Пример #33
0
    /// <summary>
    /// 设置图片 样式
    /// </summary>
    /// <param name="iOSFroamt"></param>
    /// <param name="AndroidFroamt"></param>
    static void SettingTexture(TextureImporterFormat iOSFroamt, TextureImporterFormat?AndroidFroamt = null)
    {
        if (null == AndroidFroamt)
        {
            AndroidFroamt = iOSFroamt;
        }
        List <string> fileList = new List <string>();

        /// 遍历 目录 操作
        if (null != Selection.objects)
        {
            for (int index = 0; index < Selection.objects.Length; index++)
            {
                if (null != Selection.objects[index])
                {
                    string path = string.Format("{0}/../{1}", Application.dataPath, AssetDatabase.GetAssetPath(Selection.objects[index]));
                    if (System.IO.Directory.Exists(path))
                    {
                        EditorSearchFile.SearchPath(path, fileList, "");
                    }
                    else
                    {
                        fileList.Add(path);
                    }
                }
            }
        }
        for (int index = 0; index < fileList.Count; index++)
        {
            string path = fileList[index];
            while (path.LastIndexOf("Assets/", System.StringComparison.Ordinal) != 0 && path.LastIndexOf("Assets/", System.StringComparison.Ordinal) != -1)
            {
                path = path.Substring(path.LastIndexOf("Assets/", System.StringComparison.Ordinal));
            }
            UnityEditor.TextureImporter importer = UnityEditor.TextureImporter.GetAtPath(path) as UnityEditor.TextureImporter;
            if (null == importer)
            {
                continue;
            }
            importer.mipmapEnabled = false;
            /// 读取
            TextureImporterPlatformSettings iOS     = importer.GetPlatformTextureSettings("iPhone");
            TextureImporterPlatformSettings Android = importer.GetPlatformTextureSettings("Android");
            /// 重写 设成 true
            Android.overridden           = iOS.overridden = true;
            importer.textureType         = TextureImporterType.Sprite;
            importer.alphaSource         = TextureImporterAlphaSource.FromInput;
            importer.alphaIsTransparency = true;
            importer.npotScale           = TextureImporterNPOTScale.None;
            /// 类型设置
            Android.format = (TextureImporterFormat)AndroidFroamt;
            iOS.format     = iOSFroamt;
            /// 赋值
            importer.SetPlatformTextureSettings(iOS);
            importer.SetPlatformTextureSettings(Android);
            /// LOG
            Debug.Log(string.Format("Setting Texture : [ Android = {1}, iOS = {2} ]{0}", path, AndroidFroamt, iOSFroamt));
            /// 保存
            importer.SaveAndReimport();
        }
    }
Пример #34
0
        public override string GetInfoString()
        {
            // TextureInspector code is reused for RenderTexture and Cubemap inspectors.
            // Make sure we can handle the situation where target is just a Texture and
            // not a Texture2D.
            Texture         t  = target as Texture;
            Texture2D       t2 = target as Texture2D;
            TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(t)) as TextureImporter;
            string          info            = t.width.ToString() + "x" + t.height.ToString();

            bool           showSize              = true;
            bool           isPackedSprite        = textureImporter && textureImporter.qualifiesForSpritePacking;
            bool           isNormalmap           = IsNormalMap(t);
            bool           stillNeedsCompression = TextureUtil.DoesTextureStillNeedToBeCompressed(AssetDatabase.GetAssetPath(t));
            bool           isNPOT = t2 != null && TextureUtil.IsNonPowerOfTwo(t2);
            GraphicsFormat format = t.graphicsFormat;

            showSize = !stillNeedsCompression;
            if (isNPOT)
            {
                info += " (NPOT)";
            }
            if (stillNeedsCompression)
            {
                info += " (Not yet compressed)";
            }
            else
            {
                if (isNormalmap)
                {
                    switch (format)
                    {
                    case GraphicsFormat.RGBA_DXT5_SRGB:
                    case GraphicsFormat.RGBA_DXT5_UNorm:
                        info += "  DXTnm";
                        break;

                    case GraphicsFormat.R8G8B8A8_SRGB:
                    case GraphicsFormat.R8G8B8A8_UNorm:
                    case GraphicsFormat.B8G8R8A8_SRGB:
                    case GraphicsFormat.B8G8R8A8_UNorm:
                        info += "  Nm 32 bit";
                        break;

                    case GraphicsFormat.R4G4B4A4_UNormPack16:
                    case GraphicsFormat.B4G4R4A4_UNormPack16:
                        info += "  Nm 16 bit";
                        break;

                    default:
                        info += "  " + GraphicsFormatUtility.GetFormatString(format);
                        break;
                    }
                }
                else if (isPackedSprite)
                {
                    TextureFormat desiredFormat;
                    ColorSpace    dummyColorSpace;
                    int           dummyComressionQuality;
                    textureImporter.ReadTextureImportInstructions(EditorUserBuildSettings.activeBuildTarget, out desiredFormat, out dummyColorSpace, out dummyComressionQuality);

                    info += "\n " + GraphicsFormatUtility.GetFormatString(format) + "(Original) " + TextureUtil.GetTextureFormatString(desiredFormat) + "(Atlas)";
                }
                else
                {
                    info += "  " + GraphicsFormatUtility.GetFormatString(format);
                }
            }

            if (showSize)
            {
                info += "\n" + EditorUtility.FormatBytes(TextureUtil.GetStorageMemorySizeLong(t));
            }

            if (TextureUtil.GetUsageMode(t) == TextureUsageMode.AlwaysPadded)
            {
                var glWidth  = TextureUtil.GetGPUWidth(t);
                var glHeight = TextureUtil.GetGPUHeight(t);
                if (t.width != glWidth || t.height != glHeight)
                {
                    info += UnityString.Format("\nPadded to {0}x{1}", glWidth, glHeight);
                }
            }
            else if (TextureUtil.GetUsageMode(t) == TextureUsageMode.BakedLightmapRGBM ||
                     TextureUtil.GetUsageMode(t) == TextureUsageMode.RealtimeLightmapRGBM ||
                     TextureUtil.GetUsageMode(t) == TextureUsageMode.RGBMEncoded)
            {
                info += "\nRGBM encoded";
            }
            else if (TextureUtil.GetUsageMode(t) == TextureUsageMode.DoubleLDR ||
                     TextureUtil.GetUsageMode(t) == TextureUsageMode.BakedLightmapDoubleLDR)
            {
                info += "\ndLDR encoded";
            }

            return(info);
        }
 private bool GetOverridden(TextureImporter importer)
 {
   if (!this.m_OverriddenIsDifferent)
     return this.m_Overridden;
   int maxTextureSize;
   TextureImporterFormat textureFormat;
   return importer.GetPlatformTextureSettings(this.name, out maxTextureSize, out textureFormat);
 }
 public TextureImporterSettings GetSettings(TextureImporter importer)
 {
   TextureImporterSettings importerSettings = new TextureImporterSettings();
   importer.ReadTextureSettings(importerSettings);
   this.m_Inspector.GetSerializedPropertySettings(importerSettings);
   return importerSettings;
 }
 public bool SupportsFormat(TextureImporterFormat format, TextureImporter importer)
 {
   TextureImporterSettings settings = this.GetSettings(importer);
   BuildTarget target = this.m_Target;
   int[] numArray;
   switch (target)
   {
     case BuildTarget.BlackBerry:
       numArray = TextureImporterInspector.kTextureFormatsValueBB10;
       break;
     case BuildTarget.Tizen:
       numArray = TextureImporterInspector.kTextureFormatsValueTizen;
       break;
     case BuildTarget.SamsungTV:
       numArray = TextureImporterInspector.kTextureFormatsValueSTV;
       break;
     case BuildTarget.WiiU:
       numArray = TextureImporterInspector.kTextureFormatsValueWiiU;
       break;
     case BuildTarget.tvOS:
       numArray = TextureImporterInspector.kTextureFormatsValuetvOS;
       break;
     default:
       switch (target - 9)
       {
         case ~BuildTarget.iPhone:
           numArray = TextureImporterInspector.kTextureFormatsValueiPhone;
           break;
         case BuildTarget.StandaloneOSXIntel:
           numArray = TextureImporterInspector.kTextureFormatsValueAndroid;
           break;
         case BuildTarget.StandaloneWindows:
           numArray = !settings.normalMap ? TextureImporterInspector.kTextureFormatsValueGLESEmu : TextureImporterInspector.kNormalFormatsValueWeb;
           break;
         default:
           numArray = !settings.normalMap ? TextureImporterInspector.kTextureFormatsValueWeb : TextureImporterInspector.kNormalFormatsValueWeb;
           break;
       }
   }
   return numArray.Contains((object) format);
 }
 public void InvalidatePropertiesCache()
 {
   if ((bool) ((UnityEngine.Object) this.m_RectsCache))
   {
     this.m_RectsCache.ClearAll();
     UnityEngine.Object.DestroyImmediate((UnityEngine.Object) this.m_RectsCache);
   }
   if ((bool) ((UnityEngine.Object) this.m_Texture))
     UnityEngine.Object.DestroyImmediate((UnityEngine.Object) this.m_Texture);
   this.m_OriginalTexture = (Texture2D) null;
   this.m_TextureImporter = (TextureImporter) null;
   this.m_TextureImporterSO = (SerializedObject) null;
   this.m_TextureImporterSprites = (SerializedProperty) null;
   SpriteEditorWindow.s_AlphaPixelCache = (bool[]) null;
 }
Пример #39
0
 bool SupportedTextureFormat(TextureImporter importer) {
     var format = importer.textureFormat;
     return format == TextureImporterFormat.ARGB32
         || format == TextureImporterFormat.RGBA32
         || format == TextureImporterFormat.RGB24
         || format == TextureImporterFormat.Alpha8
         || format == TextureImporterFormat.DXT1
         || format == TextureImporterFormat.DXT5;
 }
Пример #40
0
        void SetTextureSetting( TextureImporter textureImporter,bool readable )
        {
            TextureImporterSettings settings = new TextureImporterSettings();
            textureImporter.ReadTextureSettings( settings );

            settings.readable = readable;
            settings.textureFormat = TextureImporterFormat.ARGB32;
            settings.npotScale = TextureImporterNPOTScale.None;

            textureImporter.SetTextureSettings(settings);
        }
Пример #41
0
 private static SpriteMetaData GetMetaDataInSingleMode(string name, TextureImporter textureImporter)
 {
     SpriteMetaData data = new SpriteMetaData {
         border = textureImporter.spriteBorder,
         name = name,
         pivot = textureImporter.spritePivot,
         rect = new Rect(0f, 0f, 1f, 1f)
     };
     TextureImporterSettings dest = new TextureImporterSettings();
     textureImporter.ReadTextureSettings(dest);
     data.alignment = dest.spriteAlignment;
     return data;
 }
        /*
            Psuade Unity's import handlers.
        */
        // public void OnPostprocessGameObjectWithUserProperties (GameObject g, string[] propNames, object[] values) {}
        public void ForceOnPreprocessTexture(TextureImporter importer)
        {
            if (importerSourceObj == null) return;
            var importerSource = importerSourceObj as TextureImporter;
            if (importerSource == null) return;

            importer.anisoLevel = importerSource.anisoLevel;
            importer.borderMipmap = importerSource.borderMipmap;
            importer.compressionQuality = importerSource.compressionQuality;
            importer.convertToNormalmap = importerSource.convertToNormalmap;
            importer.fadeout = importerSource.fadeout;
            importer.filterMode = importerSource.filterMode;
            importer.generateCubemap = importerSource.generateCubemap;
            importer.generateMipsInLinearSpace = importerSource.generateMipsInLinearSpace;
            importer.grayscaleToAlpha = importerSource.grayscaleToAlpha;
            importer.heightmapScale = importerSource.heightmapScale;
            importer.isReadable = importerSource.isReadable;
            importer.lightmap = importerSource.lightmap;
            importer.linearTexture = importerSource.linearTexture;
            importer.maxTextureSize = importerSource.maxTextureSize;
            importer.mipMapBias = importerSource.mipMapBias;
            importer.mipmapEnabled = importerSource.mipmapEnabled;
            importer.mipmapFadeDistanceEnd = importerSource.mipmapFadeDistanceEnd;
            importer.mipmapFadeDistanceStart = importerSource.mipmapFadeDistanceStart;
            importer.mipmapFilter = importerSource.mipmapFilter;
            importer.normalmap = importerSource.normalmap;
            importer.normalmapFilter = importerSource.normalmapFilter;
            importer.npotScale = importerSource.npotScale;
            // importer.qualifiesForSpritePacking = importerSource.qualifiesForSpritePacking;
            importer.spriteBorder = importerSource.spriteBorder;
            importer.spriteImportMode = importerSource.spriteImportMode;
            importer.spritePackingTag = importerSource.spritePackingTag;
            importer.spritePivot = importerSource.spritePivot;
            importer.spritePixelsPerUnit = importerSource.spritePixelsPerUnit;
            importer.spritesheet = importerSource.spritesheet;
            importer.textureFormat = importerSource.textureFormat;
            importer.textureType = importerSource.textureType;
            importer.wrapMode = importerSource.wrapMode;
        }
Пример #43
0
        private static void changeTextureImportSettings(TextureImporter _Importer, GAFTexturesResource _Resource)
        {
            if (!m_ImportList.Contains(_Importer.assetPath))
            {
                _Importer.textureType			= TextureImporterType.Advanced;
                _Importer.npotScale				= TextureImporterNPOTScale.None;
                _Importer.maxTextureSize		= 4096;
                _Importer.alphaIsTransparency	= true;
                _Importer.mipmapEnabled			= false;

                TextureImporterSettings st = new TextureImporterSettings();
                _Importer.ReadTextureSettings(st);
                st.wrapMode = TextureWrapMode.Clamp;
                _Importer.SetTextureSettings(st);

                m_ImportList.Add(_Importer.assetPath);
            }
        }
Пример #44
0
            public TextureReadable(Texture texture)
            {
                #if UNITY_EDITOR
                if (!Application.isPlaying) {
                assetPath = AssetDatabase.GetAssetPath(texture);
                textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
                isReadable = textureImporter.isReadable;

                if (!isReadable) {
                    textureImporter.isReadable = true;
                    AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
                }
                } else {
                DisplayError(texture);
                }
                #else
                DisplayError(texture);
                #endif
            }
Пример #45
0
        public override string GetInfoString()
        {
            Texture         target = this.target as Texture;
            Texture2D       t      = this.target as Texture2D;
            TextureImporter atPath = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(target)) as TextureImporter;
            string          str    = target.width.ToString() + "x" + target.height.ToString();

            if (QualitySettings.desiredColorSpace == ColorSpace.Linear)
            {
                str = str + " " + TextureUtil.GetTextureColorSpaceString(target);
            }
            bool          flag          = true;
            bool          flag2         = (atPath != null) && atPath.qualifiesForSpritePacking;
            bool          flag3         = IsNormalMap(target);
            bool          flag4         = TextureUtil.DoesTextureStillNeedToBeCompressed(AssetDatabase.GetAssetPath(target));
            bool          flag5         = (t != null) && TextureUtil.IsNonPowerOfTwo(t);
            TextureFormat textureFormat = TextureUtil.GetTextureFormat(target);

            flag = !flag4;
            if (flag5)
            {
                str = str + " (NPOT)";
            }
            if (flag4)
            {
                str = str + " (Not yet compressed)";
            }
            else if (!flag3)
            {
                if (flag2)
                {
                    TextureFormat format2;
                    ColorSpace    space;
                    int           num;
                    atPath.ReadTextureImportInstructions(EditorUserBuildSettings.activeBuildTarget, out format2, out space, out num);
                    string   str2       = str;
                    string[] textArray1 = new string[] { str2, "\n ", TextureUtil.GetTextureFormatString(textureFormat), "(Original) ", TextureUtil.GetTextureFormatString(format2), "(Atlas)" };
                    str = string.Concat(textArray1);
                }
                else
                {
                    str = str + "  " + TextureUtil.GetTextureFormatString(textureFormat);
                }
            }
            else
            {
                TextureFormat format3 = textureFormat;
                switch (format3)
                {
                case TextureFormat.ARGB4444:
                    str = str + "  Nm 16 bit";
                    goto Label_01E0;

                case TextureFormat.ARGB32:
                    str = str + "  Nm 32 bit";
                    goto Label_01E0;
                }
                if (format3 == TextureFormat.DXT5)
                {
                    str = str + "  DXTnm";
                }
                else
                {
                    str = str + "  " + TextureUtil.GetTextureFormatString(textureFormat);
                }
            }
Label_01E0:
            if (flag)
            {
                str = str + "\n" + EditorUtility.FormatBytes(TextureUtil.GetStorageMemorySize(target));
            }
            if (TextureUtil.GetUsageMode(target) != TextureUsageMode.AlwaysPadded)
            {
                return(str);
            }
            int gLWidth  = TextureUtil.GetGLWidth(target);
            int gLHeight = TextureUtil.GetGLHeight(target);

            if ((target.width == gLWidth) && (target.height == gLHeight))
            {
                return(str);
            }
            return(str + string.Format("\nPadded to {0}x{1}", gLWidth, gLHeight));
        }
Пример #46
0
    void Init()
    {
        // check if already initialized
        if (materialInsts != null)
        {
            return;
        }

        if (spriteDefinitions == null)
        {
            spriteDefinitions = new tk2dSpriteDefinition[0];
        }
        if (materials == null)
        {
            materials = new Material[0];
        }

        materialInsts = new Material[materials.Length];
        if (needMaterialInstance)
        {
            if (tk2dSystem.OverrideBuildMaterial)
            {
                // This is a hack to work around a bug in Unity 4.x
                // Scene serialization will serialize the actively bound texture
                // but not the material during the build, only when [ExecuteInEditMode]
                // is on, eg. on sprites.
                for (int i = 0; i < materials.Length; ++i)
                {
                    materialInsts[i] = new Material(Shader.Find("tk2d/BlendVertexColor"));
        #if UNITY_EDITOR
                    materialInsts[i].hideFlags = HideFlags.DontSave;
        #endif
                }
            }
            else
            {
                bool assignTextureInst = false;
                if (pngTextures.Length > 0)
                {
                    assignTextureInst = true;
                    textureInsts      = new Texture2D[pngTextures.Length];
                    for (int i = 0; i < pngTextures.Length; ++i)
                    {
                        Texture2D tex = new Texture2D(4, 4, TextureFormat.ARGB32, textureMipMaps);
        #if UNITY_EDITOR
                        tex.name      = string.Format("{0}PNG_{1}_{2}", internalResourcePrefix, name, i);
                        tex.hideFlags = HideFlags.DontSave;
        #endif
                        tex.LoadImage(pngTextures[i].bytes);
                        textureInsts[i] = tex;
                        tex.filterMode  = textureFilterMode;
                        tex.Apply(textureMipMaps, true);
                    }
                }

                for (int i = 0; i < materials.Length; ++i)
                {
                    materialInsts[i] = Instantiate(materials[i]) as Material;
        #if UNITY_EDITOR
                    materialInsts[i].name      = string.Format("{0}Material_{1}_{2}", internalResourcePrefix, name, materials[i].name);
                    materialInsts[i].hideFlags = HideFlags.DontSave;
        #endif
                    if (assignTextureInst)
                    {
                        int textureId = (materialPngTextureId.Length == 0) ? 0 : materialPngTextureId[i];
                        materialInsts[i].mainTexture = textureInsts[textureId];
                    }
                }
            }
            for (int i = 0; i < spriteDefinitions.Length; ++i)
            {
                tk2dSpriteDefinition def = spriteDefinitions[i];
                def.materialInst = materialInsts[def.materialId];
            }
        }
        else
        {
            for (int i = 0; i < materials.Length; ++i)
            {
                materialInsts[i] = materials[i];
            }
            for (int i = 0; i < spriteDefinitions.Length; ++i)
            {
                tk2dSpriteDefinition def = spriteDefinitions[i];
                def.materialInst = def.material;
            }
        }


#if (UNITY_EDITOR && !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2))
        // Unity 4.3 when in 2D mode overrides imported textures with alphaIsTransparency set
        // which naturally breaks our old demo scenes. This happens even when meta files
        // are present :(
        if (materialInsts != null &&
            materialInsts.Length > 0 &&
            materialInsts[0] != null &&
            materialInsts[0].mainTexture != null &&
            materialInsts[0].shader != null &&
            materialInsts[0].shader.name.Contains("Premul"))                          // Detect premultiplied textures
        {
            string path = UnityEditor.AssetDatabase.GetAssetPath(materialInsts[0].mainTexture);
            if (path.Length > 0)
            {
                UnityEditor.TextureImporter importer = UnityEditor.TextureImporter.GetAtPath(path) as UnityEditor.TextureImporter;
                if (importer != null && (importer.alphaIsTransparency || importer.grayscaleToAlpha))
                {
                    if (UnityEditor.EditorUtility.DisplayDialog(
                            "Atlas texture incompatibility",
                            string.Format("Atlas texture '{0}' for sprite collection '{1}' must be reimported to display correctly in Unity 4.3 when in 2D mode.", materialInsts[0].mainTexture.name, name),
                            "Reimport"))
                    {
                        List <Texture> textures = new List <Texture>();
                        for (int i = 0; i < materialInsts.Length; ++i)
                        {
                            if (materialInsts[i] != null &&
                                materialInsts[i].mainTexture != null &&
                                !textures.Contains(materialInsts[i].mainTexture) &&                                         // only do this once
                                materialInsts[i].shader != null)
                            {
                                path = UnityEditor.AssetDatabase.GetAssetPath(materialInsts[i].mainTexture);
                                if (path.Length > 0)
                                {
                                    importer = UnityEditor.TextureImporter.GetAtPath(path) as UnityEditor.TextureImporter;
                                    if (importer != null && (importer.alphaIsTransparency || importer.grayscaleToAlpha))
                                    {
                                        importer.alphaIsTransparency = false;
                                        importer.grayscaleToAlpha    = false;
                                        UnityEditor.EditorUtility.SetDirty(importer);
                                        UnityEditor.AssetDatabase.ImportAsset(path);
                                    }
                                }
                                textures.Add(materialInsts[i].mainTexture);
                            }
                        }
                    }
                }
            }
        }
#endif

        tk2dEditorSpriteDataUnloader.Register(this);
    }
Пример #47
0
        private void UseSelectedTexture()
        {
            if (Selection.objects.Length > 1)
            {
                selectedTexture = null;
            }
            else
            {
                selectedTexture = Selection.activeObject as Texture2D;
            }

            if (selectedTexture != null)
            {
                var assetPath = AssetDatabase.GetAssetPath(selectedTexture);

                importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;

                if (importer)
                {
                    var extension = Path.GetExtension(assetPath);
                    var pathWithoutExtension = assetPath.Remove(assetPath.Length - extension.Length, extension.Length);

                    var xmlPath = pathWithoutExtension + ".xml";

                    var textAsset = AssetDatabase.LoadAssetAtPath(xmlPath, typeof(TextAsset));

                    if (textAsset != null)
                    {
                        xmlAsset = textAsset as TextAsset;
                    }
                    else
                    {
                        xmlAsset = null;
                        subTextures = null;
                    }

                    ParseXML();
                }
                else
                {
                    xmlAsset = null;
                    subTextures = null;
                }
            }
            else
            {
                importer = null;
                xmlAsset = null;
                subTextures = null;
            }

            Repaint();
        }
        /**
         * Does two things:
         * 1 - Changes the NPOT strategy to "ToNearest";
         * 2 - Changes the compression to DXT1 or DXT5 if compression is set to something different than DTX1.
         * It only changes the meta file of the texture.
         */
        static void DxtCompressTexture(TextureImporter textureImporter)
        {
            TextureImporterFormat format;
            TextureImporterSettings textureImporterSettings = new TextureImporterSettings();
            textureImporter.ReadTextureSettings(textureImporterSettings);
            format = textureImporterSettings.textureFormat;

            if (format != TextureImporterFormat.DXT1)
            {
                if (textureImporter.DoesSourceTextureHaveAlpha())
                    format = TextureImporterFormat.DXT5;
                else
                    format = TextureImporterFormat.DXT1;
            }

            textureImporter.npotScale = TextureImporterNPOTScale.ToNearest;

            textureImporterSettings.textureFormat = format;
            textureImporter.SetTextureSettings(textureImporterSettings);
        }
Пример #49
0
 public static void postProcessTexture(string _TexturePath, TextureImporter _Importer)
 {
     m_TaskManager.waitFor(0f).then(() => postProcessTextureDelayed(_TexturePath, _Importer));
 }
        public override Texture2D RenderStaticPreview(string assetPath, Object[] subAssets, int width, int height)
        {
            if (!ShaderUtil.hardwareSupportsRectRenderTexture)
            {
                return(null);
            }

            Texture texture = target as Texture;

            GraphicsFormat format = texture.graphicsFormat;

            if (!(GraphicsFormatUtility.IsIEEE754Format(format) || GraphicsFormatUtility.IsNormFormat(format)))
            {
                // Can't generate correct previews for non-float/norm formats. On Metal and Vulkan this even causes validation errors.
                return(null);
            }

            if (IsCubemap())
            {
                return(m_CubemapPreview.RenderStaticPreview(texture, width, height, GetExposureValueForTexture(texture)));
            }

            if (IsTexture3D())
            {
                return(m_Texture3DPreview.RenderStaticPreview(texture, width, height));
            }

            TextureImporter textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;

            if (textureImporter != null && textureImporter.textureType == TextureImporterType.Sprite && textureImporter.spriteImportMode == SpriteImportMode.Polygon)
            {
                // If the texture importer is a Sprite of primitive, use the sprite inspector for generating preview/icon.
                if (subAssets.Length > 0)
                {
                    Sprite sprite = subAssets[0] as Sprite;
                    if (sprite)
                    {
                        return(SpriteInspector.BuildPreviewTexture(sprite, null, true, width, height));
                    }
                }
                else
                {
                    return(null);
                }
            }

            PreviewHelpers.AdjustWidthAndHeightForStaticPreview(texture.width, texture.height, ref width, ref height);

            RenderTexture savedRT       = RenderTexture.active;
            Rect          savedViewport = ShaderUtil.rawViewportRect;

            var rt = texture as RenderTexture;

            if (rt != null)
            {
                rt.Create(); // Ensure RT is created. Otherwise the first attempted Blit will end up binding a dummy 2D Texture where it expects a 2D Texture Array. (validation errors observed on Vulkan/Metal)
            }

            RenderTexture tmp = RenderTexture.GetTemporary(
                width, height,
                0,
                SystemInfo.GetGraphicsFormat(DefaultFormat.LDR));
            Material mat = EditorGUI.GetMaterialForSpecialTexture(texture, null, QualitySettings.activeColorSpace == ColorSpace.Linear, false);

            if (mat != null)
            {
                Graphics.Blit(texture, tmp, mat);
            }
            else
            {
                Graphics.Blit(texture, tmp);
            }

            RenderTexture.active = tmp;
            Texture2D copy;
            Texture2D tex2d = target as Texture2D;

            if (tex2d != null && tex2d.alphaIsTransparency)
            {
                copy = new Texture2D(width, height, TextureFormat.RGBA32, false);
            }
            else
            {
                copy = new Texture2D(width, height, TextureFormat.RGB24, false);
            }
            copy.ReadPixels(new Rect(0, 0, width, height), 0, 0);
            copy.Apply();
            RenderTexture.ReleaseTemporary(tmp);

            EditorGUIUtility.SetRenderTextureNoViewport(savedRT);
            ShaderUtil.rawViewportRect = savedViewport;

            return(copy);
        }
Пример #51
0
 private static bool hasCorrectImportSettings(TextureImporter _Importer, GAFTexturesResource _Resource)
 {
     return  _Importer.textureType			== TextureImporterType.Advanced &&
             _Importer.npotScale				== TextureImporterNPOTScale.None &&
             _Importer.maxTextureSize		== 4096 &&
             _Importer.alphaIsTransparency	== true &&
             _Importer.mipmapEnabled			== false;
 }
Пример #52
0
		void RefreshTexture(bool force = false)
		{
			if(!m_SpriteMeshCache || !m_SpriteMeshCache.spriteMesh || !m_SpriteMeshCache.spriteMesh.sprite)
			{
				return;
			}
			
			Texture2D spriteTexture = SpriteUtility.GetSpriteTexture(m_SpriteMeshCache.spriteMesh.sprite,false);
			
			if(force || spriteTexture != m_OriginalTexture)
			{
				m_OriginalTexture = spriteTexture;
				m_TextureImporter = (AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(m_OriginalTexture)) as TextureImporter);
				
				if(m_Texture)
				{
					DestroyImmediate(m_Texture);
				}
				
				if(m_OriginalTexture)
				{
					int width = 0;
					int height = 0;
					
					SpriteMeshUtils.GetWidthAndHeight(m_TextureImporter,ref width, ref height);
					
					m_Texture = CreateTemporaryDuplicate(m_OriginalTexture,width,height);
					m_Texture.filterMode = UnityEngine.FilterMode.Point;
					m_Texture.hideFlags = HideFlags.DontSave;
				}
			}
		}
Пример #53
0
        public override void OnPreviewGUI(Rect r, GUIStyle background)
        {
            if (Event.current.type == EventType.Repaint)
            {
                background.Draw(r, false, false, false, false);
            }

            // show texture
            Texture t = target as Texture;

            if (t == null) // texture might be gone by now, in case this code is used for floating texture preview
            {
                return;
            }

            // Render target must be created before we can display it (case 491797)
            RenderTexture rt = t as RenderTexture;

            if (rt != null)
            {
                if (!SystemInfo.IsFormatSupported(rt.graphicsFormat, FormatUsage.Render))
                {
                    return; // can't do this RT format
                }
                rt.Create();
            }

            if (IsCubemap())
            {
                m_CubemapPreview.OnPreviewGUI(t, r, background);
                return;
            }

            // target can report zero sizes in some cases just after a parameter change;
            // guard against that.
            int texWidth  = Mathf.Max(t.width, 1);
            int texHeight = Mathf.Max(t.height, 1);

            float mipLevel   = GetMipLevelForRendering();
            float zoomLevel  = Mathf.Min(Mathf.Min(r.width / texWidth, r.height / texHeight), 1);
            Rect  wantedRect = new Rect(r.x, r.y, texWidth * zoomLevel, texHeight * zoomLevel);

            PreviewGUI.BeginScrollView(r, m_Pos, wantedRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb");
            FilterMode oldFilter = t.filterMode;

            TextureUtil.SetFilterModeNoDirty(t, FilterMode.Point);
            Texture2D      t2d            = t as Texture2D;
            ColorWriteMask colorWriteMask = ColorWriteMask.All;

            switch (m_PreviewMode)
            {
            case PreviewMode.R:
                colorWriteMask = ColorWriteMask.Red | ColorWriteMask.Alpha;
                break;

            case PreviewMode.G:
                colorWriteMask = ColorWriteMask.Green | ColorWriteMask.Alpha;
                break;

            case PreviewMode.B:
                colorWriteMask = ColorWriteMask.Blue | ColorWriteMask.Alpha;
                break;
            }

            if (m_PreviewMode == PreviewMode.A)
            {
                EditorGUI.DrawTextureAlpha(wantedRect, t, ScaleMode.StretchToFill, 0, mipLevel);
            }
            else
            {
                if (t2d != null && t2d.alphaIsTransparency)
                {
                    EditorGUI.DrawTextureTransparent(wantedRect, t, ScaleMode.StretchToFill, 0, mipLevel, colorWriteMask);
                }
                else
                {
                    EditorGUI.DrawPreviewTexture(wantedRect, t, null, ScaleMode.StretchToFill, 0, mipLevel, colorWriteMask);
                }
            }

            // TODO: Less hacky way to prevent sprite rects to not appear in smaller previews like icons.
            if ((wantedRect.width > 32 && wantedRect.height > 32) && Event.current.type == EventType.Repaint)
            {
                string           path            = AssetDatabase.GetAssetPath(t);
                TextureImporter  textureImporter = AssetImporter.GetAtPath(path) as TextureImporter;
                SpriteMetaData[] spritesheet     = textureImporter != null ? textureImporter.spritesheet : null;

                if (spritesheet != null && textureImporter.spriteImportMode == SpriteImportMode.Multiple)
                {
                    Rect screenRect = new Rect();
                    Rect sourceRect = new Rect();
                    GUI.CalculateScaledTextureRects(wantedRect, ScaleMode.StretchToFill, (float)t.width / (float)t.height, ref screenRect, ref sourceRect);

                    int origWidth  = t.width;
                    int origHeight = t.height;
                    textureImporter.GetWidthAndHeight(ref origWidth, ref origHeight);
                    float definitionScale = (float)t.width / (float)origWidth;

                    HandleUtility.ApplyWireMaterial();
                    GL.PushMatrix();
                    GL.MultMatrix(Handles.matrix);
                    GL.Begin(GL.LINES);
                    GL.Color(new Color(1f, 1f, 1f, 0.5f));
                    foreach (SpriteMetaData sprite in spritesheet)
                    {
                        Rect spriteRect       = sprite.rect;
                        Rect spriteScreenRect = new Rect();
                        spriteScreenRect.xMin = screenRect.xMin + screenRect.width * (spriteRect.xMin / t.width * definitionScale);
                        spriteScreenRect.xMax = screenRect.xMin + screenRect.width * (spriteRect.xMax / t.width * definitionScale);
                        spriteScreenRect.yMin = screenRect.yMin + screenRect.height * (1f - spriteRect.yMin / t.height * definitionScale);
                        spriteScreenRect.yMax = screenRect.yMin + screenRect.height * (1f - spriteRect.yMax / t.height * definitionScale);
                        DrawRect(spriteScreenRect);
                    }
                    GL.End();
                    GL.PopMatrix();
                }
            }

            TextureUtil.SetFilterModeNoDirty(t, oldFilter);

            m_Pos = PreviewGUI.EndScrollView();
            if (mipLevel != 0)
            {
                EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20), "Mip " + mipLevel);
            }
        }
        public TextureImportPlatformSettings(string name, BuildTarget target, TextureImporterInspector inspector)
        {
            m_PlatformSettings.name = name;

            m_Target    = target;
            m_Inspector = inspector;
            m_PlatformSettings.overridden = false;
            m_Importers = inspector.targets.Select(x => x as TextureImporter).ToArray();
            for (int i = 0; i < importers.Length; i++)
            {
                TextureImporter imp = importers[i];
                TextureImporterPlatformSettings curPlatformSettings = imp.GetPlatformTextureSettings(name);

                if (i == 0)
                {
                    m_PlatformSettings = curPlatformSettings;
                }
                else
                {
                    if (curPlatformSettings.overridden != m_PlatformSettings.overridden)
                    {
                        m_OverriddenIsDifferent = true;
                    }
                    if (curPlatformSettings.format != m_PlatformSettings.format)
                    {
                        m_TextureFormatIsDifferent = true;
                    }
                    if (curPlatformSettings.maxTextureSize != m_PlatformSettings.maxTextureSize)
                    {
                        m_MaxTextureSizeIsDifferent = true;
                    }
                    if (curPlatformSettings.resizeAlgorithm != m_PlatformSettings.resizeAlgorithm)
                    {
                        m_ResizeAlgorithmIsDifferent = true;
                    }
                    if (curPlatformSettings.textureCompression != m_PlatformSettings.textureCompression)
                    {
                        m_TextureCompressionIsDifferent = true;
                    }
                    if (curPlatformSettings.compressionQuality != m_PlatformSettings.compressionQuality)
                    {
                        m_CompressionQualityIsDifferent = true;
                    }
                    if (curPlatformSettings.crunchedCompression != m_PlatformSettings.crunchedCompression)
                    {
                        m_CrunchedCompressionIsDifferent = true;
                    }
                    if (curPlatformSettings.allowsAlphaSplitting != m_PlatformSettings.allowsAlphaSplitting)
                    {
                        m_AlphaSplitIsDifferent = true;
                    }
                    if (curPlatformSettings.androidETC2FallbackOverride !=
                        m_PlatformSettings.androidETC2FallbackOverride)
                    {
                        m_AndroidETC2FallbackOverrideIsDifferent = true;
                    }
                }
            }

            Sync();
        }
Пример #55
0
    //把UI图片设置为只读,减少内存占用
    public void OnPreprocessTexture()
    {
        UnityEditor.TextureImporter importer = this.assetImporter as UnityEditor.TextureImporter;
        if (importer == null)
        {
            return;
        }
        var andSettings = new TextureImporterPlatformSettings();
        var iosSettings = new TextureImporterPlatformSettings();

        andSettings.name               = "Android";
        iosSettings.name               = "iPhone";
        andSettings.overridden         = true;
        iosSettings.overridden         = true;
        andSettings.compressionQuality = iosSettings.compressionQuality = 50;

        andSettings.format = TextureImporterFormat.ETC2_RGBA8;
        andSettings.androidETC2FallbackOverride = AndroidETC2FallbackOverride.Quality32Bit;
        iosSettings.format         = TextureImporterFormat.ASTC_6x6;
        andSettings.maxTextureSize = iosSettings.maxTextureSize = 1024;//NOTE 如果有特殊需求可通过配置修改

        importer.SetPlatformTextureSettings(andSettings);
        importer.SetPlatformTextureSettings(iosSettings);

        var rootDir = importer.assetPath.Split('/')[1];

        if (rootDir == KEngineDef.ResourcesEditDir)
        {
            if (importer.isReadable)
            {
                importer.isReadable = false;
            }

            if (importer.assetPath.StartsWith(KEngineDef.UIPath))
            {
                if (assetPath.Contains("Fonts"))
                {
                    importer.textureType = TextureImporterType.Default;
                }
                else
                {
                    importer.textureType = TextureImporterType.Sprite;
                }

                importer.mipmapEnabled = false;
                //NOTE 根据项目的实际情况,是把同一种类所有icon打到一个ab中,还是每个icon打成一个ab
            }
            else if (importer.assetPath.Contains("Character"))
            {
                if (!(importer.assetPath.Contains("Character/Hero") || importer.assetPath.Contains("Character/Hair")))
                {
                    importer.textureType   = TextureImporterType.Default;
                    importer.mipmapEnabled = false;
                }
            }
            else if (importer.assetPath.Contains(".exr"))
            {
                //Debug.Log("lightmap settings: " + importer.assetPath);
                importer.textureType = TextureImporterType.Lightmap;
#if UNITY_2018_3_OR_NEWER
                importer.textureCompression = TextureImporterCompression.Uncompressed;
                var ftm = importer.GetDefaultPlatformTextureSettings();
                ftm.format = TextureImporterFormat.RGBA32;
                importer.SetPlatformTextureSettings(ftm);
#else
                importer.textureFormat = TextureImporterFormat.AutomaticTruecolor;
#endif
                importer.wrapMode = TextureWrapMode.Clamp;
                //importer.mipmapEnabled = false;
            }
        }
        else
        {
            if (importer.assetPath.Contains("Editor/GameTools/XSceneTool/MapImages"))
            {
                importer.textureType   = TextureImporterType.Default;
                importer.mipmapEnabled = false;
                importer.npotScale     = TextureImporterNPOTScale.None;
                if (!importer.isReadable)
                {
                    importer.isReadable = true;
                }
            }
        }
    }
Пример #56
0
        private static void SetDefaultSpriteSettings(ref TextureImporter textureImporter)
        {
            textureImporter.textureFormat = TextureImporterFormat.ARGB32;
            textureImporter.textureType = TextureImporterType.Advanced;
            textureImporter.spriteImportMode = SpriteImportMode.Single;
            textureImporter.npotScale = TextureImporterNPOTScale.None;
            textureImporter.filterMode = FilterMode.Point;
            textureImporter.isReadable = true;
            textureImporter.wrapMode = TextureWrapMode.Clamp;
            textureImporter.mipmapEnabled = false;

            TextureImporterSettings settings = new TextureImporterSettings ();
            textureImporter.ReadTextureSettings (settings);
            settings.spriteMeshType = SpriteMeshType.FullRect;
            settings.spriteAlignment = (int)SpriteAlignment.Center;
            textureImporter.SetTextureSettings (settings);
        }
Пример #57
0
        public override void OnPreviewGUI(Rect r, GUIStyle background)
        {
            if (Event.current.type == EventType.Repaint)
            {
                background.Draw(r, false, false, false, false);
            }
            Texture       target   = this.target as Texture;
            RenderTexture texture2 = target as RenderTexture;

            if (texture2 != null)
            {
                if (!SystemInfo.SupportsRenderTextureFormat(texture2.format))
                {
                    return;
                }
                texture2.Create();
            }
            if (this.IsCubemap())
            {
                this.m_CubemapPreview.OnPreviewGUI(target, r, background);
            }
            else
            {
                int   num  = Mathf.Max(target.width, 1);
                int   num2 = Mathf.Max(target.height, 1);
                float mipLevelForRendering = this.GetMipLevelForRendering();
                float num4     = Mathf.Min(Mathf.Min((float)(r.width / ((float)num)), (float)(r.height / ((float)num2))), 1f);
                Rect  viewRect = new Rect(r.x, r.y, num * num4, num2 * num4);
                PreviewGUI.BeginScrollView(r, this.m_Pos, viewRect, "PreHorizontalScrollbar", "PreHorizontalScrollbarThumb");
                float mipMapBias = target.mipMapBias;
                TextureUtil.SetMipMapBiasNoDirty(target, mipLevelForRendering - this.Log2(((float)num) / viewRect.width));
                FilterMode filterMode = target.filterMode;
                TextureUtil.SetFilterModeNoDirty(target, FilterMode.Point);
                if (this.m_ShowAlpha)
                {
                    EditorGUI.DrawTextureAlpha(viewRect, target);
                }
                else
                {
                    Texture2D textured = target as Texture2D;
                    if ((textured != null) && textured.alphaIsTransparency)
                    {
                        EditorGUI.DrawTextureTransparent(viewRect, target);
                    }
                    else
                    {
                        EditorGUI.DrawPreviewTexture(viewRect, target);
                    }
                }
                if ((viewRect.width > 32f) && (viewRect.height > 32f))
                {
                    TextureImporter  atPath    = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(target)) as TextureImporter;
                    SpriteMetaData[] dataArray = (atPath == null) ? null : atPath.spritesheet;
                    if ((dataArray != null) && (atPath.spriteImportMode == SpriteImportMode.Multiple))
                    {
                        Rect outScreenRect = new Rect();
                        Rect outSourceRect = new Rect();
                        GUI.CalculateScaledTextureRects(viewRect, ScaleMode.StretchToFill, ((float)target.width) / ((float)target.height), ref outScreenRect, ref outSourceRect);
                        int width  = target.width;
                        int height = target.height;
                        atPath.GetWidthAndHeight(ref width, ref height);
                        float num8 = ((float)target.width) / ((float)width);
                        HandleUtility.ApplyWireMaterial();
                        GL.PushMatrix();
                        GL.MultMatrix(Handles.matrix);
                        GL.Begin(1);
                        GL.Color(new Color(1f, 1f, 1f, 0.5f));
                        foreach (SpriteMetaData data in dataArray)
                        {
                            Rect rect  = data.rect;
                            Rect rect5 = new Rect {
                                xMin = outScreenRect.xMin + (outScreenRect.width * ((rect.xMin / ((float)target.width)) * num8)),
                                xMax = outScreenRect.xMin + (outScreenRect.width * ((rect.xMax / ((float)target.width)) * num8)),
                                yMin = outScreenRect.yMin + (outScreenRect.height * (1f - ((rect.yMin / ((float)target.height)) * num8))),
                                yMax = outScreenRect.yMin + (outScreenRect.height * (1f - ((rect.yMax / ((float)target.height)) * num8)))
                            };
                            this.DrawRect(rect5);
                        }
                        GL.End();
                        GL.PopMatrix();
                    }
                }
                TextureUtil.SetMipMapBiasNoDirty(target, mipMapBias);
                TextureUtil.SetFilterModeNoDirty(target, filterMode);
                this.m_Pos = PreviewGUI.EndScrollView();
                if (mipLevelForRendering != 0f)
                {
                    EditorGUI.DropShadowLabel(new Rect(r.x, r.y, r.width, 20f), "Mip " + mipLevelForRendering);
                }
            }
        }