public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs) { List<DefaultPackerPolicy.Entry> source1 = new List<DefaultPackerPolicy.Entry>(); foreach (int importerInstanceId in textureImporterInstanceIDs) { TextureImporter textureImporter = EditorUtility.InstanceIDToObject(importerInstanceId) as TextureImporter; TextureFormat desiredFormat; ColorSpace colorSpace; int compressionQuality; textureImporter.ReadTextureImportInstructions(target, out desiredFormat, out colorSpace, out compressionQuality); TextureImporterSettings dest = new TextureImporterSettings(); textureImporter.ReadTextureSettings(dest); foreach (Sprite sprite in ((IEnumerable<UnityEngine.Object>) AssetDatabase.LoadAllAssetRepresentationsAtPath(textureImporter.assetPath)).Select<UnityEngine.Object, Sprite>((Func<UnityEngine.Object, Sprite>) (x => x as Sprite)).Where<Sprite>((Func<Sprite, bool>) (x => (UnityEngine.Object) x != (UnityEngine.Object) null)).ToArray<Sprite>()) source1.Add(new DefaultPackerPolicy.Entry() { sprite = sprite, settings = { format = desiredFormat, colorSpace = colorSpace, compressionQuality = !TextureUtil.IsCompressedTextureFormat(desiredFormat) ? 0 : compressionQuality, filterMode = !Enum.IsDefined(typeof (UnityEngine.FilterMode), (object) textureImporter.filterMode) ? UnityEngine.FilterMode.Bilinear : textureImporter.filterMode, maxWidth = 2048, maxHeight = 2048, generateMipMaps = textureImporter.mipmapEnabled, enableRotation = this.AllowRotationFlipping, allowsAlphaSplitting = textureImporter.GetAllowsAlphaSplitting(), paddingPower = !textureImporter.mipmapEnabled ? (uint) EditorSettings.spritePackerPaddingPower : 3U }, atlasName = this.ParseAtlasName(textureImporter.spritePackingTag), packingMode = this.GetPackingMode(textureImporter.spritePackingTag, dest.spriteMeshType), anisoLevel = textureImporter.anisoLevel }); Resources.UnloadAsset((UnityEngine.Object) textureImporter); } foreach (IGrouping<string, DefaultPackerPolicy.Entry> source2 in source1.GroupBy<DefaultPackerPolicy.Entry, string, DefaultPackerPolicy.Entry>((Func<DefaultPackerPolicy.Entry, string>) (e => e.atlasName), (Func<DefaultPackerPolicy.Entry, DefaultPackerPolicy.Entry>) (e => e))) { int num = 0; IEnumerable<IGrouping<AtlasSettings, DefaultPackerPolicy.Entry>> source3 = source2.GroupBy<DefaultPackerPolicy.Entry, AtlasSettings, DefaultPackerPolicy.Entry>((Func<DefaultPackerPolicy.Entry, AtlasSettings>) (t => t.settings), (Func<DefaultPackerPolicy.Entry, DefaultPackerPolicy.Entry>) (t => t)); foreach (IGrouping<AtlasSettings, DefaultPackerPolicy.Entry> grouping in source3) { string key1 = source2.Key; if (source3.Count<IGrouping<AtlasSettings, DefaultPackerPolicy.Entry>>() > 1) key1 += string.Format(" (Group {0})", (object) num); AtlasSettings key2 = grouping.Key; key2.anisoLevel = 1; if (key2.generateMipMaps) { foreach (DefaultPackerPolicy.Entry entry in (IEnumerable<DefaultPackerPolicy.Entry>) grouping) { if (entry.anisoLevel > key2.anisoLevel) key2.anisoLevel = entry.anisoLevel; } } job.AddAtlas(key1, key2); foreach (DefaultPackerPolicy.Entry entry in (IEnumerable<DefaultPackerPolicy.Entry>) grouping) job.AssignToAtlas(key1, entry.sprite, entry.packingMode, SpritePackingRotation.None); ++num; } } }
public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs) { List<DefaultPackerPolicy.Entry> list = new List<DefaultPackerPolicy.Entry>(); for (int i = 0; i < textureImporterInstanceIDs.Length; i++) { int instanceID = textureImporterInstanceIDs[i]; TextureImporter textureImporter = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter; TextureFormat format; ColorSpace colorSpace; int compressionQuality; textureImporter.ReadTextureImportInstructions(target, out format, out colorSpace, out compressionQuality); TextureImporterSettings textureImporterSettings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(textureImporterSettings); Sprite[] array = ( from x in AssetDatabase.LoadAllAssetRepresentationsAtPath(textureImporter.assetPath) select x as Sprite into x where x != null select x).ToArray<Sprite>(); Sprite[] array2 = array; for (int j = 0; j < array2.Length; j++) { Sprite sprite = array2[j]; DefaultPackerPolicy.Entry entry = new DefaultPackerPolicy.Entry(); entry.sprite = sprite; entry.settings.format = format; entry.settings.colorSpace = colorSpace; entry.settings.compressionQuality = compressionQuality; entry.settings.filterMode = ((!Enum.IsDefined(typeof(FilterMode), textureImporter.filterMode)) ? FilterMode.Bilinear : textureImporter.filterMode); entry.settings.maxWidth = 2048; entry.settings.maxHeight = 2048; entry.settings.generateMipMaps = textureImporter.mipmapEnabled; if (textureImporter.mipmapEnabled) { entry.settings.paddingPower = 2u; } entry.atlasName = this.ParseAtlasName(textureImporter.spritePackingTag); entry.packingMode = this.GetPackingMode(textureImporter.spritePackingTag, textureImporterSettings.spriteMeshType); entry.anisoLevel = textureImporter.anisoLevel; list.Add(entry); } Resources.UnloadAsset(textureImporter); } IEnumerable<IGrouping<string, DefaultPackerPolicy.Entry>> enumerable = from e in list group e by e.atlasName; foreach (IGrouping<string, DefaultPackerPolicy.Entry> current in enumerable) { int num = 0; IEnumerable<IGrouping<AtlasSettings, DefaultPackerPolicy.Entry>> enumerable2 = from t in current group t by t.settings; foreach (IGrouping<AtlasSettings, DefaultPackerPolicy.Entry> current2 in enumerable2) { string text = current.Key; if (enumerable2.Count<IGrouping<AtlasSettings, DefaultPackerPolicy.Entry>>() > 1) { text += string.Format(" (Group {0})", num); } AtlasSettings key = current2.Key; key.anisoLevel = 1; if (key.generateMipMaps) { foreach (DefaultPackerPolicy.Entry current3 in current2) { if (current3.anisoLevel > key.anisoLevel) { key.anisoLevel = current3.anisoLevel; } } } job.AddAtlas(text, key); foreach (DefaultPackerPolicy.Entry current4 in current2) { job.AssignToAtlas(text, current4.sprite, current4.packingMode, SpritePackingRotation.None); } num++; } } }
public virtual void ShowImportSettings(BaseTextureImportPlatformSettings editor) { // Max texture size EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = editor.model.overriddenIsDifferent || editor.model.maxTextureSizeIsDifferent; int maxTextureSize = EditorGUILayout.IntPopup(maxSize.text, editor.model.platformTextureSettings.maxTextureSize, kMaxTextureSizeStrings, kMaxTextureSizeValues); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { editor.model.SetMaxTextureSizeForAll(maxTextureSize); } // Resize Algorithm EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = editor.model.overriddenIsDifferent || editor.model.resizeAlgorithmIsDifferent; int resizeAlgorithmVal = EditorGUILayout.IntPopup(kResizeAlgorithm.text, (int)editor.model.platformTextureSettings.resizeAlgorithm, kResizeAlgorithmStrings, kResizeAlgorithmValues); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { editor.model.SetResizeAlgorithmForAll((TextureResizeAlgorithm)resizeAlgorithmVal); } // Texture format int[] formatValuesForAll = {}; string[] formatStringsForAll = {}; bool formatOptionsAreDifferent = false; int formatForAll = 0; // TODO : This should not be calculated every refresh and be kept in a cache somewhere instead... for (int i = 0; i < editor.GetTargetCount(); i++) { TextureImporterSettings settings = editor.GetImporterSettings(i); TextureImporterType textureTypeForThis = editor.textureTypeHasMultipleDifferentValues ? settings.textureType : editor.textureType; int format = (int)editor.model.platformTextureSettings.format; int[] formatValues = null; string[] formatStrings = null; if (!editor.model.isDefault && !editor.model.platformTextureSettings.overridden) { // If not overriden, show what the auto format is going to be // don't care about alpha in normal maps. If editor.assetTarget is null // then we are dealing with texture preset and we show all options. var showSettingsForPreset = editor.ShowPresetSettings(); var sourceHasAlpha = showSettingsForPreset || (editor.DoesSourceTextureHaveAlpha(i) && textureTypeForThis != TextureImporterType.NormalMap); format = (int)TextureImporter.DefaultFormatFromTextureParameters(settings, editor.model.platformTextureSettings, !showSettingsForPreset && sourceHasAlpha, !showSettingsForPreset && editor.IsSourceTextureHDR(i), editor.model.buildTarget); formatValues = new int[] { format }; formatStrings = new string[] { TextureUtil.GetTextureFormatString((TextureFormat)format) }; } else { // otherwise show valid formats editor.model.GetValidTextureFormatsAndStrings(textureTypeForThis, out formatValues, out formatStrings); } // Check if values are the same if (i == 0) { formatValuesForAll = formatValues; formatStringsForAll = formatStrings; formatForAll = format; } else { if (!formatValues.SequenceEqual(formatValuesForAll) || !formatStrings.SequenceEqual(formatStringsForAll)) { formatOptionsAreDifferent = true; break; } } } using (new EditorGUI.DisabledScope(formatOptionsAreDifferent || formatStringsForAll.Length == 1)) { EditorGUI.BeginChangeCheck(); bool mixedValues = formatOptionsAreDifferent || editor.model.textureFormatIsDifferent; EditorGUI.showMixedValue = mixedValues; var selectionResult = EditorGUILayout.IntPopup(kTextureFormat, formatForAll, EditorGUIUtility.TempContent(formatStringsForAll), formatValuesForAll); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { editor.model.SetTextureFormatForAll((TextureImporterFormat)selectionResult); formatForAll = selectionResult; } if (!mixedValues && !Array.Exists(formatValuesForAll, i => i == formatForAll)) { EditorGUILayout.HelpBox(string.Format(L10n.Tr("The selected format value {0} is not compatible on this platform, please change it to a valid one from the dropdown."), (TextureImporterFormat)formatForAll), MessageType.Error); } } // Texture Compression if (editor.model.isDefault && editor.model.platformTextureSettings.format == TextureImporterFormat.Automatic) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = editor.model.overriddenIsDifferent || editor.model.textureCompressionIsDifferent || editor.model.platformTextureSettings.format != TextureImporterFormat.Automatic; TextureImporterCompression textureCompression = (TextureImporterCompression)EditorGUILayout.IntPopup(kTextureCompression, (int)editor.model.platformTextureSettings.textureCompression, kTextureCompressionOptions, kTextureCompressionValues); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { editor.model.SetTextureCompressionForAll(textureCompression); } } // Use Crunch Compression if (editor.model.isDefault && (TextureImporterFormat)formatForAll == TextureImporterFormat.Automatic && editor.model.platformTextureSettings.textureCompression != TextureImporterCompression.Uncompressed) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = editor.model.overriddenIsDifferent || editor.model.crunchedCompressionIsDifferent; bool crunchedCompression = EditorGUILayout.Toggle( kCrunchedCompression, editor.model.platformTextureSettings.crunchedCompression); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { editor.model.SetCrunchedCompressionForAll(crunchedCompression); } } // compression quality bool isCrunchedFormat = false || TextureUtil.IsCompressedCrunchTextureFormat((TextureFormat)formatForAll) ; if ( (editor.model.isDefault && (TextureImporterFormat)formatForAll == TextureImporterFormat.Automatic && editor.model.platformTextureSettings.textureCompression != TextureImporterCompression.Uncompressed && editor.model.platformTextureSettings.crunchedCompression) || (editor.model.isDefault && editor.model.platformTextureSettings.crunchedCompression && isCrunchedFormat) || (!editor.model.isDefault && isCrunchedFormat) || (!editor.model.textureFormatIsDifferent && ArrayUtility.Contains <TextureImporterFormat>( TextureImporterInspector.kFormatsWithCompressionSettings, (TextureImporterFormat)formatForAll))) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = editor.model.overriddenIsDifferent || editor.model.compressionQualityIsDifferent; // Prior to exposing compression quality for BC6H/BC7 formats they were always compressed at maximum quality even though the setting was // defaulted to 'Normal'. Now BC6H/BC7 quality is exposed to the user as Fast/Normal/Best 'Normal' maps to one setting down from maximum in the // ISPC compressor but to maintain the behaviour of existing projects we need to force their quality up to 'Best'. The 'forceMaximumCompressionQuality_BC6H_BC7' // flag is set when loading existing texture platform settings to do this and cleared when the compression quality level is manually set (by UI or API) bool forceBestQuality = editor.model.forceMaximumCompressionQuality_BC6H_BC7 && (((TextureImporterFormat)formatForAll == TextureImporterFormat.BC6H) || ((TextureImporterFormat)formatForAll == TextureImporterFormat.BC7)); int compressionQuality = forceBestQuality ? (int)TextureCompressionQuality.Best : editor.model.platformTextureSettings.compressionQuality; compressionQuality = EditCompressionQuality(editor.model.buildTarget, compressionQuality, isCrunchedFormat, (TextureImporterFormat)formatForAll); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { editor.model.SetCompressionQualityForAll(compressionQuality); //SyncPlatformSettings (); } } // show the ETC1 split option only for sprites on platforms supporting ETC and only when there is an alpha channel bool isETCPlatform = TextureImporter.IsETC1SupportedByBuildTarget(BuildPipeline.GetBuildTargetByName(editor.model.platformTextureSettings.name)); bool isDealingWithSprite = (editor.spriteImportMode != SpriteImportMode.None); bool isETCFormatSelected = TextureImporter.IsTextureFormatETC1Compression((TextureFormat)formatForAll); if (isETCPlatform && isDealingWithSprite && isETCFormatSelected) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = editor.model.overriddenIsDifferent || editor.model.allowsAlphaSplitIsDifferent; bool allowsAlphaSplit = EditorGUILayout.Toggle(kUseAlphaSplitLabel, editor.model.platformTextureSettings.allowsAlphaSplitting); if (EditorGUI.EndChangeCheck()) { editor.model.SetAllowsAlphaSplitForAll(allowsAlphaSplit); } } }
void ReimportTexture(string assetPath, TextureWrapMode wrapMode, FilterMode filterMode, int anisoLevel, int maxTextureSize, TextureImporterFormat textureFormat) { // Debug.Log("ChangeImportTextureToGUI - " + assetPath); TextureImporter texImporter = TextureImporter.GetAtPath(assetPath) as TextureImporter; TextureImporterSettings settings = new TextureImporterSettings(); texImporter.ReadTextureSettings(settings); // settings.ApplyTextureType(TextureImporterType.GUI, false); // texImporter.SetTextureSettings(settings); if (m_bSetGUI) { if (m_bGUI) { texImporter.textureType = TextureImporterType.GUI; } else { texImporter.textureType = TextureImporterType.Default; } } if (m_bSetWrapMode) { texImporter.wrapMode = wrapMode; } if (m_bSetGUI) { if (!m_bGUI) { if (m_bSetFilterMode) { texImporter.filterMode = filterMode; } if (m_bSetAnisoLevel) { texImporter.anisoLevel = anisoLevel; } } } else { if (m_bSetFilterMode) { texImporter.filterMode = filterMode; } if (m_bSetAnisoLevel) { texImporter.anisoLevel = anisoLevel; } } if (m_bSetMaxTextureSizeIdx) { texImporter.maxTextureSize = maxTextureSize; } if (m_bSetTextureFormatIdx) { texImporter.textureFormat = textureFormat; } // texImporter.npotScale = TextureImporterNPOTScale.None; AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceSynchronousImport); }
/// <summary> /// スンスペクター描画 /// </summary> public override void OnInspectorGUI() { // とりあえずデフォルト // DrawDefaultInspector() ; //-------------------------------------------- // ターゲットのインスタンス VoxelMesh tTarget = target as VoxelMesh; EditorGUILayout.Separator(); // 少し区切りスペース // オフセット Vector3 tOffset = EditorGUILayout.Vector3Field("Offset", tTarget.offset); if (tOffset != tTarget.offset) { Undo.RecordObject(tTarget, "VoxelMesh : Offset Change"); // アンドウバッファに登録 tTarget.offset = tOffset; EditorUtility.SetDirty(tTarget); } // ボクセルスケール // float tVoxelScale = EditorGUILayout.FloatField( "Voxel Scale", tTarget.voxelScale ) ; float tVoxelScale = EditorGUILayout.Slider("Voxel Scale", tTarget.voxelScale, 0.1f, 2.0f); if (tVoxelScale != tTarget.voxelScale && tVoxelScale > 0) { Undo.RecordObject(tTarget, "VoxelMesh : Voxel Scale Change"); // アンドウバッファに登録 tTarget.voxelScale = tVoxelScale; EditorUtility.SetDirty(tTarget); } // マテリアル Material tMaterial = EditorGUILayout.ObjectField("Maretial", tTarget.material, typeof(Material), false) as Material; if (tMaterial != tTarget.material) { Undo.RecordObject(tTarget, "VoxelMesh : Material Change"); // アンドウバッファに登録 tTarget.material = tMaterial; EditorUtility.SetDirty(tTarget); } // テクスチャ Texture2D tTexture = EditorGUILayout.ObjectField("Texture", tTarget.texture, typeof(Texture2D), false) as Texture2D; if (tTexture != tTarget.texture) { Undo.RecordObject(tTarget, "VoxelMesh : Texture Change"); // アンドウバッファに登録 tTarget.texture = tTexture; EditorUtility.SetDirty(tTarget); } // ボクセルテクスチャ Texture2D tVoxelTexture = EditorGUILayout.ObjectField("Voxel Texture", tTarget.voxelTexture, typeof(Texture2D), false) as Texture2D; bool tVoxelTextureReadable = tTarget.voxelTextureReadable; if (tVoxelTexture != null) { // Read/Write 属性が有効になっているか確認する // EditorUtility.DisplayDialog( "Voxel Texture", GetMessage( "VoxelTexture_BadProperty" ), "Close" ) ; // オブジェクトのファイルパスを取得する string tPath = AssetDatabase.GetAssetPath(tVoxelTexture.GetInstanceID()); // インポーターを取得る TextureImporter tTextureImporter = AssetImporter.GetAtPath(tPath) as TextureImporter; // インポーターから meta の設定情報を読み取る TextureImporterSettings tSettings = new TextureImporterSettings(); tTextureImporter.ReadTextureSettings(tSettings); if (tSettings.readable == false) { // 読み取り属性が有効になっていない EditorGUILayout.HelpBox(GetMessage("VoxelTexture_BadProperty"), MessageType.Warning, true); tVoxelTextureReadable = false; } else { // 読み取り属性が有効になっている tVoxelTextureReadable = true; } } else { tVoxelTextureReadable = false; } if (tVoxelTextureReadable != tTarget.voxelTextureReadable) { Undo.RecordObject(tTarget, "VoxelMesh : Voxel Texture Readable Change"); // アンドウバッファに登録 tTarget.voxelTextureReadable = tVoxelTextureReadable; EditorUtility.SetDirty(tTarget); } if (tVoxelTexture != tTarget.voxelTexture) { Undo.RecordObject(tTarget, "VoxelMesh : Voxel Texture Change"); // アンドウバッファに登録 tTarget.voxelTexture = tVoxelTexture; EditorUtility.SetDirty(tTarget); } }
Color[] GetPixels(Texture2D texture, bool toLinear) { Color[] ret = null; string assetPath = AssetDatabase.GetAssetPath(texture); if (string.IsNullOrEmpty(assetPath) == false) { TextureImporter importer = TextureImporter.GetAtPath(assetPath) as TextureImporter; string extension = System.IO.Path.GetExtension(assetPath).ToLower(); TextureImporterFormat importFormat; if (extension == ".exr" || extension == ".hdr") { importFormat = TextureImporterFormat.RGBAHalf; } else { importFormat = TextureImporterFormat.RGBA32; } var overrideTextureImporterSettings = new TextureImporterSettings(); var textureImporterSettings = new TextureImporterSettings(); importer.ReadTextureSettings(overrideTextureImporterSettings); importer.ReadTextureSettings(textureImporterSettings); var defaultPlatformSettings = importer.GetDefaultPlatformTextureSettings(); var overrideDefaultPlatformSettings = new TextureImporterPlatformSettings(); defaultPlatformSettings.CopyTo(overrideDefaultPlatformSettings); var targetPlatformSettings = importer.GetPlatformTextureSettings(GetBuildTargetPlatformName()); var overrideTargetPlatformSettings = new TextureImporterPlatformSettings(); targetPlatformSettings.CopyTo(overrideTargetPlatformSettings); overrideTextureImporterSettings.readable = true; overrideTextureImporterSettings.sRGBTexture = false; /* GetPixels には関係ない? */ overrideDefaultPlatformSettings.format = TextureImporterFormat.Automatic; overrideDefaultPlatformSettings.textureCompression = TextureImporterCompression.Uncompressed; overrideDefaultPlatformSettings.crunchedCompression = false; overrideTargetPlatformSettings.overridden = true; overrideTargetPlatformSettings.format = importFormat; overrideTargetPlatformSettings.textureCompression = TextureImporterCompression.Uncompressed; overrideTargetPlatformSettings.crunchedCompression = false; importer.SetTextureSettings(overrideTextureImporterSettings); importer.SetPlatformTextureSettings(overrideDefaultPlatformSettings); importer.SetPlatformTextureSettings(overrideTargetPlatformSettings); AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); ret = texture.GetPixels(0); if (toLinear != false && exrToLinear != false) { for (int i0 = 0; i0 < ret.Length; ++i0) { #if true ret[i0].r = Mathf.Pow(ret[i0].r, 2.2f); ret[i0].g = Mathf.Pow(ret[i0].g, 2.2f); ret[i0].b = Mathf.Pow(ret[i0].b, 2.2f); #else ret[i0].r = (float)((int)(Mathf.Pow(ret[i0].r, 2.2f) * 255.0f) / 255.0f); ret[i0].g = (float)((int)(Mathf.Pow(ret[i0].g, 2.2f) * 255.0f) / 255.0f); ret[i0].b = (float)((int)(Mathf.Pow(ret[i0].b, 2.2f) * 255.0f) / 255.0f); #endif } } importer.SetTextureSettings(textureImporterSettings); importer.SetPlatformTextureSettings(defaultPlatformSettings); importer.SetPlatformTextureSettings(targetPlatformSettings); AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); } return(ret); }
public override void OnInspectorGUI() { TexImport remove = null; foreach (TexImport s in settings) { if (EditorUI.DrawHeader(s.path)) { EditorUI.BeginContents(); GUILayout.BeginHorizontal(); Object obj = AssetDatabase.LoadAssetAtPath(s.path, typeof(Object)); if (EditorGUILayoutEx.ObjectField <Object>(ref obj, false)) { if (obj != null) { s.path = AssetDatabase.GetAssetPath(obj); } else { s.path = string.Empty; } } if (GUILayout.Button("-", GUILayout.Width(20))) { remove = s; } GUILayout.EndHorizontal(); TextureImporterSettings setting = s.setting; EditorGUILayoutEx.Toggle("Apply", ref s.apply); GUI.enabled = s.apply; TextureImporterType[] imTypes = new TextureImporterType[] { // remove deprecated TextureImporterType.Default, TextureImporterType.Sprite, TextureImporterType.GUI, TextureImporterType.SingleChannel, TextureImporterType.NormalMap, TextureImporterType.Lightmap, TextureImporterType.Cursor, TextureImporterType.Cookie, }; var texType = s.setting.textureType; if (EditorGUILayoutEx.PopupEnum <TextureImporterType>("Import Type", ref texType, imTypes)) { setting.ApplyTextureType(texType); } EditorGUILayoutEx.PopupEnum <TextureImporterFormat>("Texture Format", ref s.format); if (s.setting.textureType == TextureImporterType.Sprite) { DrawSpriteMenu(s); } else { setting.wrapMode = (TextureWrapMode)EditorGUILayout.EnumPopup("Texture WrapMode", setting.wrapMode); setting.filterMode = (FilterMode)EditorGUILayout.EnumPopup("Filter Mode", setting.filterMode); setting.readable = EditorGUILayout.Toggle("Readable", setting.readable); setting.mipmapEnabled = EditorGUILayout.Toggle("Generate Mip Maps", setting.mipmapEnabled); if (setting.mipmapEnabled) { EditorGUI.indentLevel += 2; setting.borderMipmap = EditorGUILayout.Toggle("Border MipMaps", setting.borderMipmap); setting.mipmapFilter = (TextureImporterMipFilter)EditorGUILayout.EnumPopup("MipMap Filtering", setting.mipmapFilter); setting.fadeOut = EditorGUILayout.Toggle("FadeOut MipMaps", setting.fadeOut); setting.mipmapBias = EditorGUILayout.FloatField("MipMap Bias", setting.mipmapBias); setting.mipmapFadeDistanceStart = EditorGUILayout.IntField("MipMap Fade Distance Start", setting.mipmapFadeDistanceStart); setting.mipmapFadeDistanceEnd = EditorGUILayout.IntField("MipMap Fade Distance End", setting.mipmapFadeDistanceEnd); EditorGUI.indentLevel -= 2; } DrawSpriteMenu(s); setting.alphaIsTransparency = EditorGUILayout.Toggle("AlphaIsTransparency", setting.alphaIsTransparency); setting.aniso = EditorGUILayout.IntField("Aniso Level", setting.aniso).Clamp(1, 9); setting.convertToNormalMap = EditorGUILayout.Toggle("Convert To NormalMap", setting.convertToNormalMap); setting.generateCubemap = (TextureImporterGenerateCubemap)EditorGUILayout.EnumPopup("Generate CubeMap", setting.generateCubemap); setting.heightmapScale = EditorGUILayout.FloatField("HightMap Scale", setting.heightmapScale); setting.normalMapFilter = (TextureImporterNormalFilter)EditorGUILayout.EnumPopup("Filter Mode", setting.normalMapFilter); setting.npotScale = (TextureImporterNPOTScale)EditorGUILayout.EnumPopup("Non Power of 2", setting.npotScale); int maxSize = s.maxTexSize; if (EditorGUILayoutEx.Popup <int>("Max Size", ref maxSize, new int[] { 32, 64, 128, 256, 512, 1024, 2048, 4096 })) { s.maxTexSize = maxSize; } } EditorUI.EndContents(); GUI.enabled = true; } } if (remove != null) { settings.Remove(remove); } }
private static Sprite SaveAsset(PsdLayer psdLayer, TextureImporterSettings psdUnityImport, Texture2D texture, ImportUserData importSettings, ImportLayerData layerSettings) { // Generate the file path for this layer string fileDir; string filepath = GetFilePath(psdLayer, importSettings, out fileDir); // Create the folder if non existent if (AssetDatabase.IsValidFolder(fileDir) == false) { var subPaths = fileDir.Split('/'); string parentFolder = subPaths[0]; foreach (string folder in subPaths.Skip(1)) { string targetFolder = string.Format("{0}/{1}", parentFolder, folder); if (AssetDatabase.IsValidFolder(targetFolder) == false) { AssetDatabase.CreateFolder(parentFolder, folder); } parentFolder = targetFolder; } } // Write out the texture contents into the file AssetDatabase.ExtractAsset(texture, filepath); byte[] buf = texture.EncodeToPNG(); File.WriteAllBytes(filepath, buf); AssetDatabase.ImportAsset(filepath, ImportAssetOptions.ForceUpdate); Texture2D textureObj = AssetDatabase.LoadAssetAtPath <Texture2D>(filepath); // Get the texture importer for the asset TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(filepath); // Read out the texture import settings so settings can be changed TextureImporterSettings texSetting = new TextureImporterSettings(); textureImporter.ReadTextureSettings(texSetting); float finalPPU = psdUnityImport.spritePixelsPerUnit; switch (layerSettings.ScaleFactor) { case ScaleFactor.Half: finalPPU /= 2; break; case ScaleFactor.Quarter: finalPPU /= 4; break; } // Change settings texSetting.spriteAlignment = (int)layerSettings.Alignment; texSetting.spritePivot = layerSettings.Pivot; texSetting.spritePixelsPerUnit = finalPPU; texSetting.filterMode = psdUnityImport.filterMode; texSetting.wrapMode = psdUnityImport.wrapMode; texSetting.textureType = TextureImporterType.Sprite; texSetting.spriteMode = (int)SpriteImportMode.Single; texSetting.mipmapEnabled = false; texSetting.alphaIsTransparency = true; texSetting.npotScale = TextureImporterNPOTScale.None; // Set the rest of the texture settings textureImporter.spritePackingTag = importSettings.PackingTag; // Write in the texture import settings textureImporter.SetTextureSettings(texSetting); EditorUtility.SetDirty(textureObj); AssetDatabase.WriteImportSettingsIfDirty(filepath); AssetDatabase.ImportAsset(filepath, ImportAssetOptions.ForceUpdate); return((Sprite)AssetDatabase.LoadAssetAtPath(filepath, typeof(Sprite))); }
public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs) { List <DefaultPackerPolicy.Entry> list = new List <DefaultPackerPolicy.Entry>(); string text = ""; if (target != BuildTarget.NoTarget) { text = BuildPipeline.GetBuildTargetName(target); } for (int i = 0; i < textureImporterInstanceIDs.Length; i++) { int instanceID = textureImporterInstanceIDs[i]; TextureImporter textureImporter = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter; TextureFormat textureFormat; ColorSpace colorSpace; int num; textureImporter.ReadTextureImportInstructions(target, out textureFormat, out colorSpace, out num); TextureImporterSettings textureImporterSettings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(textureImporterSettings); bool flag = text != "" && this.HasPlatformEnabledAlphaSplittingForCompression(text, textureImporter); Sprite[] array = (from x in AssetDatabase.LoadAllAssetRepresentationsAtPath(textureImporter.assetPath) select x as Sprite into x where x != null select x).ToArray <Sprite>(); Sprite[] array2 = array; for (int j = 0; j < array2.Length; j++) { Sprite sprite = array2[j]; DefaultPackerPolicy.Entry entry = new DefaultPackerPolicy.Entry(); entry.sprite = sprite; entry.settings.format = textureFormat; entry.settings.colorSpace = colorSpace; entry.settings.compressionQuality = ((!TextureUtil.IsCompressedTextureFormat(textureFormat)) ? 0 : num); entry.settings.filterMode = ((!Enum.IsDefined(typeof(FilterMode), textureImporter.filterMode)) ? FilterMode.Bilinear : textureImporter.filterMode); entry.settings.maxWidth = 2048; entry.settings.maxHeight = 2048; entry.settings.generateMipMaps = textureImporter.mipmapEnabled; entry.settings.enableRotation = this.AllowRotationFlipping; entry.settings.allowsAlphaSplitting = (TextureImporter.IsTextureFormatETC1Compression(textureFormat) && flag); if (textureImporter.mipmapEnabled) { entry.settings.paddingPower = 3u; } else { entry.settings.paddingPower = (uint)EditorSettings.spritePackerPaddingPower; } entry.atlasName = this.ParseAtlasName(textureImporter.spritePackingTag); entry.packingMode = this.GetPackingMode(textureImporter.spritePackingTag, textureImporterSettings.spriteMeshType); entry.anisoLevel = textureImporter.anisoLevel; list.Add(entry); } Resources.UnloadAsset(textureImporter); } IEnumerable <IGrouping <string, DefaultPackerPolicy.Entry> > enumerable = from e in list group e by e.atlasName; foreach (IGrouping <string, DefaultPackerPolicy.Entry> current in enumerable) { int num2 = 0; IEnumerable <IGrouping <AtlasSettings, DefaultPackerPolicy.Entry> > enumerable2 = from t in current group t by t.settings; foreach (IGrouping <AtlasSettings, DefaultPackerPolicy.Entry> current2 in enumerable2) { string text2 = current.Key; if (enumerable2.Count <IGrouping <AtlasSettings, DefaultPackerPolicy.Entry> >() > 1) { text2 += string.Format(" (Group {0})", num2); } AtlasSettings key = current2.Key; key.anisoLevel = 1; if (key.generateMipMaps) { foreach (DefaultPackerPolicy.Entry current3 in current2) { if (current3.anisoLevel > key.anisoLevel) { key.anisoLevel = current3.anisoLevel; } } } job.AddAtlas(text2, key); foreach (DefaultPackerPolicy.Entry current4 in current2) { job.AssignToAtlas(text2, current4.sprite, current4.packingMode, SpritePackingRotation.None); } num2++; } } }
public void AddComponents(int layerIndex, GameObject imageObject, Sprite sprite, TextureImporterSettings settings) { var uiImg = imageObject.AddComponent <Image>(); uiImg.sprite = sprite; uiImg.SetNativeSize(); uiImg.rectTransform.SetAsFirstSibling(); Vector2 sprPivot = PsdBuilder.GetPivot(settings); uiImg.rectTransform.pivot = sprPivot; }
public virtual void ShowImportSettings(Editor baseEditor, TextureImportPlatformSettings platformSettings) { TextureImporterInspector editor = baseEditor as TextureImporterInspector; // Max texture size EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.maxTextureSizeIsDifferent; int maxTextureSize = EditorGUILayout.IntPopup(maxSize.text, platformSettings.maxTextureSize, kMaxTextureSizeStrings, kMaxTextureSizeValues); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { platformSettings.SetMaxTextureSizeForAll(maxTextureSize); } // Resize Algorithm EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.resizeAlgorithmIsDifferent; int resizeAlgorithmVal = EditorGUILayout.IntPopup(resizeAlgorithm.text, (int)platformSettings.resizeAlgorithm, kResizeAlgorithmStrings, kResizeAlgorithmValues); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { platformSettings.SetResizeAlgorithmForAll((TextureResizeAlgorithm)resizeAlgorithmVal); } // Texture Compression using (new EditorGUI.DisabledScope(platformSettings.overridden && !platformSettings.isDefault)) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.textureCompressionIsDifferent || (platformSettings.overridden && !platformSettings.isDefault); TextureImporterCompression textureCompression = (TextureImporterCompression)EditorGUILayout.IntPopup(kTextureCompression, (int)platformSettings.textureCompression, kTextureCompressionOptions, kTextureCompressionValues); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { platformSettings.SetTextureCompressionForAll(textureCompression); } } // Texture format int[] formatValuesForAll = null; string[] formatStringsForAll = null; bool formatOptionsAreDifferent = false; int formatForAll = 0; for (int i = 0; i < editor.targets.Length; i++) { TextureImporter imp = editor.targets[i] as TextureImporter; TextureImporterSettings settings = platformSettings.GetSettings(imp); TextureImporterType textureTypeForThis = editor.textureTypeHasMultipleDifferentValues ? settings.textureType : editor.textureType; int format = (int)platformSettings.format; int[] formatValues = null; string[] formatStrings = null; if (platformSettings.isDefault) { format = (int)TextureImporterFormat.Automatic; formatValues = new int[] { (int)TextureImporterFormat.Automatic }; formatStrings = new string[] { "Auto" }; } else { // If not overriden, show what the auto format is going to be if (!platformSettings.overridden) { format = (int)TextureImporter.FormatFromTextureParameters(settings, platformSettings.platformTextureSettings, editor.assetTarget && imp.DoesSourceTextureHaveAlpha(), editor.assetTarget && imp.IsSourceTextureHDR(), platformSettings.m_Target); formatValues = new int[] { format }; formatStrings = new string[] { TextureUtil.GetTextureFormatString((TextureFormat)format) }; } // else show the format choice filtered by platform. else { // Single channel format is the same for all platform at the moment if (textureTypeForThis == TextureImporterType.Cookie || textureTypeForThis == TextureImporterType.SingleChannel) { formatValues = TextureImportPlatformSettings.kTextureFormatsValueSingleChannel; formatStrings = TextureImporterInspector.s_TextureFormatStringsSingleChannel; } else { // on gles targets we use rgb normal maps so no need to split formats if (TextureImporterInspector.IsGLESMobileTargetPlatform(platformSettings.m_Target)) { if (platformSettings.m_Target == BuildTarget.iOS || platformSettings.m_Target == BuildTarget.tvOS) { formatValues = TextureImportPlatformSettings.kTextureFormatsValueApplePVR; formatStrings = TextureImporterInspector.s_TextureFormatStringsApplePVR; } else { formatValues = TextureImportPlatformSettings.kTextureFormatsValueAndroid; formatStrings = TextureImporterInspector.s_TextureFormatStringsAndroid; } } else if (textureTypeForThis == TextureImporterType.NormalMap) { formatValues = TextureImportPlatformSettings.kNormalFormatsValueDefault; formatStrings = TextureImporterInspector.s_NormalFormatStringsDefault; } else { if (platformSettings.m_Target == BuildTarget.WebGL) { formatValues = TextureImportPlatformSettings.kTextureFormatsValueWebGL; formatStrings = TextureImporterInspector.s_TextureFormatStringsWebGL; } else if (platformSettings.m_Target == BuildTarget.PSP2) { formatValues = TextureImportPlatformSettings.kTextureFormatsValuePSP2; formatStrings = TextureImporterInspector.s_TextureFormatStringsPSP2; } else if (platformSettings.m_Target == BuildTarget.Switch) { formatValues = TextureImportPlatformSettings.kTextureFormatsValueSwitch; formatStrings = TextureImporterInspector.s_TextureFormatStringsSwitch; } else { formatValues = TextureImportPlatformSettings.kTextureFormatsValueDefault; formatStrings = TextureImporterInspector.s_TextureFormatStringsDefault; } } } } } // Check if values are the same if (i == 0) { formatValuesForAll = formatValues; formatStringsForAll = formatStrings; formatForAll = format; } else { if (!formatValues.SequenceEqual(formatValuesForAll) || !formatStrings.SequenceEqual(formatStringsForAll)) { formatOptionsAreDifferent = true; break; } } } using (new EditorGUI.DisabledScope(formatOptionsAreDifferent || formatStringsForAll.Length == 1)) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = formatOptionsAreDifferent || platformSettings.textureFormatIsDifferent; formatForAll = EditorGUILayout.IntPopup(TextureImporterInspector.s_Styles.textureFormat, formatForAll, EditorGUIUtility.TempContent(formatStringsForAll), formatValuesForAll); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { platformSettings.SetTextureFormatForAll((TextureImporterFormat)formatForAll); } // In case the platform is overriden, the chosen format can become invalid when changing texture type (example: Switching from "Default" overridden with RGBAHalf to "Single Channel" where only Alpha8 is available) if (Array.IndexOf(formatValuesForAll, formatForAll) == -1) { platformSettings.SetTextureFormatForAll((TextureImporterFormat)formatValuesForAll[0]); } } if (platformSettings.isDefault && platformSettings.textureCompression != TextureImporterCompression.Uncompressed) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.crunchedCompressionIsDifferent; bool crunchedCompression = EditorGUILayout.Toggle(TextureImporterInspector.s_Styles.crunchedCompression, platformSettings.crunchedCompression); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { platformSettings.SetCrunchedCompressionForAll(crunchedCompression); } } // compression quality bool isCrunchedFormat = false || (TextureImporterFormat)formatForAll == TextureImporterFormat.DXT1Crunched || (TextureImporterFormat)formatForAll == TextureImporterFormat.DXT5Crunched || (TextureImporterFormat)formatForAll == TextureImporterFormat.ETC_RGB4Crunched || (TextureImporterFormat)formatForAll == TextureImporterFormat.ETC2_RGBA8Crunched ; if ( (platformSettings.isDefault && platformSettings.textureCompression != TextureImporterCompression.Uncompressed && platformSettings.crunchedCompression) || (!platformSettings.isDefault && isCrunchedFormat) || (!platformSettings.textureFormatIsDifferent && ArrayUtility.Contains <TextureImporterFormat>(TextureImporterInspector.kFormatsWithCompressionSettings, (TextureImporterFormat)formatForAll))) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.compressionQualityIsDifferent; int compressionQuality = EditCompressionQuality(platformSettings.m_Target, platformSettings.compressionQuality, isCrunchedFormat); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) { platformSettings.SetCompressionQualityForAll(compressionQuality); //SyncPlatformSettings (); } } // show the ETC1 split option only for sprites on platforms supporting ETC. bool isETCPlatform = TextureImporter.IsETC1SupportedByBuildTarget(BuildPipeline.GetBuildTargetByName(platformSettings.name)); bool isDealingWithSprite = (editor.spriteImportMode != SpriteImportMode.None); bool isETCFormatSelected = TextureImporter.IsTextureFormatETC1Compression((TextureFormat)formatForAll); if (isETCPlatform && isDealingWithSprite && isETCFormatSelected) { EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = platformSettings.overriddenIsDifferent || platformSettings.allowsAlphaSplitIsDifferent; bool allowsAlphaSplit = GUILayout.Toggle(platformSettings.allowsAlphaSplitting, TextureImporterInspector.s_Styles.etc1Compression); if (EditorGUI.EndChangeCheck()) { platformSettings.SetAllowsAlphaSplitForAll(allowsAlphaSplit); } } }
public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs) { List<Entry> entries = new List<Entry>(); foreach (int instanceID in textureImporterInstanceIDs) { TextureImporter ti = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter; var texture = AssetDatabase.LoadAssetAtPath(ti.assetPath, typeof(Texture2D)) as Texture2D; int paddingPower = ComputePaddingPower(texture); #if UNITY_4_6 || UNITY_4_7 TextureImportInstructions ins = new TextureImportInstructions(); ti.ReadTextureImportInstructions(ins, target); #else // Unity 5 ColorSpace colorSpace; int compression; TextureFormat format; ti.ReadTextureImportInstructions(target, out format, out colorSpace, out compression); TextureImporterSettings tis = new TextureImporterSettings(); ti.ReadTextureSettings(tis); #endif Sprite[] sprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(ti.assetPath).Select(x => x as Sprite).Where(x => x != null).ToArray(); foreach (Sprite sprite in sprites) { Entry entry = new Entry(); entry.sprite = sprite; #if UNITY_4_6 || UNITY_4_7 entry.settings.format = ins.desiredFormat; entry.settings.usageMode = TextureUsageMode.Default; entry.settings.colorSpace = ins.colorSpace; entry.settings.compressionQuality = ins.compressionQuality; #else // Unity 5 entry.settings.format = format; entry.settings.colorSpace = colorSpace; entry.settings.compressionQuality = compression; #endif entry.settings.filterMode = Enum.IsDefined(typeof(FilterMode), ti.filterMode) ? ti.filterMode : FilterMode.Bilinear; entry.settings.maxWidth = 2048; entry.settings.maxHeight = 2048; entry.settings.generateMipMaps = ti.mipmapEnabled; //if (ti.mipmapEnabled) entry.paddingPower = (uint)paddingPower; // using padding power group as a hack to group sprites with similar padding power entry.settings.paddingPower = PaddingPowerGroup(paddingPower); Debug.Log("Groupping " + paddingPower + " to " + entry.settings.paddingPower); entry.atlasName = ParseAtlasName(ti.spritePackingTag); entry.packingMode = SpritePackingMode.Rectangle; entry.anisoLevel = ti.anisoLevel; entries.Add(entry); } Resources.UnloadAsset(ti); Resources.UnloadAsset(texture); } // First split sprites into groups based on atlas name var atlasGroups = from e in entries group e by e.atlasName; foreach (var atlasGroup in atlasGroups) { int page = 0; // Then split those groups into smaller groups based on texture settings var settingsGroup = from t in atlasGroup group t by t.settings; foreach (var settingGroup in settingsGroup) { string atlasName = atlasGroup.Key; if (page > 0) atlasName += string.Format(" (Group {0})", page); AtlasSettings settings = settingGroup.Key; settings.anisoLevel = 1; // Use the highest aniso level from all entries in this atlas if (settings.generateMipMaps) foreach (Entry entry in settingGroup) if (entry.anisoLevel > settings.anisoLevel) settings.anisoLevel = entry.anisoLevel; // apply now the padding power because grouping would fail earlier uint biggest = BiggestPadding(settingGroup); settings.paddingPower = biggest; job.AddAtlas(atlasName, settings); foreach (Entry entry in settingGroup) { job.AssignToAtlas(atlasName, entry.sprite, SpritePackingMode.Rectangle, SpritePackingRotation.None); } ++page; } } }
internal static TextureFlags GetTextureFlags(TextureImporterSettings textImporter, UnityEngine.Texture2D texture) { TextureFlags flags = 0; // Handle Atlas. It does not have an Importer for now. if (textImporter == null) { flags |= TextureFlags.UClamp; flags |= TextureFlags.VClamp; flags |= TextureFlags.Point; return(flags); } switch (textImporter.wrapModeU) { case UnityEngine.TextureWrapMode.Clamp: flags |= TextureFlags.UClamp; break; case UnityEngine.TextureWrapMode.Mirror: flags |= TextureFlags.UMirror; break; case UnityEngine.TextureWrapMode.Repeat: flags |= TextureFlags.URepeat; break; } switch (textImporter.wrapModeV) { case UnityEngine.TextureWrapMode.Clamp: flags |= TextureFlags.VClamp; break; case UnityEngine.TextureWrapMode.Mirror: flags |= TextureFlags.VMirror; break; case UnityEngine.TextureWrapMode.Repeat: flags |= TextureFlags.URepeat; break; } if (textImporter.filterMode == UnityEngine.FilterMode.Point) { flags |= TextureFlags.Point; } if (textImporter.filterMode == UnityEngine.FilterMode.Trilinear) { flags |= TextureFlags.Trilinear; } if (textImporter.mipmapEnabled) { flags |= TextureFlags.MimapEnabled; } if (textImporter.sRGBTexture) { flags |= TextureFlags.Srgb; } if (textImporter.textureType == TextureImporterType.NormalMap) { flags |= TextureFlags.IsNormalMap; } if (!IsPowerOfTwo(texture)) { if ((flags & TextureFlags.MimapEnabled) == TextureFlags.MimapEnabled) { throw new ArgumentException($"Mipmapping is incompatible with NPOT textures. Update texture: {texture.name} to be power of two or disable mipmaps on it."); } else if ((flags & TextureFlags.UClamp) != TextureFlags.UClamp || (flags & TextureFlags.VClamp) != TextureFlags.VClamp) { throw new ArgumentException($"NPOT textures must use clamp wrap mode. Update texture: {texture.name} to be power of two or use clamp mode on it."); } } return(flags); }
void OnPostprocessTexture(Texture2D texture) { string atlasName = new DirectoryInfo(Path.GetDirectoryName(assetPath)).Name; TextureImporter importer = assetImporter as TextureImporter; if (assetPath.IndexOf("/fx/") >= 0 || assetPath.ToLower().IndexOf("emoji") > 0) { return; } if (assetPath.IndexOf("/TextureAlphaAtlas/") >= 0) { // if (!textureDicCount.ContainsKey (assetPath)) { // textureDicCount.Add (assetPath, 0); // } // if (textureDicCount [assetPath] >= 2) { // return; // } // int count = textureDicCount [assetPath]; // textureDicCount [assetPath] = count++; importer.textureType = TextureImporterType.Default; importer.mipmapEnabled = false; importer.mipMapBias = 0; importer.borderMipmap = false; importer.isReadable = false; importer.npotScale = TextureImporterNPOTScale.None; importer.textureType = TextureImporterType.Default; importer.filterMode = FilterMode.Bilinear; importer.SetPlatformTextureSettings("Standalone", 1024, TextureImporterFormat.AutomaticCompressed); importer.SetPlatformTextureSettings("Android", 1024, TextureImporterFormat.AutomaticCompressed); importer.SetPlatformTextureSettings("iPhone", 1024, TextureImporterFormat.RGB16); //PVRTC_RGB4 TextureImporterSettings tt = new TextureImporterSettings(); importer.ReadTextureSettings(tt); importer.SetTextureSettings(tt); return; } if (assetPath.IndexOf("/AddOns/") >= 0 || assetPath.IndexOf("/CustomImages/") >= 0 || assetPath.IndexOf("/Resources/") >= 0 || assetPath.IndexOf("/Design/") >= 0 || assetPath.IndexOf("/NewWorldMapWindow/") >= 0) { return; } if (ignoreFileList == null) { readIgnoreFiles(); } if (assetPath.Contains("Game/Assets/Textures")) { importer.textureType = TextureImporterType.Default; importer.mipmapEnabled = false; importer.mipMapBias = 0; importer.borderMipmap = false; importer.mipmapFadeDistanceStart = 0; importer.mipmapFadeDistanceEnd = 0; importer.mipMapsPreserveCoverage = false; importer.androidETC2FallbackOverride = AndroidETC2FallbackOverride.Quality16Bit; int maxWidth = 2048; TextureImporterSettings tt2 = new TextureImporterSettings(); importer.ReadTextureSettings(tt2); if (importer.maxTextureSize == 1024) { maxWidth = 1024; importer.npotScale = TextureImporterNPOTScale.ToLarger; importer.filterMode = FilterMode.Point; } else { maxWidth = 2048; importer.npotScale = TextureImporterNPOTScale.ToLarger; importer.filterMode = FilterMode.Bilinear; } if (importer.alphaIsTransparency) { importer.SetPlatformTextureSettings("Standalone", maxWidth, TextureImporterFormat.RGBA32); importer.SetPlatformTextureSettings("Android", maxWidth, TextureImporterFormat.ETC2_RGBA8, false); } else { importer.SetPlatformTextureSettings("Standalone", maxWidth, TextureImporterFormat.RGB24); importer.SetPlatformTextureSettings("Android", maxWidth, TextureImporterFormat.ETC_RGB4, false); } TextureImporterPlatformSettings iosSettings = importer.GetPlatformTextureSettings("iPhone"); if (iosSettings.format != TextureImporterFormat.RGBA16 && iosSettings.format != TextureImporterFormat.RGB16) { if (importer.alphaIsTransparency) { importer.SetPlatformTextureSettings("iPhone", maxWidth, TextureImporterFormat.PVRTC_RGBA4); } else { importer.SetPlatformTextureSettings("iPhone", maxWidth, TextureImporterFormat.PVRTC_RGB4); } } else { //importer.SetPlatformTextureSettings ("iPhone", maxWidth, TextureImporterFormat.RGBA16); } TextureImporterSettings tt = new TextureImporterSettings(); importer.ReadTextureSettings(tt); importer.SetTextureSettings(tt); return; } else { importer.maxTextureSize = 1024; } importer.spritePackingTag = atlasName; //先不要 if (assetPath.IndexOf("img_b_Noneg") < 0) { importer.spriteImportMode = SpriteImportMode.Single; importer.filterMode = FilterMode.Bilinear; importer.borderMipmap = false; importer.crunchedCompression = false; importer.isReadable = false; importer.mipmapEnabled = false; importer.npotScale = TextureImporterNPOTScale.None; importer.sRGBTexture = true; importer.textureCompression = TextureImporterCompression.Compressed; importer.textureShape = TextureImporterShape.Texture2D; importer.textureType = TextureImporterType.Sprite; if (importer.alphaIsTransparency) { importer.SetPlatformTextureSettings("Standalone", importer.maxTextureSize, TextureImporterFormat.RGBA32); } else { importer.SetPlatformTextureSettings("Standalone", importer.maxTextureSize, TextureImporterFormat.RGBA32); } // importer.SetPlatformTextureSettings ("Standalone", importer.maxTextureSize, TextureImporterFormat.DXT5Crunched); importer.SetPlatformTextureSettings("Android", importer.maxTextureSize, TextureImporterFormat.ETC2_RGBA8, true); if ((assetPath.IndexOf("PublicResources") >= 0) && EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS) { importer.SetPlatformTextureSettings("iPhone", importer.maxTextureSize, TextureImporterFormat.PVRTC_RGBA4); //PVRTC_RGBA4 } else { TextureImporterPlatformSettings iosSettings = importer.GetPlatformTextureSettings("iPhone"); if (iosSettings.format != TextureImporterFormat.RGBA32) { importer.SetPlatformTextureSettings("iPhone", importer.maxTextureSize, TextureImporterFormat.PVRTC_RGBA4); //PVRTC_RGBA4 } else { importer.SetPlatformTextureSettings("iPhone", importer.maxTextureSize, TextureImporterFormat.PVRTC_RGBA4); //PVRTC_RGBA4 } } TextureImporterSettings tt = new TextureImporterSettings(); importer.ReadTextureSettings(tt); tt.spriteMeshType = SpriteMeshType.FullRect; tt.mipmapEnabled = false; importer.SetTextureSettings(tt); } else { importer.textureType = TextureImporterType.Default; } //if (assetPath.IndexOf ("PublicResources") >= 0) { // string fileName = assetPath.Substring (assetPath.LastIndexOf ("/") + 1); // if (fileName.IndexOf ("U_") < 0) { // fileName = fileName.Substring (0, fileName.IndexOf (".")); // AssetDatabase.RenameAsset (assetPath, "U_" + fileName); // AssetDatabase.ImportAsset (assetPath); // } //} }
void OnPreprocessTexture() { // Trigger only for asset path that contains word "Sprite" if (assetPath.Contains("Sprite")) { Debug.Log("Processing texture " + assetImporter.assetPath); TextureImporter textureImporter = (TextureImporter)assetImporter; // Texture Type textureImporter.textureType = TextureImporterType.Sprite; // Texture Shape textureImporter.textureShape = TextureImporterShape.Texture2D; // Sprite Mode textureImporter.spriteImportMode = SpriteImportMode.Single; // Packing Tag textureImporter.spritePackingTag = "X"; // Pixels Per Unit textureImporter.spritePixelsPerUnit = 100; // Mesh type and a few others require access via settings objects. // Read the existing object here, then modify it and apply it back. TextureImporterSettings textureSettings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(textureSettings); // Mesh Type textureSettings.spriteMeshType = SpriteMeshType.FullRect; // Extrude Edges textureSettings.spriteExtrude = 13; // Generate Physics Shape textureSettings.spriteGenerateFallbackPhysicsShape = false; // Set back the customized TextureImporterSettings textureImporter.SetTextureSettings(textureSettings); // Pivot textureImporter.spritePivot = new Vector2(0.33f, 0.33f); // Advanced // sRGB (Color Texture) textureImporter.sRGBTexture = true; // Alpha Source textureImporter.alphaSource = TextureImporterAlphaSource.FromInput; // Alpha Is Transparency textureImporter.alphaIsTransparency = false; // Read/Write Enabled textureImporter.isReadable = true; // Generate Mip Maps textureImporter.mipmapEnabled = true; // Border Mip Maps textureImporter.borderMipmap = false; // Mip Map Filtering textureImporter.mipmapFilter = TextureImporterMipFilter.KaiserFilter; // Mip Maps Perserve Coverage textureImporter.mipMapsPreserveCoverage = false; /// Fadeout Mip Maps textureImporter.fadeout = true; // Fade Range textureImporter.mipmapFadeDistanceStart = 3; textureImporter.mipmapFadeDistanceEnd = 9; // Wrap Mode textureImporter.wrapMode = TextureWrapMode.Clamp; // Filter Mode textureImporter.filterMode = FilterMode.Bilinear; // Aniso Level textureImporter.anisoLevel = 1; // Default (the box in the bottom of the Inspector panel) textureImporter.SetPlatformTextureSettings(new TextureImporterPlatformSettings { // Max Size maxTextureSize = 32, // Resize Algorithm resizeAlgorithm = TextureResizeAlgorithm.Mitchell, // Format format = TextureImporterFormat.Automatic, // Compression textureCompression = TextureImporterCompression.CompressedHQ, // Use Crunch Compression crunchedCompression = true, // Compression quality compressionQuality = 75 }); textureImporter.SetPlatformTextureSettings(new TextureImporterPlatformSettings { // Use name to target specific platform settings name = "Standalone", // Override for PC, Mac & Linux Standalone overridden = true, // Max Size maxTextureSize = 32, // Resize Algorithm resizeAlgorithm = TextureResizeAlgorithm.Mitchell, // Format format = TextureImporterFormat.RGBA32 }); } }
// ---------------- private void DrawSpriteScraper() { // GUIStyles initialization. if (!areGUIStylesInitialized) { areGUIStylesInitialized = true; headerInfoStyle = new GUIStyle(EditorStyles.label); headerInfoStyle.alignment = TextAnchor.MiddleCenter; } // Sprite Scraper mode GUILayout.Space(5); EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); scraperMode = GUILayout.Toolbar(scraperMode, scraperModes, GUI.skin.button, GUI.ToolbarButtonSize.FitToContents, GUILayout.Height(25)); EditorGUILayout.EndHorizontal(); // Settings areSettingsUnfolded = EditorGUILayout.Foldout(areSettingsUnfolded, settingsGUI, true); if (areSettingsUnfolded) { EditorGUI.indentLevel++; // Save texture folder. EditorGUILayout.BeginHorizontal(); EditorGUILayout.TextField(saveTextureFolderGUI, saveTextureFolder); Rect _rect = EditorGUILayout.GetControlRect(false, 16, GUILayout.Width(16)); _rect.Set ( _rect.x - 2, _rect.y - 1, _rect.width + 2, _rect.height + 1 ); if (GUI.Button(_rect, GUIContent.none)) { string _folder = EditorUtility.OpenFolderPanel(textureFolderPanel, string.Empty, string.Empty); if (_folder.Contains(Application.dataPath)) { doDisplayInvalidFolderMessage = false; saveTextureFolder = _folder.Remove(0, Application.dataPath.Length - 6) + Path.AltDirectorySeparatorChar; } else { doDisplayInvalidFolderMessage = true; } } _rect.width = 30; _rect.x -= (_rect.width / 2) - 2; _rect.y += 1; EditorGUI.LabelField(_rect, EditorGUIUtility.IconContent(browseIconName)); EditorGUILayout.EndHorizontal(); if (doDisplayInvalidFolderMessage) { EditorGUILayout.HelpBox(invalidFolderMessage, MessageType.Error); } // Unlit material. unlitMaterial = (Material)EditorGUILayout.ObjectField(unlitMaterialGUI, unlitMaterial, typeof(Material), false); EditorGUI.indentLevel--; } if (!unlitMaterial) { EditorGUILayout.HelpBox(noUnlitMessage, MessageType.Warning); } GUILayout.Space(5); EditorGUI.DrawRect(EditorGUILayout.GetControlRect(false, 1), Color.grey); GUILayout.Space(5); templatesList.DoLayoutList(); // List cleaner buttons GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(cleanButton) && EditorUtility.DisplayDialog(confirmDialogTitle, cleanMessage, confirmDialogOK, confirmDialogCancel)) { templates.Clear(); } if (GUILayout.Button(removeUnusedButton) && EditorUtility.DisplayDialog(confirmDialogTitle, removeUnusedMessage, confirmDialogOK, confirmDialogCancel)) { for (int _i = 0; _i < templates.Count; _i++) { if (!templates[_i].IsSelected) { templates.RemoveAt(_i); _i--; } } } GUILayout.EndHorizontal(); // Merge scraps into beautiful artworks. if (GUILayout.Button(mergeScrapsGUI, GUILayout.MaxWidth(100), GUILayout.Height(25))) { #region Scraper if (templates.Count > 0) { doDisplayNoTemplateMessage = false; // Create and configure camera used to capture templates. Camera _renderCamera = new GameObject().AddComponent <Camera>(); Rect _viewport = new Rect(0, 0, 1, 1); _renderCamera.orthographic = true; _renderCamera.clearFlags = CameraClearFlags.SolidColor; _renderCamera.backgroundColor = Color.clear; _renderCamera.cullingMask = ~2; _renderCamera.allowDynamicResolution = true; Renderer[] _allRenderers = FindObjectsOfType <Renderer>(); GameObject[] _artworks = new GameObject[templates.Count]; int[] _artworksLayer = new int[templates.Count]; for (int _n = 0; _n < templates.Count; _n++) { if (!templates[_n].IsSelected || !templates[_n].Root) { continue; } SpriteTemplate _template = templates[_n]; SpriteRenderer[] _sprites = _template.Root.GetComponentsInChildren <SpriteRenderer>(); SpriteMask[] _masks = _template.Root.GetComponentsInChildren <SpriteMask>(); // Set template bounds volume entirely in camera view. Bounds _bounds = new Bounds(_sprites[0].bounds.center, _sprites[0].bounds.size); for (int _i = 1; _i < _sprites.Length; _i++) { _bounds.Encapsulate(_sprites[_i].bounds); } _renderCamera.orthographicSize = 5; _renderCamera.transform.position = new Vector3(_bounds.center.x, _bounds.center.y, _bounds.center.z - 10); while (!(_viewport.Contains(_renderCamera.WorldToViewportPoint(_bounds.min)) && _viewport.Contains(_renderCamera.WorldToViewportPoint(_bounds.max)))) { _renderCamera.orthographicSize++; } // Set all visible renderers on a different layer (not visible anymore). Plane[] _frustrumPlanes = GeometryUtility.CalculateFrustumPlanes(_renderCamera); Dictionary <GameObject, int> _renderers = new Dictionary <GameObject, int>(); for (int _i = 0; _i < _allRenderers.Length; _i++) { if (GeometryUtility.TestPlanesAABB(_frustrumPlanes, _allRenderers[_i].bounds) && !_sprites.Contains(_allRenderers[_i]) && !_masks.Contains(_allRenderers[_i]) && !_renderers.ContainsKey(_allRenderers[_i].gameObject)) { _renderers.Add(_allRenderers[_i].gameObject, _allRenderers[_i].gameObject.layer); _allRenderers[_i].gameObject.layer = 1; } } // Get artwork texture information and capture template. Vector2 _offset = _renderCamera.WorldToScreenPoint(_bounds.min); Vector2 _boundsSize = (Vector2)_renderCamera.WorldToScreenPoint(_bounds.max) - _offset; Vector2Int _size; if (_template.DoUsePowerOfTwoTexture) { _size = new Vector2Int(Mathf.NextPowerOfTwo((int)_boundsSize.x), Mathf.NextPowerOfTwo((int)_boundsSize.y)); } else { _size = new Vector2Int((int)_boundsSize.x, (int)_boundsSize.y); } RenderTexture _renderTexture = new RenderTexture(_renderCamera.pixelWidth, _renderCamera.pixelHeight, 32); RenderTexture.active = _renderTexture; _renderCamera.targetTexture = _renderTexture; // Set template sprites material to unlit if not baking light. Material[] _spritesMaterial = null; bool _doNotBakeLight = !_template.DoBakeLights && unlitMaterial; if (_doNotBakeLight) { _spritesMaterial = new Material[_sprites.Length]; for (int _i = 0; _i < _sprites.Length; _i++) { _spritesMaterial[_i] = _sprites[_i].sharedMaterial; _sprites[_i].material = unlitMaterial; } } _renderCamera.Render(); // Restore template sprites material. if (_doNotBakeLight) { for (int _i = 0; _i < _sprites.Length; _i++) { _sprites[_i].material = _spritesMaterial[_i]; } } // Reset renderers layer. foreach (KeyValuePair <GameObject, int> _renderer in _renderers) { _renderer.Key.layer = _renderer.Value; } // Create full transparent texture, then paint capture on it. var _capture = new Texture2D(_size.x, _size.y, TextureFormat.RGBA32, false); Color[] _colors = _capture.GetPixels(); for (int _i = 0; _i < _colors.Length; _i++) { _colors[_i] = Color.clear; } _capture.SetPixels(_colors); // Reversed Y starting position _capture.ReadPixels(new Rect(_offset.x, _renderCamera.pixelHeight - _offset.y - _boundsSize.y, _boundsSize.x, _boundsSize.y), 0, 0); _capture.Apply(); // Create artwork based on template. SpriteRenderer _artwork = new GameObject(_template.Root.name).AddComponent <SpriteRenderer>(); Vector2 _pivot = new Vector2((_boundsSize.x * .5f) / _size.x, 0); float _pixelPerUnit = _renderCamera.pixelHeight / (_renderCamera.orthographicSize * 2f); _artwork.gameObject.layer = 1; _artwork.sortingOrder = _template.OrderInLayer; _artwork.transform.position = new Vector3(_bounds.min.x + _bounds.extents.x, _bounds.min.y, _bounds.center.z); if (_template.Material) { _artwork.material = _template.Material; } _artworks[_n] = _artwork.gameObject; _artworksLayer[_n] = _template.Layer; // Save texture according to selected mode. if (scraperMode < 2) { string _path = Application.dataPath + saveTextureFolder.Remove(0, 6); if (!Directory.Exists(_path)) { Directory.CreateDirectory(_path); } // Get unique file path. _path += _artwork.name + textureExtension; if (File.Exists(_path)) { string _originalPath = _path.Insert(_path.Length - 4, "_"); int _number = 0; do { _path = _originalPath.Insert(_originalPath.Length - 4, _number.ToString()); _number++; } while (File.Exists(_path)); } // Save texture as PNG. File.WriteAllBytes(_path, _capture.EncodeToPNG()); _path = _path.Remove(0, Application.dataPath.Length - 6); AssetDatabase.ImportAsset(_path, ImportAssetOptions.ForceUpdate); TextureImporter _importer = (TextureImporter)AssetImporter.GetAtPath(_path); TextureImporterSettings _settings = new TextureImporterSettings(); _importer.textureType = TextureImporterType.Sprite; _importer.spritePixelsPerUnit = _pixelPerUnit; _importer.ReadTextureSettings(_settings); _settings.spriteAlignment = (int)SpriteAlignment.Custom; _importer.SetTextureSettings(_settings); _importer.spritePivot = _pivot; _importer.SaveAndReimport(); _artwork.sprite = AssetDatabase.LoadAssetAtPath <Sprite>(_path); } else { _artwork.sprite = Sprite.Create(_capture, new Rect(0, 0, _size.x, _size.y), _pivot, _pixelPerUnit); } } // Replace templates by artworks on new scene mode. if (scraperMode == 0) { for (int _i = 0; _i < _artworks.Length; _i++) { if (_artworks[_i] && templates[_i].Root) { _artworks[_i].transform.SetParent(templates[_i].Root.parent); try { DestroyImmediate(templates[_i].Root.gameObject); } catch (InvalidOperationException) { GameObject _prefabRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(templates[_i].Root.gameObject); PrefabUtility.UnpackPrefabInstance(_prefabRoot, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); DestroyImmediate(templates[_i].Root.gameObject); } } } // Save scene as new one. templates.Clear(); EditorApplication.ExecuteMenuItem(saveAsMenuPath); } // Set artowrks layer. for (int _i = 0; _i < _artworks.Length; _i++) { if (_artworks[_i]) { _artworks[_i].layer = _artworksLayer[_i]; } } // Clean capture tools. DestroyImmediate(_renderCamera.gameObject); RenderTexture.active = null; } else { doDisplayNoTemplateMessage = true; } #endregion } if (doDisplayNoTemplateMessage) { EditorGUILayout.HelpBox(noTemplateMessage, MessageType.Error); } }
private static Sprite ImportLayer(PsdDocument psdDoc, ImportUserData importSettings, ImportLayerData layerSettings, TextureImporterSettings psdUnityImport) { if (layerSettings == null) { return(null); } PsdLayer psdLayer = GetPsdLayerByIndex(psdDoc, layerSettings.indexId); if (psdLayer.IsGroup) { return(null); } // Generate the texture Texture2D layerTexture = GetLayerTexture(psdDoc, psdLayer, layerSettings); if (layerTexture == null) { return(null); } // Save the texture as an asset Sprite layerSprite = null; try { layerSprite = SaveAsset(psdLayer, psdUnityImport, layerTexture, importSettings, layerSettings); } catch { } return(layerSprite); }
static void Execute() { Object[] selectObject = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets); for (int index = 0; index < selectObject.Length; index++) { Object o = selectObject[index]; if (!(o is Texture2D)) { continue; } string path = AssetDatabase.GetAssetPath(o); string infoFile = path + ".info.txt"; //判断文件是否存在 if (AssetDatabase.LoadAssetAtPath(infoFile, typeof(object)) == null) { continue; } FileStream fs = new FileStream(infoFile, FileMode.Open); StreamReader sr = new StreamReader(fs); string line = sr.ReadLine(); //第一行注释 line = sr.ReadLine().Trim(); //第二行偏移信息 sr.Close(); fs.Close(); //删除信息文件 AssetDatabase.DeleteAsset(infoFile); string[] lineSplit = line.Split(','); float[] info = new float[4]; for (int i = 0; i < 4; i++) { info[i] = System.Convert.ToInt32(lineSplit[i]); } //中心点在(0, 0)表示不偏移 if (info[0] == 0 && info[1] == 0) { continue; } Vector2 spritePivot = new Vector2(); spritePivot.x = info[0] / info[2]; spritePivot.y = (info[3] - info[1]) / info[3]; TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter; TextureImporterSettings settings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(settings); settings.spriteAlignment = (int)SpriteAlignment.Custom; settings.spritePivot = spritePivot; settings.spritePixelsPerUnit = 1; textureImporter.SetTextureSettings(settings); AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); EditorUtility.DisplayProgressBar("Processing", path, 1.0f * index / selectObject.Length); } EditorUtility.ClearProgressBar(); }
private static ReconstructData GetReconstructData(PsdDocument psdDoc, string psdPath, Vector2 documentPivot, ImportUserData importSettings, ImportLayerData reconstructRoot) { // Get the texture import setting of the PSD TextureImporter psdUnitySettings = (TextureImporter)AssetImporter.GetAtPath(psdPath); TextureImporterSettings psdUnityImport = new TextureImporterSettings(); psdUnitySettings.ReadTextureSettings(psdUnityImport); Vector2 docSize = new Vector2(psdDoc.Width, psdDoc.Height); ReconstructData data = new ReconstructData(docSize, documentPivot, psdUnitySettings.spritePixelsPerUnit); reconstructRoot.Iterate( layerCallback: layer => { if (layer.import == false) { return; } var psdLayer = GetPsdLayerByIndex(psdDoc, layer.indexId); Rect layerBounds = new Rect() { xMin = psdLayer.Left, xMax = psdLayer.Right, yMin = psdDoc.Height - psdLayer.Bottom, yMax = psdDoc.Height - psdLayer.Top }; data.layerBoundsIndex.Add(layer.indexId, layerBounds); string layerDir; string layerPath = GetFilePath(psdLayer, importSettings, out layerDir); Sprite layerSprite = AssetDatabase.LoadAssetAtPath <Sprite>(layerPath); if (layerSprite == null) { layerSprite = ImportLayer(psdDoc, importSettings, layer, psdUnityImport); } Vector2 spriteAnchor = Vector2.zero; if (layerSprite != null) { TextureImporter layerImporter = (TextureImporter)AssetImporter.GetAtPath(layerPath); TextureImporterSettings layerSettings = new TextureImporterSettings(); layerImporter.ReadTextureSettings(layerSettings); if (layerSettings.spriteAlignment == (int)SpriteAlignment.Custom) { spriteAnchor = layerSettings.spritePivot; } else { spriteAnchor = AlignmentToPivot((SpriteAlignment)layerSettings.spriteAlignment); } } data.AddSprite(layer.indexId, layerSprite, spriteAnchor); }, canEnterGroup: checkGroup => checkGroup.import ); return(data); }
static bool CreateTilemapSprite(string targetPath, int cellWidth, int cellHeight, int pixelsPerUnit, TSX.Tileset tileset, string subSpriteNameBase, out Sprite[] tileSprites) { TextureImporter ti = AssetImporter.GetAtPath(targetPath) as TextureImporter; if (ti == null) { tileSprites = new Sprite[0]; Debug.LogError("Cannot find tilemap sprite file at " + targetPath); return(false); } TextureImporterSettings textureSettings = new TextureImporterSettings(); ti.ReadTextureSettings(textureSettings); SpriteMeshType meshType = SpriteMeshType.FullRect; SpriteAlignment alignment = SpriteAlignment.Custom; Vector2 pivot = new Vector2(0.5f, 0.5f); // For the whole tileset sprite, so not important FilterMode filterMode = FilterMode.Point; SpriteImportMode importMode = SpriteImportMode.Multiple; bool fallbackPhysicsShape = true; if (textureSettings.spritePixelsPerUnit != pixelsPerUnit || textureSettings.spriteMeshType != meshType || textureSettings.spriteAlignment != (int)alignment || textureSettings.spritePivot != pivot || textureSettings.filterMode != filterMode || textureSettings.spriteMode != (int)importMode || textureSettings.spriteGenerateFallbackPhysicsShape != fallbackPhysicsShape) { textureSettings.spritePixelsPerUnit = pixelsPerUnit; textureSettings.spriteMeshType = meshType; textureSettings.spriteAlignment = (int)alignment; textureSettings.spritePivot = pivot; textureSettings.filterMode = filterMode; textureSettings.spriteMode = (int)importMode; textureSettings.spriteGenerateFallbackPhysicsShape = fallbackPhysicsShape; ti.SetTextureSettings(textureSettings); int tileCount = tileset.GetTileCount(); List <SpriteMetaData> newData = new List <SpriteMetaData>(tileCount); int i = 0; for (int y = tileset.image.height - tileset.margin; (y - tileset.tileheight >= tileset.margin); y -= tileset.tileheight + tileset.spacing) { for (int x = tileset.margin; x + tileset.tilewidth <= tileset.image.width - tileset.margin; x += tileset.tilewidth + tileset.spacing) { SpriteMetaData data = new SpriteMetaData(); data.name = subSpriteNameBase + "_" + i; data.alignment = (int)alignment; data.pivot = GetPivot(tileset.tilewidth, tileset.tileheight, cellWidth, cellHeight); data.rect = new Rect(x, y - tileset.tileheight, tileset.tilewidth, tileset.tileheight); newData.Add(data); i++; if (i >= tileCount) { break; } } if (i >= tileCount) { break; } } ti.spritesheet = newData.ToArray(); EditorUtility.SetDirty(ti); ti.SaveAndReimport(); } Sprite[] subSprites = AssetDatabase.LoadAllAssetsAtPath(targetPath).OfType <Sprite>().ToArray(); // For some reason Unity thinks it's smart to return the sub-sprites in random order... // ...and provide no API for retrieving sub-sprites by index >_< // so we have to manually sort them by the ids in their names Array.Sort <Sprite>(subSprites, new SpriteComparer()); tileSprites = subSprites; return(true); }
public static void EncodeSingle(Texture2D texture, bool deleteOld, bool isPNG) { Texture2D origTexture = texture; var assetPath = AssetDatabase.GetAssetPath(origTexture); var importer = (TextureImporter)AssetImporter.GetAtPath(assetPath); bool needRevert = false; var tis = new TextureImporterSettings(); importer.ReadTextureSettings(tis); var compression = importer.textureCompression; var isBipmap = importer.mipmapEnabled; var isLinear = importer.sRGBTexture; if (!importer.isReadable) { needRevert = true; importer.isReadable = true; importer.SaveAndReimport(); AssetDatabase.Refresh(); } var pixels = origTexture.GetPixels(); var targetFormat = importer.DoesSourceTextureHaveAlpha() ? TextureFormat.ARGB32 : TextureFormat.RGB24; var newTxt = new Texture2D(origTexture.width, origTexture.height, targetFormat, isBipmap, isLinear); if (importer.textureType == TextureImporterType.NormalMap) { DTXnmColors(newTxt, pixels); } else { newTxt.SetPixels(pixels); } var buff = isPNG ? newTxt.EncodeToPNG() : newTxt.EncodeToJPG(JPGQualityLevel); var ext = isPNG ? ".png" : ".jpg"; var filePath = Path.GetDirectoryName(assetPath) + "/" + origTexture.name + (deleteOld ? ext : "_new" + ext); File.WriteAllBytes(filePath, buff); if (needRevert) { importer.isReadable = false; importer.SaveAndReimport(); } AssetDatabase.Refresh(); importer = (TextureImporter)AssetImporter.GetAtPath(filePath); if (importer != null) { importer.SetTextureSettings(tis); importer.textureCompression = compression; importer.SaveAndReimport(); AssetDatabase.Refresh(); } var newTexture = AssetDatabase.LoadAssetAtPath <Texture>(filePath); var oriCol = EditorGUIUtility.isProSkin ? "#00b300" : "#b300b3"; var toCol = EditorGUIUtility.isProSkin ? "#fc0" : "#03f"; if (newTexture == null) { Debug.Log("Waiting for new texture - " + Path.GetFileName(filePath)); } Debug.Log(string.Format("Encode <color={2}>{0}</color> to: <color={3}>{1}</color>", Path.GetFileName(assetPath), Path.GetFileName(filePath), oriCol, toCol), newTexture); // Replace in dependcies if (Sources.ContainsKey(origTexture)) { Debug.LogFormat("We found {0} materials realted to {1}.", Sources[origTexture].Count, origTexture); foreach (var material in Sources[origTexture]) { ReplaceDependcies(origTexture, newTexture as Texture2D, material); } Sources.Remove(origTexture); AssetDatabase.Refresh(); } Selection.activeObject = newTexture; if (!deleteOld) { return; } if (filePath == assetPath) { return; } Debug.Log("Deleting @" + assetPath); AssetDatabase.DeleteAsset(assetPath); AssetDatabase.Refresh(); }
public string ExportToFile(bool useCurrentFileName) { bool bIsInsideProject = true; string path; if (useCurrentFileName) { path = m_CurrentAsset.exportSettings.fileName; } else { string title = "Save Texture, use # for frame numbering."; string defaultFileName, extension; int count = m_ProcessingNodeStack.outputSequence.frames.Count; int numU = m_ProcessingNodeStack.outputSequence.numU; int numV = m_ProcessingNodeStack.outputSequence.numV; string defaultDir = Path.GetDirectoryName(AssetDatabase.GetAssetPath(m_CurrentAsset)); defaultFileName = m_CurrentAsset.name; if (count > 1) { defaultFileName += "_#"; } if (numU * numV != 1) { defaultFileName += "_" + numU + "x" + numV; } switch (m_CurrentAsset.exportSettings.exportMode) { case ImageSequence.ExportMode.EXR: defaultFileName += ".exr"; extension = "exr"; break; case ImageSequence.ExportMode.Targa: defaultFileName += ".tga"; extension = "tga"; break; case ImageSequence.ExportMode.PNG: defaultFileName += ".png"; extension = "png"; break; default: return(null); } path = EditorUtility.SaveFilePanel(title, defaultDir, defaultFileName, extension); if (path == null || path == "") { return(""); } if (path.Contains(Application.dataPath)) { path = path.Replace(Application.dataPath, "Assets"); } } if (!path.StartsWith("Assets/")) { bIsInsideProject = false; Debug.LogWarning("VFX Toolbox Warning : Saving a texture outside the project's scope. Import Settings will not be applied"); } int frameCount = m_ProcessingNodeStack.outputSequence.length; if (frameCount > 1 && !Path.GetFileNameWithoutExtension(path).Contains("#")) { if (!EditorUtility.DisplayDialog("VFX Toolbox", "You are currently exporting a sequence of images with no # in filename for numbering, do you want to add _# as a suffix of the filename?", "Add Postfix", "Cancel Export")) { return(""); } string newpath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + "_#" + Path.GetExtension(path); path = newpath; } ImageSequence.ExportSettings settings = m_CurrentAsset.exportSettings; bool bCanceled = false; try { int i = 1; foreach (ProcessingFrame frame in m_ProcessingNodeStack.outputSequence.frames) { if (VFXToolboxGUIUtility.DisplayProgressBar("Image Sequencer", "Exporting Frame #" + i + "/" + frameCount, (float)i / frameCount, 0, true)) { bCanceled = true; break; } // Export frame : first, dump data into color array Color[] inputs; if (frame.texture is Texture2D) // if using input frame { RenderTexture temp = RenderTexture.GetTemporary(frame.texture.width, frame.texture.height, 0, RenderTextureFormat.ARGBHalf); Graphics.Blit((Texture2D)frame.texture, temp); inputs = ReadBack(temp); } else // frame.texture is RenderTexture { frame.Process(); inputs = ReadBack((RenderTexture)frame.texture); } string fileName = GetNumberedFileName(path, i, frameCount); // Dump data byte[] bytes; switch (m_CurrentAsset.exportSettings.exportMode) { case ImageSequence.ExportMode.EXR: #if UNITY_5_6_OR_NEWER // New Exporter { Texture2D texture = new Texture2D(frame.texture.width, frame.texture.height, TextureFormat.RGBAHalf, settings.generateMipMaps, !settings.sRGB); texture.SetPixels(inputs); texture.Apply(true); bytes = texture.EncodeToEXR(); } #else // Old Exporter { bytes = MiniEXR.MiniEXR.MiniEXRWrite((ushort)frame.texture.width, (ushort)frame.texture.height, settings.exportAlpha, inputs, true); } #endif break; case ImageSequence.ExportMode.Targa: { bytes = MiniTGA.MiniTGAWrite((ushort)frame.texture.width, (ushort)frame.texture.height, settings.exportAlpha, inputs); } break; case ImageSequence.ExportMode.PNG: { Texture2D texture = new Texture2D(frame.texture.width, frame.texture.height, TextureFormat.RGBA32, settings.generateMipMaps, !settings.sRGB); texture.SetPixels(inputs); texture.Apply(true); bytes = texture.EncodeToPNG(); } break; default: { bytes = new byte[0] { }; // Empty file that should not happen } break; } File.WriteAllBytes(fileName, bytes); AssetDatabase.Refresh(); // Process Import if saved inside project if (bIsInsideProject) { TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(fileName); importer.wrapMode = m_CurrentAsset.exportSettings.wrapMode; importer.filterMode = m_CurrentAsset.exportSettings.filterMode; switch (m_CurrentAsset.exportSettings.dataContents) { case ImageSequence.DataContents.Color: importer.textureType = TextureImporterType.Default; break; case ImageSequence.DataContents.NormalMap: importer.textureType = TextureImporterType.NormalMap; importer.convertToNormalmap = false; break; case ImageSequence.DataContents.NormalMapFromGrayscale: importer.textureType = TextureImporterType.NormalMap; importer.convertToNormalmap = true; break; case ImageSequence.DataContents.Sprite: importer.textureType = TextureImporterType.Sprite; importer.spriteImportMode = SpriteImportMode.Multiple; importer.spritesheet = GetSpriteMetaData(frame, m_ProcessingNodeStack.outputSequence.numU, m_ProcessingNodeStack.outputSequence.numV); break; } TextureImporterSettings importerSettings = new TextureImporterSettings(); importer.ReadTextureSettings(importerSettings); if (m_CurrentAsset.exportSettings.outputShape == ImageSequence.OutputMode.Texture2DArray) { importerSettings.textureShape = TextureImporterShape.Texture2DArray; importerSettings.flipbookColumns = m_ProcessingNodeStack.outputSequence.numU; importerSettings.flipbookRows = m_ProcessingNodeStack.outputSequence.numV; } else if (m_CurrentAsset.exportSettings.outputShape == ImageSequence.OutputMode.Texture2D) { importerSettings.textureShape = TextureImporterShape.Texture2D; } importer.SetTextureSettings(importerSettings); importer.mipmapEnabled = m_CurrentAsset.exportSettings.generateMipMaps; switch (m_CurrentAsset.exportSettings.exportMode) { case ImageSequence.ExportMode.Targa: importer.sRGBTexture = m_CurrentAsset.exportSettings.sRGB; importer.alphaSource = m_CurrentAsset.exportSettings.exportAlpha ? TextureImporterAlphaSource.FromInput : TextureImporterAlphaSource.None; importer.textureCompression = m_CurrentAsset.exportSettings.compress ? TextureImporterCompression.Compressed : TextureImporterCompression.Uncompressed; break; case ImageSequence.ExportMode.EXR: importer.sRGBTexture = false; importer.alphaSource = (m_CurrentAsset.exportSettings.exportAlpha && !m_CurrentAsset.exportSettings.compress) ? TextureImporterAlphaSource.FromInput : TextureImporterAlphaSource.None; importer.textureCompression = m_CurrentAsset.exportSettings.compress ? TextureImporterCompression.CompressedHQ : TextureImporterCompression.Uncompressed; break; case ImageSequence.ExportMode.PNG: importer.sRGBTexture = m_CurrentAsset.exportSettings.sRGB; importer.alphaSource = m_CurrentAsset.exportSettings.exportAlpha ? TextureImporterAlphaSource.FromInput : TextureImporterAlphaSource.None; importer.textureCompression = m_CurrentAsset.exportSettings.compress ? TextureImporterCompression.Compressed : TextureImporterCompression.Uncompressed; break; } AssetDatabase.ImportAsset(fileName, ImportAssetOptions.ForceUpdate); } // Separate Alpha if (m_CurrentAsset.exportSettings.exportSeparateAlpha) { string alphaFilename = fileName.Substring(0, fileName.Length - 4) + "_alpha.tga"; // build alpha for (int k = 0; k < inputs.Length; k++) { float a = inputs[k].a; inputs[k] = new Color(a, a, a, a); } MiniTGA.MiniTGAWrite(alphaFilename, (ushort)frame.texture.width, (ushort)frame.texture.height, false, inputs); AssetDatabase.Refresh(); // Process Importer for alpha if inside project if (bIsInsideProject) { TextureImporter alphaImporter = (TextureImporter)TextureImporter.GetAtPath(alphaFilename); if (m_CurrentAsset.exportSettings.dataContents == ImageSequence.DataContents.Sprite) { alphaImporter.textureType = TextureImporterType.Sprite; alphaImporter.spriteImportMode = SpriteImportMode.Multiple; alphaImporter.spritesheet = GetSpriteMetaData(frame, m_ProcessingNodeStack.outputSequence.numU, m_ProcessingNodeStack.outputSequence.numV); alphaImporter.alphaSource = TextureImporterAlphaSource.None; } else { alphaImporter.textureType = TextureImporterType.SingleChannel; alphaImporter.alphaSource = TextureImporterAlphaSource.FromGrayScale; } alphaImporter.wrapMode = m_CurrentAsset.exportSettings.wrapMode; alphaImporter.filterMode = m_CurrentAsset.exportSettings.filterMode; alphaImporter.sRGBTexture = false; alphaImporter.mipmapEnabled = m_CurrentAsset.exportSettings.generateMipMaps; alphaImporter.textureCompression = m_CurrentAsset.exportSettings.compress ? TextureImporterCompression.Compressed : TextureImporterCompression.Uncompressed; AssetDatabase.ImportAsset(alphaFilename, ImportAssetOptions.ForceUpdate); } } i++; } } catch (System.Exception e) { VFXToolboxGUIUtility.ClearProgressBar(); Debug.LogError(e.Message); } VFXToolboxGUIUtility.ClearProgressBar(); if (bCanceled) { return(""); } else { return(path); } }
public static void BuildPsd(GameObject root, PSDLayerGroupInfo group, PsdExportSettings settings, PsdFileInfo fileInfo, SpriteAlignment align, IPsdConstructor constructor) { // Run the export on non exported layers PSDExporter.Export(settings, fileInfo, false); // Find all the layers being exported var exportLayers = PSDExporter.GetExportLayers(settings, fileInfo); // Stores the root object for each encountered group Dictionary <PSDLayerGroupInfo, GameObject> groupHeaders = new Dictionary <PSDLayerGroupInfo, GameObject>(); // Store the last parent, for traversal GameObject lastParent = root; GameObject rootBase = root; int groupVisibleMask = 1; int groupDepth = 0; // Loop through all the layers of the PSD file // backwards so they appear in the expected order // Going through all the layers, and not just the exported layers // so that the groups can be setup for (int i = group.end; i >= group.start; i--) { // Skip if layer is hidden if (fileInfo.LayerVisibility[i] == false) { continue; } var groupInfo = fileInfo.GetGroupByLayerIndex(i); bool inGroup = groupInfo != null; // Skip if layer belongs to a hidden group if (inGroup && groupInfo.visible == false) { continue; } // When inside a group... if (inGroup) { // Inverted because starting backwards bool startGroup = groupInfo.end == i; bool closeGroup = groupInfo.start == i; // Go up or down group depths if (startGroup) { groupDepth++; groupVisibleMask |= ((groupInfo.visible ? 1 : 0) << groupDepth); } if (closeGroup) { // Reset group visible flag when closing group groupVisibleMask &= ~(1 << groupDepth); groupDepth--; } // First, check if parents of this group is visible in the first place bool parentVisible = true; for (int parentMask = groupDepth - 1; parentMask > 0; parentMask--) { bool isVisible = (groupVisibleMask & (1 << parentMask)) > 0; parentVisible &= isVisible; } // Parents not visible, continue to next layer if (!parentVisible) { continue; } // Finally, check if layer being processed is start/end of group if (startGroup || closeGroup) { // If start or end of the group, call HandleGroupObject // which creates the group layer object and assignment of lastParent HandleGroupObject(groupInfo, groupHeaders, startGroup, constructor, ref lastParent); // A bunch of book keeping needs to be done at the start of a group if (startGroup) { // If this is the start of the group being constructed // store as the rootBase if (i == group.end) { rootBase = lastParent; } } // Start or end group doesn't have visible sprite object, skip to next layer continue; } } // End processing of group start/end // If got to here, processing a visual layer // Skip if the export layers list doesn't contain this index if (exportLayers.Contains(i) == false) { continue; } // If got here and root base hasn't been set, that's a problem if (rootBase == null) { throw new Exception("Trying to create image layer before root base has been set"); } // Get layer info Layer layer = settings.Psd.Layers[i]; // Create the game object for the sprite string layerName = Utility.PinYinHelper.Convert(layer.Name); GameObject spriteObject = constructor.CreateGameObject(layerName, lastParent); // Reparent created object to last parent if (lastParent != null) { spriteObject.transform.SetParent(lastParent.transform, false); } Vector2 spritePivot = GetPivot(SpriteAlignment.Center); if (layer.IsText) { var layerText = layer.LayerText; Text text = spriteObject.AddComponent <Text>(); text.horizontalOverflow = HorizontalWrapMode.Overflow; text.verticalOverflow = VerticalWrapMode.Overflow; if (!string.IsNullOrEmpty(PsdSetting.Instance.DefaultFontPath)) { text.font = AssetDatabase.LoadAssetAtPath <Font>(PsdSetting.Instance.DefaultFontPath); } text.fontStyle = GetFontStyle(layerText); text.fontSize = (int)layerText.FontSize; text.rectTransform.SetAsFirstSibling(); text.rectTransform.sizeDelta = new Vector2(layer.Rect.width, layer.Rect.height); text.text = layerText.Text.Replace("\r\n", "\n").Replace("\r", "\n"); float a = ((layerText.FillColor & 0xFF000000U) >> 24) / 255f; float r = ((layerText.FillColor & 0xFF0000U) >> 16) / 255f; float g = ((layerText.FillColor & 0xFF00U) >> 8) / 255f; float b = (layerText.FillColor & 0xFFU) / 255f; text.color = new Color(r, g, b, a); // if (layerText.OutlineWidth > 0) // { // Outline outline = spriteObject.AddComponent<Outline>(); // outline.effectDistance = new Vector2((float)layerText.OutlineWidth , (float)layerText.OutlineWidth); // } } else { // Retrieve sprite from asset database string sprPath = PSDExporter.GetLayerFilename(settings, i); Sprite sprite = AssetDatabase.LoadAssetAtPath <Sprite>(sprPath); // Get the pivot settings for the sprite TextureImporter sprImporter = (TextureImporter)AssetImporter.GetAtPath(sprPath); TextureImporterSettings sprSettings = new TextureImporterSettings(); sprImporter.ReadTextureSettings(sprSettings); sprImporter = null; // Add components to the sprite object for the visuals constructor.AddComponents(i, spriteObject, sprite, sprSettings); // Reposition the sprite object according to PSD position spritePivot = GetPivot(sprSettings); } Vector3 layerPos = constructor.GetLayerPosition(layer.Rect, spritePivot, settings.PixelsToUnitSize); // reverse y axis layerPos.y = fileInfo.height - layerPos.y; // Scaling factor, if sprites were scaled down float posScale = 1f; switch (settings.ScaleBy) { case 1: posScale = 0.5f; break; case 2: posScale = 0.25f; break; } layerPos *= posScale; // Sprite position is based on root object position initially Transform spriteT = spriteObject.transform; // spriteT.position = layerPos; RectTransform rectTrans = spriteObject.GetComponent <RectTransform>(); rectTrans.anchoredPosition3D = layerPos; } // End layer loop parseComponent(root); } // End BuildPsd()
public static void Scale(ScaleType _type, string _path, string _target) { string path = _path; string newPath = _target; // // load the texture from the disc by // setting the importer to use RGBA32 and ensure the texture is readable // TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; TextureImporterSettings orgSettings = new TextureImporterSettings(); ti.ReadTextureSettings(orgSettings); ti.textureFormat = TextureImporterFormat.RGBA32; ti.isReadable = true; AssetDatabase.ImportAsset(path); // get the pixels Texture2D originalTexture = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D; Color32[] c1 = originalTexture.GetPixels32(); int orgWidth = originalTexture.width; int orgHeight = originalTexture.height; originalTexture = null; // // restore original import settings // ti = AssetImporter.GetAtPath(path) as TextureImporter; ti.SetTextureSettings(orgSettings); AssetDatabase.ImportAsset(path); // arbitrary target size int width = 433; //preserve aspect ratio int height = Mathf.RoundToInt((width / (float)orgWidth) * orgHeight); //actually scale the data switch (_type) { case ScaleType.Lanczos: c1 = ScaleUnityTexture.ScaleLanczos(c1, orgWidth, width, height); break; case ScaleType.Linear: c1 = ScaleUnityTexture.ScaleLinear(c1, orgWidth, width, height); break; case ScaleType.Point: c1 = ScaleUnityTexture.ScalePoint(c1, orgWidth, width, height); break; } // create target texture Texture2D outT = new Texture2D(width, height, TextureFormat.RGBA32, false); // set the pixels outT.SetPixels32(c1); // encode the texture byte[] outBytes = outT.EncodeToPNG(); // save texture System.IO.File.WriteAllBytes(newPath, outBytes); AssetDatabase.ImportAsset(newPath); // Apply the same import settings for this texture ti = AssetImporter.GetAtPath(newPath) as TextureImporter; ti.SetTextureSettings(orgSettings); AssetDatabase.ImportAsset(newPath); }
private void ConvertToSprite(Shape shape) { string dname = "Assets/Resources/Shapes2D Sprites"; string fname = dname + "/" + shape.name + ".png"; string rname = "Shapes2D Sprites/" + shape.name; if (!System.IO.Directory.Exists(dname)) { System.IO.Directory.CreateDirectory(dname); } if (System.IO.File.Exists(fname) && !EditorUtility.DisplayDialog("Overwrite File?", "A file with the name " + fname + " already exists. " + "Are you sure you want to overwrite it?", "Yes", "Cancel")) { return; } float pixelsPerUnit = 100; Shapes2DPrefs prefs = GetPreferences(); if (prefs) { pixelsPerUnit = prefs.pixelsPerUnit; } else { Debug.LogWarning("Can't find Shapes2D Preferences in Shapes2D/Preferences. Please re-import Shapes2D."); } Vector2 pivot = RenderToTexture2D(fname, shape, pixelsPerUnit: pixelsPerUnit); // refresh the asset AssetDatabase.ImportAsset(fname); // set the sprite's pivot point so any rotations/position stay the same TextureImporter textureImporter = AssetImporter.GetAtPath(fname) as TextureImporter; TextureImporterSettings texSettings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(texSettings); #if UNITY_5_5_OR_NEWER texSettings.ApplyTextureType(TextureImporterType.Sprite); #else texSettings.ApplyTextureType(TextureImporterType.Sprite, true); #endif texSettings.spritePixelsPerUnit = pixelsPerUnit; if (Vector2.Distance(pivot, new Vector2(0.5f, 0.5f)) < 0.01f) { texSettings.spriteAlignment = (int)SpriteAlignment.Center; textureImporter.SetTextureSettings(texSettings); } else { texSettings.spriteAlignment = (int)SpriteAlignment.Custom; textureImporter.SetTextureSettings(texSettings); textureImporter.spritePivot = pivot; } AssetDatabase.ImportAsset(fname, ImportAssetOptions.ForceUpdate); Sprite sprite = Resources.Load <Sprite>(rname); Undo.RecordObjects(shape.GetUndoObjects().ToArray(), "Convert to Sprite"); shape.SetAsSprite(sprite, GetDefaultSpriteMaterial()); // exit the gui routine because otherwise we get annoying errors because // we deleted a material and unity still wants to draw it EditorGUIUtility.ExitGUI(); }
/// <summary> /// Imports and configures atlas texture. /// </summary> /// <returns><c>true</c>, if import and configure atlas texture was successful, <c>false</c> otherwise.</returns> /// <param name="targetTexture">Target texture.</param> /// <param name="sourceTexture">Source texture.</param> /// <param name="uvs">Uvs.</param> /// <param name="names">Names.</param> /// <param name="defaultPivot">Default pivot.</param> /// <param name="defaultCustomPivot">Default custom pivot.</param> public static bool ImportAndConfigureAtlasTexture(Texture2D targetTexture, Texture2D sourceTexture, Rect[] uvs, SPSpriteImportData[] spritesImportData) { // Get the asset path string assetPath = SPTools.GetAssetPath(targetTexture); if (string.IsNullOrEmpty(assetPath)) { Debug.LogError("Sprite Packer failed to Import and Configure the atlas texture, reason: Could not resolve asset path."); return(false); } // Clear the read-only flag in texture file attributes if (!SPTools.RemoveReadOnlyFlag(assetPath)) { Debug.LogError("Sprite Packer failed to Import and Configure the atlas texture, reason: Could not remove the readonly flag from the asset."); return(false); } // Write the source texture data to the asset byte[] bytes = sourceTexture.EncodeToPNG(); System.IO.File.WriteAllBytes(assetPath, bytes); bytes = null; // Get the asset texture importer TextureImporter texImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (texImporter == null) { Debug.LogError("Sprite Packer failed to Import and Configure the atlas texture, reason: Could not get the texture importer for the asset."); return(false); } // Get the asset texture importer settings TextureImporterSettings texImporterSettings = new TextureImporterSettings(); // Apply sprite type texImporter.textureType = TextureImporterType.Sprite; texImporter.spriteImportMode = SpriteImportMode.Multiple; // Configure the spritesheet meta data SpriteMetaData[] spritesheetMeta = new SpriteMetaData[uvs.Length]; for (int i = 0; i < uvs.Length; i++) { if (SPTools.HasSpritesheetMeta(texImporter.spritesheet, spritesImportData[i].name)) { SpriteMetaData currentMeta = SPTools.GetSpritesheetMeta(texImporter.spritesheet, spritesImportData[i].name); Rect currentRect = uvs[i]; currentRect.x *= sourceTexture.width; currentRect.width *= sourceTexture.width; currentRect.y *= sourceTexture.height; currentRect.height *= sourceTexture.height; currentMeta.rect = currentRect; spritesheetMeta[i] = currentMeta; } else { SpriteMetaData currentMeta = new SpriteMetaData(); Rect currentRect = uvs[i]; currentRect.x *= sourceTexture.width; currentRect.width *= sourceTexture.width; currentRect.y *= sourceTexture.height; currentRect.height *= sourceTexture.height; currentMeta.rect = currentRect; currentMeta.name = spritesImportData[i].name; currentMeta.alignment = (int)spritesImportData[i].alignment; currentMeta.pivot = spritesImportData[i].pivot; currentMeta.border = spritesImportData[i].border; spritesheetMeta[i] = currentMeta; } } texImporter.spritesheet = spritesheetMeta; // Read the texture importer settings texImporter.ReadTextureSettings(texImporterSettings); // Disable Read/Write texImporterSettings.readable = false; // Re-set the texture importer settings texImporter.SetTextureSettings(texImporterSettings); // Save and Reimport the asset AssetDatabase.SaveAssets(); SPTools.DoAssetReimport(assetPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); // Return success return(true); }
public void DoEditTextureAll() { if (Selection.objects == null || Selection.objects.Length != 1) { Debug.LogWarning("한개의 폴더만 선택 후 다시 눌러주세요"); return; } _listDirectoryInfo.Clear(); string strFolderPath = AssetDatabase.GetAssetPath(Selection.objects[0]); List <TextureImporter> listTexture = new List <TextureImporter>(); DirectoryInfo pDirectory = new DirectoryInfo(strFolderPath); ProcAddTextureImporter_InDirectory(pDirectory, listTexture); _listDirectoryInfo.AddRange_Last(pDirectory.GetDirectories()); while (_listDirectoryInfo.Count != 0) { DirectoryInfo pDirectoryChild = _listDirectoryInfo.First.Value; _listDirectoryInfo.RemoveFirst(); _listDirectoryInfo.AddRange_Last(pDirectoryChild.GetDirectories()); ProcAddTextureImporter_InDirectory(pDirectoryChild, listTexture); } for (int i = 0; i < listTexture.Count; i++) { bool bIsChange = false; TextureImporter pImporter = listTexture[i]; if (pImporter.textureType != TextureImporterType.Sprite) { pImporter.textureType = TextureImporterType.Sprite; bIsChange = true; } if (pImporter.spritePackingTag.Equals(_strSpriteTag) == false) { pImporter.spritePackingTag = _strSpriteTag; bIsChange = true; } if (pImporter.spriteImportMode != SpriteImportMode.Single) { pImporter.spriteImportMode = SpriteImportMode.Single; bIsChange = true; } bool bIsChangeTextureImporter = false; TextureImporterSettings pTextureSettings = new TextureImporterSettings(); pImporter.ReadTextureSettings(pTextureSettings); if (pTextureSettings.spriteMeshType.Equals(_eSpriteMeshType) == false) { pTextureSettings.spriteMeshType = _eSpriteMeshType; bIsChangeTextureImporter = true; } if (pTextureSettings.spriteExtrude.Equals((uint)_iSpriteExtrude) == false) { pTextureSettings.spriteExtrude = (uint)_iSpriteExtrude; bIsChangeTextureImporter = true; } if (bIsChangeTextureImporter) { pImporter.SetTextureSettings(pTextureSettings); } if (bIsChange || bIsChangeTextureImporter) { Debug.Log("Change :" + pImporter.assetPath, pImporter); pImporter.SaveAndReimport(); } } AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); }
public void OpenFile(Object fileObject) { if (isOpeningFile) { return; } importFile = null; importPath = string.Empty; importPreview = null; importPPU = 100; importSettings = new ImportUserData() { DocAlignment = SpriteAlignment.Center }; importDisplay = null; selectionCount = 0; quickSelect.Clear(); lastSelectedLayer = null; var filePath = AssetDatabase.GetAssetPath(fileObject); if (filePath.ToLower().EndsWith(".psd") == false) { return; } importFile = fileObject; importPath = filePath; importPreview = AssetDatabase.LoadAssetAtPath <Texture2D>(importPath); // Read the texture import settings of the asset file TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(importPath); TextureImporterSettings unityImportSettings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(unityImportSettings); importPPU = unityImportSettings.spritePixelsPerUnit; // Attempt to deserialize string json = textureImporter.userData; bool didGetUserData = false; if (string.IsNullOrEmpty(json) == false) { fsData data = fsJsonParser.Parse(json); object deserialObj = null; if (serializer.TryDeserialize(data, typeImportUserData, ref deserialObj) .AssertSuccessWithoutWarnings() .Succeeded) { importSettings = (ImportUserData)deserialObj; if (importSettings == null) { importSettings = new ImportUserData(); } else { didGetUserData = true; } } } if (didGetUserData) { settingsChanged = false; } else { settingsChanged = true; showImportSettings = true; } isOpeningFile = true; PsdImporter.BuildImportLayerData(importFile, importSettings, (importedLayerData, displayData) => { importSettings.DocRoot = ResolveData(importSettings.DocRoot, importedLayerData); importDisplay = displayData; isOpeningFile = false; CollateImportList(); Repaint(); }); }
public static void SaveMesh() { GameObject go = Selection.activeGameObject; SkinnedMeshRenderer[] skinnedMeshRenderers = go.GetComponentsInChildren <SkinnedMeshRenderer>(); foreach (SkinnedMeshRenderer render in skinnedMeshRenderers) { if (render.sharedMesh == null) { continue; } Mesh mesh = render.sharedMesh; if (!File.Exists("Assets/_Test/" + mesh.name + ".asset")) { Mesh newmesh = (Mesh)Mesh.Instantiate(mesh); AssetDatabase.CreateAsset(newmesh, "Assets/_Test/" + mesh.name + ".asset"); } foreach (Material material in render.materials) { if (!File.Exists("Assets/_Test/" + material.name.Replace(" (Instance)", "") + ".mat")) { AssetDatabase.CreateAsset(material, "Assets/_Test/" + material.name.Replace(" (Instance)", "") + ".mat"); } if (material.mainTexture != null) { Texture2D t = (Texture2D)material.mainTexture; // t = (Texture2D) Texture2D.Instantiate(t); // Texture2D newTexture2D = ne // newTexture2D.SetPixels32(t.GetPixels32()); // newTexture2D.Apply(); // var bytes = newTexture2D.EncodeToPNG(); // AssetDatabase.CreateAsset(t, "Assets/_Test/" + t.name + "png.asset"); // File.WriteAllBytes("Assets/_Test/" + material.mainTexture.name + ".png", bytes); Shader shader = Shader.Find("Sprites/Default"); SaveRenderTextureToPNG(t, shader, "Assets/_Test/", t.name.Replace(" (Instance)", "")); } } } Animation[] animations = go.GetComponentsInChildren <Animation>(); foreach (Animation animation in animations) { foreach (AnimationState state in animation) { if (state != null && state.clip != null) { AnimationClip clip = (AnimationClip)AnimationClip.Instantiate(state.clip); if (!File.Exists("Assets/_Test/" + clip.name.Replace("(Clone)", "") + ".anim")) { AssetDatabase.CreateAsset(clip, "Assets/_Test/" + clip.name.Replace("(Clone)", "") + ".anim"); } } } } SpriteRenderer[] spriteRenderers = go.GetComponentsInChildren <SpriteRenderer>(); foreach (SpriteRenderer spriteRenderer in spriteRenderers) { if (spriteRenderer.sprite != null) { Shader shader = Shader.Find("Sprites/Default"); Texture2D t = (Texture2D)spriteRenderer.sprite.texture; SaveRenderTextureToPNG(t, shader, "Assets/_Test/", t.name.Replace(" (Instance)", "")); string path = "Assets/_Test/" + t.name.Replace(" (Instance)", "") + ".png"; ImportAssetOptions options = ImportAssetOptions.Default; AssetDatabase.ImportAsset(path); TextureImporter importer = (TextureImporter)TextureImporter.GetAtPath(path); importer.textureType = TextureImporterType.Sprite; TextureImporterSettings tis = new TextureImporterSettings(); importer.ReadTextureSettings(tis); tis.ApplyTextureType(TextureImporterType.Sprite, false); importer.SetTextureSettings(tis); AssetDatabase.ImportAsset(path); } } }
public Sprite Create(SpriteAssetFactoryInputData data) { if (!string.IsNullOrEmpty(data.Name) && !string.IsNullOrEmpty(data.Path) && data.Reference != null) { EditorFileUtils.CreateDirectories(data.Path); var directoryInfo = new DirectoryInfo(data.Path); var fullPath = Path.Combine(directoryInfo.FullName, $"{data.Name}.png"); var relativePath = Path.Combine(data.Path, $"{data.Name}.png"); var bytes = data.Reference.EncodeToPNG(); File.WriteAllBytes(fullPath, bytes); AssetDatabase.Refresh(); _importerSettings = data.ImporterSettings; _importerPlatformSettings = data.ImporterPlatformSettings; var importer = AssetImporter.GetAtPath(relativePath); if (importer != null && importer is TextureImporter textureImporter) { if (_importerSettings != null) { textureImporter.textureType = _importerSettings.textureType; textureImporter.spritePixelsPerUnit = _importerSettings.spritePixelsPerUnit; textureImporter.spritePivot = _importerSettings.spritePivot; textureImporter.sRGBTexture = _importerSettings.sRGBTexture; textureImporter.alphaSource = _importerSettings.alphaSource; textureImporter.alphaIsTransparency = _importerSettings.alphaIsTransparency; textureImporter.isReadable = _importerSettings.readable; textureImporter.mipmapEnabled = _importerSettings.mipmapEnabled; textureImporter.wrapMode = _importerSettings.wrapMode; textureImporter.filterMode = _importerSettings.filterMode; textureImporter.anisoLevel = _importerSettings.aniso; var importerSettings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(importerSettings); importerSettings.spriteMode = _importerSettings.spriteMode; importerSettings.spriteMeshType = _importerSettings.spriteMeshType; importerSettings.spriteExtrude = _importerSettings.spriteExtrude; importerSettings.spriteAlignment = _importerSettings.spriteAlignment; importerSettings.spriteGenerateFallbackPhysicsShape = _importerSettings.spriteGenerateFallbackPhysicsShape; textureImporter.SetTextureSettings(importerSettings); foreach (var platformSettings in _importerPlatformSettings) { var existingSettings = textureImporter.GetPlatformTextureSettings(platformSettings.name); existingSettings.overridden = platformSettings.overridden; existingSettings.maxTextureSize = platformSettings.maxTextureSize; existingSettings.resizeAlgorithm = platformSettings.resizeAlgorithm; existingSettings.format = platformSettings.format; existingSettings.textureCompression = platformSettings.textureCompression; existingSettings.crunchedCompression = platformSettings.crunchedCompression; existingSettings.compressionQuality = platformSettings.compressionQuality; existingSettings.allowsAlphaSplitting = platformSettings.allowsAlphaSplitting; existingSettings.androidETC2FallbackOverride = platformSettings.androidETC2FallbackOverride; textureImporter.SetPlatformTextureSettings(existingSettings); } } else { textureImporter.mipmapEnabled = false; textureImporter.isReadable = true; textureImporter.textureType = TextureImporterType.Sprite; textureImporter.spritePivot = new Vector2(0.5f, 0.5f); textureImporter.filterMode = _settings.FilterMode; textureImporter.mipmapEnabled = _settings.GenerateMipMaps; textureImporter.crunchedCompression = _settings.UseCrunchCompression; textureImporter.compressionQuality = _settings.CompressionQuality; textureImporter.textureCompression = _settings.Compression; } textureImporter.SaveAndReimport(); } AssetDatabase.Refresh(); AssetDatabaseHelper.TryGetAsset <Sprite>(relativePath, out var sprite); return(sprite); } return(null); }
private static IEnumerator ImportCoroutine(Object psdFile, ImportUserData importSettings, List <int[]> layerIndices, bool doYield = false, Action <int, ImportLayerData> layerCallback = null, Action <List <Sprite> > completeCallback = null) { string filepath = GetPsdFilepath(psdFile); if (string.IsNullOrEmpty(filepath)) { if (completeCallback != null) { completeCallback(null); } yield break; } // No target directory set, use PSD file directory if (string.IsNullOrEmpty(importSettings.TargetDirectory)) { importSettings.TargetDirectory = filepath.Substring(0, filepath.LastIndexOf("/")); } // Get the texture importer for the PSD TextureImporter psdUnitySettings = (TextureImporter)AssetImporter.GetAtPath(filepath); TextureImporterSettings psdUnityImport = new TextureImporterSettings(); psdUnitySettings.ReadTextureSettings(psdUnityImport); int importCurrent = 0; List <Sprite> sprites = new List <Sprite>(); using (PsdDocument psd = PsdDocument.Create(filepath)) { foreach (int[] layerIdx in layerIndices) { ImportLayerData layerSettings = importSettings.GetLayerData(layerIdx); if (layerSettings == null) { continue; } if (layerCallback != null) { layerCallback(importCurrent, layerSettings); } var sprite = ImportLayer(psd, importSettings, layerSettings, psdUnityImport); sprites.Add(sprite); importCurrent++; if (doYield) { yield return(null); } } } if (completeCallback != null) { completeCallback(sprites); } }
public void OnGroupAtlases(BuildTarget target, PackerJob job, int[] textureImporterInstanceIDs) { List <Entry> entries = new List <Entry>(); foreach (int instanceID in textureImporterInstanceIDs) { TextureImporter ti = EditorUtility.InstanceIDToObject(instanceID) as TextureImporter; TextureFormat desiredFromat; ColorSpace colorSapce; int compressionQuality; ti.ReadTextureImportInstructions(target, out desiredFromat, out colorSapce, out compressionQuality); TextureImporterSettings tis = new TextureImporterSettings(); ti.ReadTextureSettings(tis); Sprite[] sprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(ti.assetPath).Select(x => x as Sprite).Where(x => x != null).ToArray(); foreach (Sprite sprite in sprites) { Entry entry = new Entry(); entry.sprite = sprite; entry.settings.format = desiredFromat; entry.settings.colorSpace = colorSapce; entry.settings.compressionQuality = compressionQuality; entry.settings.filterMode = Enum.IsDefined(typeof(FilterMode), ti.filterMode) ? ti.filterMode : FilterMode.Bilinear; entry.settings.maxWidth = 1024; entry.settings.maxHeight = 1024; entry.atlasName = ParseAtlasName(ti.spritePackingTag); entry.packingMode = GetPackingMode(ti.spritePackingTag, tis.spriteMeshType); entries.Add(entry); } Resources.UnloadAsset(ti); } // First split sprites into groups based on atlas name var atlasGroups = from e in entries group e by e.atlasName; foreach (var atlasGroup in atlasGroups) { int page = 0; // Then split those groups into smaller groups based on texture settings var settingsGroups = from t in atlasGroup group t by t.settings; foreach (var settingsGroup in settingsGroups) { string atlasName = atlasGroup.Key; if (settingsGroups.Count() > 1) { atlasName += string.Format(" (Group {0})", page); } job.AddAtlas(atlasName, settingsGroup.Key); foreach (Entry entry in settingsGroup) { job.AssignToAtlas(atlasName, entry.sprite, entry.packingMode, SpritePackingRotation.None); } ++page; } } }