public static void ImportedAsset(string path) { ImportedAsset(AssetImporter.GetAtPath(path)); }
public void SetAssetBundleNameAndVariant(string assetPath, string bundleName, string variantName) { AssetImporter.GetAtPath(assetPath).SetAssetBundleNameAndVariant(bundleName, variantName); }
private Texture2D NormalMap(Texture2D source, float strength) { strength = Mathf.Clamp(strength, 0.0F, 5.0F); Texture2D normalTexture; float xLeft; float xRight; float yUp; float yDown; float yDelta; float xDelta; //SET READEABLE ORIGINAL TEX string path = AssetDatabase.GetAssetPath(source); TextureImporter A = (TextureImporter)AssetImporter.GetAtPath(path); A.isReadable = true; AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); normalTexture = new Texture2D(source.width, source.height, TextureFormat.ARGB32, true); for (int y = 0; y < normalTexture.height; y++) { for (int x = 0; x < normalTexture.width; x++) { float green = 1f; float blue = 1f; if (source.GetPixel(x, y).a <= .01f) { normalTexture.SetPixel(x, y, new Color(0f, 0f, 0f, 1f)); continue; } if (source.GetPixel(x, y).grayscale > 0f && source.GetPixel(x, y).grayscale < .1f) { green = 1.3f; blue = .2f; } xLeft = source.GetPixel(x - 1, y).grayscale *strength; xRight = source.GetPixel(x + 1, y).grayscale *strength; yUp = source.GetPixel(x, y - 1).grayscale *strength; yDown = source.GetPixel(x, y + 1).grayscale *strength; xDelta = ((xLeft - xRight) + 1) * 0.5f; yDelta = ((yUp - yDown) + 1) * 0.5f; normalTexture.SetPixel(x, y, new Color(xDelta, yDelta * green, 1.0f * blue, 1.0f)); } } normalTexture.Apply(); // System.IO.Directory.CreateDirectory("Assets/_NormalTextures/"); // System.IO.File.WriteAllBytes("Assets/_NormalTextures/" + source.name + ".png", normalTexture.EncodeToPNG()); return(normalTexture); }
protected static List <BundleMeshes> ParseBundleMeshes(string raceName) { var textureLoader = new TextureLoader(); var bundleMeshList = new List <BundleMeshes>(); int substringLength = "Assets/Character_Editor/Prefabs/".Length; var meshTypes = new Dictionary <MeshType, string> { { MeshType.Torso, Meshes.Torso.GetFolderPath(raceName) }, { MeshType.Beard, Meshes.Beard.GetFolderPath(raceName) }, { MeshType.FaceFeature, Meshes.FaceFeature.GetFolderPath(raceName) }, { MeshType.Hair, Meshes.Hair.GetFolderPath(raceName) }, { MeshType.Helm, Meshes.Helm.GetFolderPath(raceName) }, { MeshType.TorsoAdd, Meshes.TorsoAdd.GetFolderPath(raceName) }, { MeshType.LegRight, Meshes.Leg.GetFolderPath(raceName, MeshType.LegRight) }, { MeshType.LegLeft, Meshes.Leg.GetFolderPath(raceName, MeshType.LegLeft) }, { MeshType.ShoulderLeft, Meshes.Shoulder.GetFolderPath(raceName, MeshType.ShoulderLeft) }, { MeshType.ShoulderRight, Meshes.Shoulder.GetFolderPath(raceName, MeshType.ShoulderRight) }, { MeshType.ArmLeft, Meshes.Arm.GetFolderPath(raceName, MeshType.ArmLeft) }, { MeshType.ArmRight, Meshes.Arm.GetFolderPath(raceName, MeshType.ArmRight) }, { MeshType.Belt, Meshes.Belt.GetFolderPath(raceName) }, { MeshType.BeltAdd, Meshes.BeltAdd.GetFolderPath(raceName) }, { MeshType.HandLeft, Meshes.Hand.GetFolderPath(raceName, MeshType.HandLeft) }, { MeshType.HandRight, Meshes.Hand.GetFolderPath(raceName, MeshType.HandRight) }, }; foreach (var path in meshTypes) { var bundleMeshes = new BundleMeshes(); bundleMeshes.type = path.Key; var dirPath = Path.Combine(Application.dataPath, path.Value.Substring(7)); if (!Directory.Exists(dirPath)) { continue; } var folders = Directory.GetDirectories(dirPath); for (int i = 0; i < folders.Length; i++) { var bundleMesh = new BundleMesh(); string gameObjectsPath = folders[i].Substring(Application.dataPath.Length - 6); var meshGUIDs = AssetDatabase.FindAssets("t:GameObject", new string[] { gameObjectsPath + "/StaticModel" } ); if (meshGUIDs.Length == 0) { continue; } var bundleModelPath = AssetDatabase.GUIDToAssetPath(meshGUIDs[0]); string bundleName, assetPath; ParsePathToBundle(bundleModelPath.Substring(substringLength), out bundleName, out assetPath, 2); AssetImporter.GetAtPath(bundleModelPath).SetAssetBundleNameAndVariant(bundleName, ""); bundleMesh.modelPath = assetPath; foreach (var texturePath in textureLoader.ParseTextures(null, gameObjectsPath + "/Textures")) { var bundleTexture = new BundleTexture(); foreach (var colorPath in texturePath) { ParsePathToBundle(colorPath.Substring(substringLength), out bundleName, out assetPath, 2); AssetImporter.GetAtPath(colorPath).SetAssetBundleNameAndVariant(bundleName, ""); var bundleColor = new BundleColor(); bundleColor.path = assetPath; bundleTexture.colors.Add(bundleColor); } bundleMesh.textures.Add(bundleTexture); } bundleMeshes.meshPaths.Add(bundleMesh); } bundleMeshList.Add(bundleMeshes); } return(bundleMeshList); }
private static string[] ExportAtlasPNG(MA_TextureAtlasserProAtlas atlas, TextureExportSettings textureExportSettings, string savePath = EXPORT_ASSET_PATH, string tempPath = TEMP_ASSET_PATH) { if (atlas == null || atlas.textureQuads == null || atlas.textureGroupRegistration == null) { return(null); } string[] assetPaths = new string[atlas.textureGroupRegistration.Count]; //Directories. string savePathTextures = savePath + atlas.name + "/Textures/"; CreateFolder(savePathTextures); //Create temp folder CreateFolder(tempPath); //Foreach texture group for (int i = 0; i < atlas.textureGroupRegistration.Count; i++) { //Create new Texture Atlas Texture2D newTexture = new Texture2D((int)atlas.textureAtlasSize.x, (int)atlas.textureAtlasSize.y) { name = atlas.name + "_" + atlas.textureGroupRegistration[i].name }; foreach (MA_TextureAtlasserProQuad q in atlas.textureQuads) { if (q.textureGroups != null && q.textureGroups[i].texture != null) { //Make temp copy string orginalTexturePath = AssetDatabase.GetAssetPath(q.textureGroups[i].texture); string orginalTextureExtension = System.IO.Path.GetExtension(orginalTexturePath); string tempTexturePath = tempPath + q.textureGroups[i].texture.name + orginalTextureExtension; AssetDatabase.CopyAsset(orginalTexturePath, tempTexturePath); //Set temp copy to default settings TextureImporter tempTextureImporter = (TextureImporter)AssetImporter.GetAtPath(tempTexturePath); tempTextureImporter.textureType = TextureImporterType.Default; tempTextureImporter.sRGBTexture = false; tempTextureImporter.alphaIsTransparency = false; tempTextureImporter.maxTextureSize = (int)Mathf.Max(atlas.textureAtlasSize.x, atlas.textureAtlasSize.y); tempTextureImporter.textureCompression = TextureImporterCompression.Uncompressed; tempTextureImporter.SaveAndReimport(); //Load temp copy Texture tempCopy = AssetDatabase.LoadAssetAtPath <Texture>(tempTextureImporter.assetPath); //Create new texture part Texture2D newTexturePart = (Texture2D)MA_TextureUtils.ConvertToReadableTexture(tempCopy); //Scale it newTexturePart = newTexturePart.MA_Scale2D((int)q.guiRect.width, (int)q.guiRect.height, textureExportSettings.textureScaleMode); //Add it newTexture = newTexture.MA_Combine2D(newTexturePart, (int)q.guiRect.x, (int)q.guiRect.y); //Delete temp copy AssetDatabase.DeleteAsset(tempTextureImporter.assetPath); } } //Save it newTexture.MA_Save2D(newTexture.name, savePathTextures); assetPaths[i] = (savePathTextures + newTexture.name + '.' + textureExportSettings.textureFormat.ToString()); //Set settings. switch (textureExportSettings.textureType) { case TextureType.Default: { TextureImporter textureImporter = (TextureImporter)AssetImporter.GetAtPath(savePathTextures + newTexture.name + '.' + textureExportSettings.textureFormat.ToString()); textureImporter.textureType = TextureImporterType.Default; textureImporter.SaveAndReimport(); } break; case TextureType.Sprite: SetAtlasSpriteSettings(atlas, textureExportSettings, savePathTextures); break; case TextureType.SpriteSliced: SetAtlasSpriteSettings(atlas, textureExportSettings, savePathTextures); break; default: break; } } //Delete temp folder DeleteFolder(tempPath); //Refresh AssetDatabase.Refresh(); return(assetPaths); }
public static void DoImportBitmapFont(string fntPatn) { TextAsset fnt = AssetDatabase.LoadMainAssetAtPath(fntPatn) as TextAsset; string text = fnt.text; FntParse parse = FntParse.GetFntParse(ref text); if (parse == null) { return; } string fntName = Path.GetFileNameWithoutExtension(fntPatn); string rootPath = Path.GetDirectoryName(fntPatn); string fontPath = string.Format("{0}/{1}.fontsettings", rootPath, fntName); string texPath = string.Format("{0}/{1}", rootPath, parse.textureName); Texture2D texture = AssetDatabase.LoadMainAssetAtPath(texPath) as Texture2D; if (texture == null) { Debug.LogErrorFormat(fnt, "{0}: not found '{1}'.", typeof(BFImporter), texPath); return; } TextureImporter texImporter = AssetImporter.GetAtPath(texPath) as TextureImporter; texImporter.textureType = TextureImporterType.GUI; texImporter.mipmapEnabled = false; texImporter.SaveAndReimport(); Font font = AssetDatabase.LoadMainAssetAtPath(fontPath) as Font; if (font == null) { font = new Font(); AssetDatabase.CreateAsset(font, fontPath); AssetDatabase.WriteImportSettingsIfDirty(fontPath); AssetDatabase.ImportAsset(fontPath); } Material material = AssetDatabase.LoadAssetAtPath(fontPath, typeof(Material)) as Material; if (material == null) { material = new Material(Shader.Find("UI/Default")); material.name = "Font Material"; AssetDatabase.AddObjectToAsset(material, fontPath); // unity 5.4+ cannot refresh it immediately, must import it AssetDatabase.ImportAsset(fontPath); } font.material = material; material.mainTexture = texture; font.characterInfo = parse.charInfos; SerializedObject so = new SerializedObject(font); so.Update(); so.FindProperty("m_FontSize").floatValue = Mathf.Abs(parse.fontSize); so.FindProperty("m_LineSpacing").floatValue = parse.lineHeight; so.FindProperty("m_Ascent").floatValue = parse.lineBaseHeight; SerializedProperty prop = so.FindProperty("m_Descent"); if (prop != null) { prop.floatValue = parse.lineBaseHeight - parse.lineHeight; } UpdateKernings(so, parse.kernings); so.ApplyModifiedProperties(); so.SetIsDifferentCacheDirty(); AssetDatabase.SaveAssets(); #if UNITY_5_5_OR_NEWER // unity 5.5 can not load custom font ReloadFont(fontPath); #endif }
/// <summary> /// Copy srcaar files to aar files that are excluded from Unity's build process. /// </summary> /// <param name="dependencies">Dependencies to inject.</param> /// <returns>true if successful, false otherwise.</returns> private static bool CopySrcAars(ICollection <Dependency> dependencies) { bool succeeded = true; var aarFiles = new List <string>(); // Copy each .srcaar file to .aar while configuring the plugin importer to ignore the // file. foreach (var aar in LocalMavenRepository.FindAarsInLocalRepos(dependencies)) { var dir = Path.GetDirectoryName(aar); var filename = Path.GetFileNameWithoutExtension(aar); var targetFilename = Path.Combine(dir, filename + ".aar"); bool configuredAar = File.Exists(targetFilename); if (!configuredAar) { bool copiedAndLabeledAar = AssetDatabase.CopyAsset(aar, targetFilename); if (copiedAndLabeledAar) { var unlabeledAssets = new HashSet <string>(); PlayServicesResolver.LabelAssets( new [] { targetFilename }, complete: (unlabeled) => { unlabeledAssets.UnionWith(unlabeled); }); copiedAndLabeledAar = unlabeledAssets.Count == 0; } if (copiedAndLabeledAar) { try { PluginImporter importer = (PluginImporter)AssetImporter.GetAtPath( targetFilename); importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); configuredAar = true; } catch (Exception ex) { PlayServicesResolver.Log(String.Format( "Failed to disable {0} from being included by Unity's " + "internal build. {0} has been deleted and will not be " + "included in Gradle builds. ({1})", aar, ex), level: LogLevel.Error); } } else { PlayServicesResolver.Log(String.Format( "Unable to copy {0} to {1}. {1} will not be included in Gradle " + "builds.", aar, targetFilename), level: LogLevel.Error); } if (configuredAar) { aarFiles.Add(targetFilename); } else { if (File.Exists(targetFilename)) { AssetDatabase.DeleteAsset(targetFilename); } succeeded = false; } } } foreach (var aar in aarFiles) { if (!LocalMavenRepository.PatchPomFile(aar)) { succeeded = false; } } return(succeeded); }
public void SaveLUT(LUTResult lutResult) { if (lutResult == null) { ToolSettings.Instance.Message = "Error while reading LUT data."; return; } var assetpath = _texturePath; bool justBrowsed = false; if (string.IsNullOrEmpty(assetpath)) { if (EditorUtility.DisplayDialog("Browse?", "There is no current path to save the file to.", "Browse", "Cancel")) { var path = EditorUtility.SaveFilePanelInProject("Save as", Path.GetFileName(_texturePath), "png", "Please enter a file name to save the texture to"); justBrowsed = true; if (string.IsNullOrEmpty(path)) { return; } _texturePath = path; } else { return; } } if (File.Exists(_texturePath) && !justBrowsed && !_overwrite) { if (!EditorUtility.DisplayDialog("Overwrite?", "File already exists. This action will overwrite the current file. Do you want to continue?", "Overwrite", "Cancel")) { return; } } File.WriteAllBytes(_texturePath, lutResult.Texture.EncodeToPNG()); AssetDatabase.Refresh(); var text = AssetDatabase.LoadAssetAtPath(_texturePath, typeof(Texture2D)) as Texture2D; if (text != null) { text.wrapMode = TextureWrapMode.Clamp; text.filterMode = FilterMode.Bilinear; } TextureImporter tImporter = AssetImporter.GetAtPath(_texturePath) as TextureImporter; if (tImporter != null) { tImporter.mipmapEnabled = false; tImporter.isReadable = false; tImporter.filterMode = FilterMode.Bilinear; tImporter.anisoLevel = 0; #if UNITY_5_5_OR_NEWER tImporter.textureType = TextureImporterType.Default; tImporter.textureCompression = TextureImporterCompression.Uncompressed; tImporter.sRGBTexture = false; #else tImporter.textureType = TextureImporterType.Advanced; tImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor; tImporter.linearTexture = true; #endif tImporter.wrapMode = TextureWrapMode.Clamp; tImporter.maxTextureSize = 1024; AssetDatabase.ImportAsset(_texturePath, ImportAssetOptions.ForceUpdate); } }
//[Test] public void TextureFormats() { var cleanup = new List<string>(); // remove these assets afterwards var path = BeginAssetTest(); try { // These are the paths of our test textures in the package var srcPath0 = AssetDatabase.GUIDToAssetPath("e2e8f2c4db9cbae48ad0c09078dbabd5"); var srcPath1 = AssetDatabase.GUIDToAssetPath("35b624c59e124e6408affa5fef552ae1"); var srcPath2 = AssetDatabase.GUIDToAssetPath("8670b3720a4f1514ea8438a9f24d96e4"); // These are the paths where we copy our test textures to var dstPath0 = AssetDatabase.GenerateUniqueAssetPath("Assets/" + System.IO.Path.GetFileName(srcPath0)); var dstPath1 = AssetDatabase.GenerateUniqueAssetPath("Assets/" + System.IO.Path.GetFileName(srcPath1)); var dstPath2 = AssetDatabase.GenerateUniqueAssetPath("Assets/" + System.IO.Path.GetFileName(srcPath2)); // Make sure to remove the test assets afterwards cleanup.Add(dstPath0); cleanup.Add(dstPath1); cleanup.Add(dstPath2); // Copy test assets FileUtil.CopyFileOrDirectory(srcPath0, dstPath0); FileUtil.CopyFileOrDirectory(srcPath1, dstPath1); FileUtil.CopyFileOrDirectory(srcPath2, dstPath2); AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport); // Assign test textures to test 3d texture var importerTex3d = (Texture3DAtlasImporter)AssetImporter.GetAtPath(path); importerTex3d.textures = new Texture2D[] { AssetDatabase.LoadAssetAtPath<Texture2D>(dstPath0), AssetDatabase.LoadAssetAtPath<Texture2D>(dstPath1), AssetDatabase.LoadAssetAtPath<Texture2D>(dstPath2) }; importerTex3d.SaveAndReimport(); // Use each texture format var formats = GetSupportedTextureImporterFormats(); foreach(var format in formats) { // Set the Texture2D's to the corresponding texture format AssetDatabase.StartAssetEditing(); try { foreach (var destPath in new[] { dstPath0, dstPath1, dstPath2 }) { var importer = (TextureImporter)AssetImporter.GetAtPath(destPath); //importer.sRGBTexture = true; var settings = importer.GetDefaultPlatformTextureSettings(); settings.overridden = true; settings.format = format; importer.SetPlatformTextureSettings(settings); importer.SaveAndReimport(); } AssetDatabase.SaveAssets(); } finally { AssetDatabase.StopAssetEditing(); } // Now check i var tex0 = AssetDatabase.LoadAssetAtPath<Texture2D>(dstPath0); var tex1 = AssetDatabase.LoadAssetAtPath<Texture2D>(dstPath1); var tex2 = AssetDatabase.LoadAssetAtPath<Texture2D>(dstPath2); var tex3d = AssetDatabase.LoadAssetAtPath<Texture3D>(path); var tex2d = new Texture2D(tex3d.width, tex3d.height, tex3d.format, tex3d.mipmapCount > 1); Graphics.CopyTexture(tex3d, 0, tex2d, 0); System.IO.File.WriteAllBytes("Assets/Slice0.png", tex2d.EncodeToPNG()); Graphics.CopyTexture(tex3d, 1, tex2d, 0); System.IO.File.WriteAllBytes("Assets/Slice1.png", tex2d.EncodeToPNG()); Graphics.CopyTexture(tex3d, 2, tex2d, 0); System.IO.File.WriteAllBytes("Assets/Slice2.png", tex2d.EncodeToPNG()); Debug.Log(tex3d.format); } } finally { foreach(var p in cleanup) { if (System.IO.File.Exists(p)) AssetDatabase.DeleteAsset(p); } EndAssetTest(path); AssetDatabase.Refresh(); } }
public static void SetAssetbundleName(string path, AssetBuildRule bundleRule) { AssetImporter importer = AssetImporter.GetAtPath(path); SetAssetbundleName(importer, bundleRule); }
/// <summary> /// 自动出来资源导入 /// </summary> public static bool ProcessAssetImport(string name) { if (name.EndsWith(".dds")) { if (EditorUtility.DisplayDialog("出现了dds格式的纹理,这是不允许的!不要问为什么。", name, "删除")) { AssetDatabase.DeleteAsset(name); } else { AssetDatabase.DeleteAsset(name); } return(false); } if (!name.Contains("/Custom/") && (name.EndsWith(".png") || name.EndsWith(".jpg"))) { TextureImporter textureImporter = AssetImporter.GetAtPath(name) as TextureImporter; bool customSetting = false; AssetDatabase.GetLabels(textureImporter).ForEach((x) => { if (x == "TextureImporterFormatCustomSetting") { customSetting = true; } }); if (!customSetting) { textureImporter.spriteImportMode = SpriteImportMode.Single; textureImporter.alphaIsTransparency = true; if (textureImporter != null) { textureImporter.mipmapEnabled = false; textureImporter.wrapMode = TextureWrapMode.Clamp; if (name.StartsWith("Assets/Game/PackagingResources/") && (name.Contains("/Module/") || name.Contains("/Effect")) && name.Contains("/Image/")) { bool needSaveAndReimport = false; if (textureImporter.textureType != TextureImporterType.Sprite) { textureImporter.textureType = TextureImporterType.Sprite; // if (name.EndsWith(".jpg")) // { // textureImporter.alphaSource = TextureImporterAlphaSource.None; // } needSaveAndReimport = true; } needSaveAndReimport |= ProcessIosAssetSpriteImport(textureImporter); needSaveAndReimport |= ProcessAndroidAssetSpriteImport(textureImporter); if (needSaveAndReimport) { textureImporter.SaveAndReimport(); } } else if (name.Contains("/ModuleEffectPicture/")) { if (name.EndsWith(".jpg")) { textureImporter.alphaSource = TextureImporterAlphaSource.FromInput; } if (textureImporter.textureType != TextureImporterType.Sprite) { textureImporter.textureType = TextureImporterType.Sprite; textureImporter.SaveAndReimport(); } } } } } return(EditorAssetBundleEditorTool.AutoProcessAsset(name)); }
// Convert material from Unity to glTF PBR private void unityToPBRMaterial(Material mat, ref GlTF_Material material) { bool isMaterialPBR = true; bool isMetal = true; bool hasPBRMap = false; if (!mat.shader.name.Contains("Standard")) { Debug.Log("Material " + mat.shader + " is not fully supported"); isMaterialPBR = false; } else { // Is metal workflow used isMetal = mat.shader.name == "Standard"; GlTF_Writer.hasSpecularMaterials = GlTF_Writer.hasSpecularMaterials || !isMetal; material.isMetal = isMetal; // Is smoothness defined by diffuse texture or PBR texture' alpha? if (mat.GetFloat("_SmoothnessTextureChannel") != 0) { Debug.Log("Smoothness uses diffuse's alpha channel. Unsupported for now"); } hasPBRMap = (!isMetal && mat.GetTexture("_SpecGlossMap") != null || isMetal && mat.GetTexture("_MetallicGlossMap") != null); } //Check transparency bool hasTransparency = handleTransparency(ref mat, ref material); //Parse diffuse channel texture and color if (mat.HasProperty("_MainTex") && mat.GetTexture("_MainTex") != null) { var textureValue = new GlTF_Material.DictValue(); textureValue.name = isMetal ? "baseColorTexture" : "diffuseTexture"; int diffuseTextureIndex = processTexture((Texture2D)mat.GetTexture("_MainTex"), hasTransparency ? IMAGETYPE.RGBA : IMAGETYPE.RGBA_OPAQUE); textureValue.intValue.Add("index", diffuseTextureIndex); textureValue.intValue.Add("texCoord", 0); material.pbrValues.Add(textureValue); } if (mat.HasProperty("_Color")) { var colorValue = new GlTF_Material.ColorValue(); colorValue.name = isMetal ? "baseColorFactor" : "diffuseFactor"; Color c = mat.GetColor("_Color"); clampColor(ref c); colorValue.color = c; material.pbrValues.Add(colorValue); } //Parse PBR textures if (isMaterialPBR) { if (isMetal) { if (hasPBRMap) // No metallic factor if texture { var textureValue = new GlTF_Material.DictValue(); textureValue.name = "metallicRoughnessTexture"; Texture2D metallicRoughnessTexture = (Texture2D)mat.GetTexture("_MetallicGlossMap"); Texture2D occlusion = (Texture2D)mat.GetTexture("_OcclusionMap"); int metalRoughTextureIndex = createOcclusionMetallicRoughnessTexture(ref occlusion, ref metallicRoughnessTexture); textureValue.intValue.Add("index", metalRoughTextureIndex); textureValue.intValue.Add("texCoord", 0); material.pbrValues.Add(textureValue); } var metallicFactor = new GlTF_Material.FloatValue(); metallicFactor.name = "metallicFactor"; metallicFactor.value = hasPBRMap ? 1.0f : mat.GetFloat("_Metallic"); material.pbrValues.Add(metallicFactor); //Roughness factor var roughnessFactor = new GlTF_Material.FloatValue(); roughnessFactor.name = "roughnessFactor"; roughnessFactor.value = hasPBRMap ? 1.0f : 1 - mat.GetFloat("_Glossiness"); // gloss scale is not supported for now(property _GlossMapScale) material.pbrValues.Add(roughnessFactor); } else { if (hasPBRMap) // No metallic factor if texture { var textureValue = new GlTF_Material.DictValue(); textureValue.name = "specularGlossinessTexture"; int specGlossTextureIndex = processTexture((Texture2D)mat.GetTexture("_SpecGlossMap"), IMAGETYPE.RGBA); textureValue.intValue.Add("index", specGlossTextureIndex); textureValue.intValue.Add("texCoord", 0); material.pbrValues.Add(textureValue); } var specularFactor = new GlTF_Material.ColorValue(); specularFactor.name = "specularFactor"; specularFactor.color = hasPBRMap ? Color.white : mat.GetColor("_SpecColor"); // gloss scale is not supported for now(property _GlossMapScale) specularFactor.isRGB = true; material.pbrValues.Add(specularFactor); var glossinessFactor = new GlTF_Material.FloatValue(); glossinessFactor.name = "glossinessFactor"; glossinessFactor.value = hasPBRMap ? 1.0f : mat.GetFloat("_Glossiness"); // gloss scale is not supported for now(property _GlossMapScale) material.pbrValues.Add(glossinessFactor); } } //BumpMap if (mat.HasProperty("_BumpMap") && mat.GetTexture("_BumpMap") != null) { Texture2D bumpTexture = mat.GetTexture("_BumpMap") as Texture2D; // Check if it's a normal or a bump map TextureImporter im = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(bumpTexture)) as TextureImporter; bool isBumpMap = im.convertToNormalmap; if (isBumpMap) { Debug.LogWarning("Unsupported texture " + bumpTexture + " (normal maps generated from grayscale are not supported)"); } else { var textureValue = new GlTF_Material.DictValue(); textureValue.name = "normalTexture"; int bumpTextureIndex = processTexture(bumpTexture, IMAGETYPE.NORMAL_MAP); textureValue.intValue.Add("index", bumpTextureIndex); textureValue.intValue.Add("texCoord", 0); textureValue.floatValue.Add("scale", mat.GetFloat("_BumpScale")); material.values.Add(textureValue); } } //Emissive if (mat.HasProperty("_EmissionMap") && mat.GetTexture("_EmissionMap") != null) { Texture2D emissiveTexture = mat.GetTexture("_EmissionMap") as Texture2D; var textureValue = new GlTF_Material.DictValue(); textureValue.name = "emissiveTexture"; int emissiveTextureIndex = processTexture(emissiveTexture, IMAGETYPE.RGB); textureValue.intValue.Add("index", emissiveTextureIndex); textureValue.intValue.Add("texCoord", 0); material.values.Add(textureValue); } var emissiveFactor = new GlTF_Material.ColorValue(); emissiveFactor.name = "emissiveFactor"; emissiveFactor.isRGB = true; emissiveFactor.color = mat.GetColor("_EmissionColor"); material.values.Add(emissiveFactor); //Occlusion (kept as separated channel for specular workflow, but merged in R channel for metallic workflow) if (mat.HasProperty("_OcclusionMap") && mat.GetTexture("_OcclusionMap") != null) { Texture2D occlusionTexture = mat.GetTexture("_OcclusionMap") as Texture2D; var textureValue = new GlTF_Material.DictValue(); textureValue.name = "occlusionTexture"; int occlusionTextureIndex = processTexture(occlusionTexture, IMAGETYPE.RGB); textureValue.intValue.Add("index", occlusionTextureIndex); textureValue.intValue.Add("texCoord", 0); textureValue.floatValue.Add("strength", mat.GetFloat("_OcclusionStrength")); material.values.Add(textureValue); } // Unity materials are single sided by default GlTF_Material.BoolValue doubleSided = new GlTF_Material.BoolValue(); doubleSided.name = "doubleSided"; doubleSided.value = false; material.values.Add(doubleSided); }
private bool getPixelsFromTexture(ref Texture2D texture, out Color[] pixels) { //Make texture readable TextureImporter im = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture)) as TextureImporter; if (!im) { pixels = new Color[1]; return(false); } bool readable = im.isReadable; #if UNITY_5_4 TextureImporterFormat format = im.textureFormat; #else TextureImporterCompression format = im.textureCompression; #endif TextureImporterType type = im.textureType; bool isConvertedBump = im.convertToNormalmap; if (!readable) { im.isReadable = true; } #if UNITY_5_4 if (type != TextureImporterType.Image) { im.textureType = TextureImporterType.Image; } im.textureFormat = TextureImporterFormat.ARGB32; #else if (type != TextureImporterType.Default) { im.textureType = TextureImporterType.Default; } im.textureCompression = TextureImporterCompression.Uncompressed; #endif im.SaveAndReimport(); pixels = texture.GetPixels(); if (!readable) { im.isReadable = false; } #if UNITY_5_4 if (type != TextureImporterType.Image) { im.textureType = type; } #else if (type != TextureImporterType.Default) { im.textureType = type; } #endif if (isConvertedBump) { im.convertToNormalmap = true; } #if UNITY_5_4 im.textureFormat = format; #else im.textureCompression = format; #endif im.SaveAndReimport(); return(true); }
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { #region iOS and tvOS { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/tvOS/GameAnalyticsTVOS.h") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.tvOS) || importer.GetCompatibleWithPlatform(BuildTarget.iOS))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, true); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/tvOS/GameAnalyticsTVOSUnity.m") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.tvOS) || importer.GetCompatibleWithPlatform(BuildTarget.iOS))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, true); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/tvOS/libGameAnalyticsTVOS.a") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.tvOS) || importer.GetCompatibleWithPlatform(BuildTarget.iOS))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, true); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } #endregion // iOS and tvOS #region General { PluginImporter importer = AssetImporter.GetAtPath("Assets/GameAnalytics/Plugins/GameAnalytics.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneLinux) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneLinux64) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneWindows) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneWindows64) || !importer.GetCompatibleWithPlatform(BuildTarget.WSAPlayer) || !importer.GetPlatformData(BuildTarget.WSAPlayer, "SDK").Equals("UWP") || !importer.GetPlatformData(BuildTarget.WSAPlayer, "ScriptingBackend").Equals("Il2Cpp"))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, true); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, true); importer.SetPlatformData(BuildTarget.WSAPlayer, "SDK", "UWP"); importer.SetPlatformData(BuildTarget.WSAPlayer, "ScriptingBackend", "Il2Cpp"); importer.SaveAndReimport(); } } #endregion // General #region Standalone { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/Windows/x86/sqlite3.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneWindows))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/Windows/x64/sqlite3.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneWindows64))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, true); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/Mac/sqlite3.bundle") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/Linux/sqlite3.so") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneLinux) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneLinux64) || !importer.GetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, true); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } #endregion // Standalone #region WebGL { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WebGL/GameAnalytics.WebGL.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WebGL))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, true); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WebGL/HandleIO.jslib") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WebGL))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, true); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WebGL/Mono.Data.Sqlite.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WebGL))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, true); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WebGL/sqlite.c") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WebGL))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, true); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WebGL/sqlite.h") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WebGL))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, true); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, false); importer.SaveAndReimport(); } } #endregion // WebGL #region WSA { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WSA/GameAnalytics.WSA.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WSAPlayer) || !importer.GetPlatformData(BuildTarget.WSAPlayer, "SDK").Equals("UWP") || !importer.GetPlatformData(BuildTarget.WSAPlayer, "ScriptingBackend").Equals("DotNet"))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, true); importer.SetPlatformData(BuildTarget.WSAPlayer, "SDK", "UWP"); importer.SetPlatformData(BuildTarget.WSAPlayer, "ScriptingBackend", "DotNet"); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WSA/Microsoft.Data.Sqlite.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WSAPlayer) || !importer.GetPlatformData(BuildTarget.WSAPlayer, "SDK").Equals("UWP"))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, true); importer.SetPlatformData(BuildTarget.WSAPlayer, "SDK", "UWP"); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WSA/x86/sqlite3.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WSAPlayer) || !importer.GetPlatformData(BuildTarget.WSAPlayer, "SDK").Equals("UWP") || !importer.GetPlatformData(BuildTarget.WSAPlayer, "CPU").Equals("X86"))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, true); importer.SetPlatformData(BuildTarget.WSAPlayer, "SDK", "UWP"); importer.SetPlatformData(BuildTarget.WSAPlayer, "CPU", "X86"); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WSA/x64/sqlite3.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WSAPlayer) || !importer.GetPlatformData(BuildTarget.WSAPlayer, "SDK").Equals("UWP") || !importer.GetPlatformData(BuildTarget.WSAPlayer, "CPU").Equals("X64"))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, true); importer.SetPlatformData(BuildTarget.WSAPlayer, "SDK", "UWP"); importer.SetPlatformData(BuildTarget.WSAPlayer, "CPU", "X64"); importer.SaveAndReimport(); } } { PluginImporter importer = AssetImporter.GetAtPath("Assets/Plugins/WSA/ARM/sqlite3.dll") as PluginImporter; if (importer != null && (importer.GetCompatibleWithAnyPlatform() || !importer.GetCompatibleWithPlatform(BuildTarget.WSAPlayer) || !importer.GetPlatformData(BuildTarget.WSAPlayer, "SDK").Equals("UWP") || !importer.GetPlatformData(BuildTarget.WSAPlayer, "CPU").Equals("ARM"))) { importer.SetCompatibleWithAnyPlatform(false); importer.SetCompatibleWithEditor(false); importer.SetCompatibleWithPlatform(BuildTarget.Android, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinux64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneLinuxUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXIntel64, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneOSXUniversal, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows, false); importer.SetCompatibleWithPlatform(BuildTarget.StandaloneWindows64, false); importer.SetCompatibleWithPlatform(BuildTarget.iOS, false); importer.SetCompatibleWithPlatform(BuildTarget.tvOS, false); importer.SetCompatibleWithPlatform(BuildTarget.WebGL, false); importer.SetCompatibleWithPlatform(BuildTarget.WSAPlayer, true); importer.SetPlatformData(BuildTarget.WSAPlayer, "SDK", "UWP"); importer.SetPlatformData(BuildTarget.WSAPlayer, "CPU", "ARM"); importer.SaveAndReimport(); } } #endregion // WSA }
private void GradientCreator() { GUILayout.Label("Gradient Creator", bigLabel); GUILayout.Space(20); GUILayout.Label("This feature can be used to create textures for the Color Ramp Effect", EditorStyles.boldLabel); EditorGUILayout.GradientField("Gradient", gradient, GUILayout.Height(25)); EditorGUILayout.BeginHorizontal(); { GUILayout.Label("Texture Size:", GUILayout.MaxWidth(145)); textureSizes = (TextureSizes)EditorGUILayout.EnumPopup(textureSizes, GUILayout.MaxWidth(200)); } EditorGUILayout.EndHorizontal(); int textureSize = (int)textureSizes; Texture2D gradTex = new Texture2D(textureSize, 1, TextureFormat.RGBA32, false); for (int i = 0; i < textureSize; i++) { gradTex.SetPixel(i, 0, gradient.Evaluate((float)i / (float)textureSize)); } gradTex.Apply(); GUILayout.Space(20); GUILayout.Label("Select the folder where new Gradient Textures will be saved", EditorStyles.boldLabel); HandleSaveFolderEditorPref("All1ShaderGradients", gradientSavesPath, "Gradient"); string prefSavedPath = PlayerPrefs.GetString("All1ShaderGradients") + "/"; if (Directory.Exists(prefSavedPath)) { EditorGUILayout.BeginHorizontal(); { GUILayout.Label("Gradient Texture Filtering: ", GUILayout.MaxWidth(170)); gradientFiltering = (FilterMode)EditorGUILayout.EnumPopup(gradientFiltering, GUILayout.MaxWidth(200)); } EditorGUILayout.EndHorizontal(); if (GUILayout.Button("Save Gradient Texture")) { string path = prefSavedPath + "ColorGradient.png"; if (System.IO.File.Exists(path)) { path = GetNewValidPath(path); } string texName = path.Replace(prefSavedPath, ""); path = EditorUtility.SaveFilePanel("Save texture as PNG", prefSavedPath, texName, "png"); if (path.Length != 0) { byte[] pngData = gradTex.EncodeToPNG(); if (pngData != null) { File.WriteAllBytes(path, pngData); } AssetDatabase.Refresh(); if (path.IndexOf("Assets/") >= 0) { string subPath = path.Substring(path.IndexOf("Assets/")); TextureImporter importer = AssetImporter.GetAtPath(subPath) as TextureImporter; if (importer != null) { Debug.Log("Gradient saved inside the project: " + subPath); importer.filterMode = gradientFiltering; importer.SaveAndReimport(); EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(subPath, typeof(Texture))); } } else { Debug.Log("Gradient saved outside the project: " + path); } } } } }
public override void OnInspectorGUI() { DrawDefaultInspector(); EditorGUILayout.HelpBox(helpText, MessageType.Info); if (GUILayout.Button("Take snapshot")) { var directions = new Quaternion[] { Quaternion.LookRotation(Vector3.forward), Quaternion.LookRotation(Vector3.back), Quaternion.LookRotation(Vector3.left), Quaternion.LookRotation(Vector3.right), Quaternion.LookRotation(Vector3.up, Vector3.back), Quaternion.LookRotation(Vector3.down, Vector3.forward) }; Camera tempCamera = null; foreach (SteamVR_Skybox target in targets) { var targetScene = target.gameObject.scene; var sceneName = Path.GetFileNameWithoutExtension(targetScene.path); var scenePath = Path.GetDirectoryName(targetScene.path); var assetPath = scenePath + "/" + sceneName; if (!AssetDatabase.IsValidFolder(assetPath)) { var guid = AssetDatabase.CreateFolder(scenePath, sceneName); assetPath = AssetDatabase.GUIDToAssetPath(guid); } var camera = target.GetComponent <Camera>(); if (camera == null) { if (tempCamera == null) { tempCamera = new GameObject().AddComponent <Camera>(); } camera = tempCamera; } var targetTexture = camera.targetTexture; if (camera.targetTexture == null) { targetTexture = new RenderTexture(1024, 1024, 24); targetTexture.antiAliasing = 8; camera.targetTexture = targetTexture; } var oldPosition = target.transform.localPosition; var oldRotation = target.transform.localRotation; var baseRotation = target.transform.rotation; var t = camera.transform; t.position = target.transform.position; camera.orthographic = false; camera.fieldOfView = 90; for (int i = 0; i < directions.Length; i++) { t.rotation = baseRotation * directions[i]; camera.Render(); // Copy to texture and save to disk. RenderTexture.active = targetTexture; var texture = new Texture2D(targetTexture.width, targetTexture.height, TextureFormat.ARGB32, false); texture.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0); texture.Apply(); RenderTexture.active = null; var assetName = string.Format(nameFormat, assetPath, target.name, i); System.IO.File.WriteAllBytes(assetName, texture.EncodeToPNG()); } if (camera != tempCamera) { target.transform.localPosition = oldPosition; target.transform.localRotation = oldRotation; } } if (tempCamera != null) { Object.DestroyImmediate(tempCamera.gameObject); } // Now that everything has be written out, reload the associated assets and assign them. AssetDatabase.Refresh(); foreach (SteamVR_Skybox target in targets) { var targetScene = target.gameObject.scene; var sceneName = Path.GetFileNameWithoutExtension(targetScene.path); var scenePath = Path.GetDirectoryName(targetScene.path); var assetPath = scenePath + "/" + sceneName; for (int i = 0; i < directions.Length; i++) { var assetName = string.Format(nameFormat, assetPath, target.name, i); var importer = AssetImporter.GetAtPath(assetName) as TextureImporter; #if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0) importer.textureFormat = TextureImporterFormat.RGB24; #else importer.textureCompression = TextureImporterCompression.Uncompressed; #endif importer.wrapMode = TextureWrapMode.Clamp; importer.mipmapEnabled = false; importer.SaveAndReimport(); var texture = AssetDatabase.LoadAssetAtPath <Texture>(assetName); target.SetTextureByIndex(i, texture); } } } else if (GUILayout.Button("Take stereo snapshot")) { const int width = 4096; const int height = width / 2; const int halfHeight = height / 2; var textures = new Texture2D[] { new Texture2D(width, height, TextureFormat.ARGB32, false), new Texture2D(width, height, TextureFormat.ARGB32, false) }; var timer = new System.Diagnostics.Stopwatch(); Camera tempCamera = null; foreach (SteamVR_Skybox target in targets) { timer.Start(); var targetScene = target.gameObject.scene; var sceneName = Path.GetFileNameWithoutExtension(targetScene.path); var scenePath = Path.GetDirectoryName(targetScene.path); var assetPath = scenePath + "/" + sceneName; if (!AssetDatabase.IsValidFolder(assetPath)) { var guid = AssetDatabase.CreateFolder(scenePath, sceneName); assetPath = AssetDatabase.GUIDToAssetPath(guid); } var camera = target.GetComponent <Camera>(); if (camera == null) { if (tempCamera == null) { tempCamera = new GameObject().AddComponent <Camera>(); } camera = tempCamera; } var fx = camera.gameObject.AddComponent <SteamVR_SphericalProjection>(); var oldTargetTexture = camera.targetTexture; var oldOrthographic = camera.orthographic; var oldFieldOfView = camera.fieldOfView; var oldAspect = camera.aspect; var oldPosition = target.transform.localPosition; var oldRotation = target.transform.localRotation; var basePosition = target.transform.position; var baseRotation = target.transform.rotation; var transform = camera.transform; int cellSize = int.Parse(target.StereoCellSize.ToString().Substring(1)); float ipd = target.StereoIpdMm / 1000.0f; int vTotal = halfHeight / cellSize; float dv = 90.0f / vTotal; // vertical degrees per segment float dvHalf = dv / 2.0f; var targetTexture = new RenderTexture(cellSize, cellSize, 24); targetTexture.wrapMode = TextureWrapMode.Clamp; targetTexture.antiAliasing = 8; camera.fieldOfView = dv; camera.orthographic = false; camera.targetTexture = targetTexture; // Render sections of a sphere using a rectilinear projection // and resample using a sphereical projection into a single panorama // texture per eye. We break into sections in order to keep the eye // separation similar around the sphere. Rendering alternates between // top and bottom sections, sweeping horizontally around the sphere, // alternating left and right eyes. for (int v = 0; v < vTotal; v++) { var pitch = 90.0f - (v * dv) - dvHalf; var uTotal = width / targetTexture.width; var du = 360.0f / uTotal; // horizontal degrees per segment var duHalf = du / 2.0f; var vTarget = v * halfHeight / vTotal; for (int i = 0; i < 2; i++) // top, bottom { if (i == 1) { pitch = -pitch; vTarget = height - vTarget - cellSize; } for (int u = 0; u < uTotal; u++) { var yaw = -180.0f + (u * du) + duHalf; var uTarget = u * width / uTotal; var xOffset = -ipd / 2 * Mathf.Cos(pitch * Mathf.Deg2Rad); for (int j = 0; j < 2; j++) // left, right { var texture = textures[j]; if (j == 1) { xOffset = -xOffset; } var offset = baseRotation * Quaternion.Euler(0, yaw, 0) * new Vector3(xOffset, 0, 0); transform.position = basePosition + offset; var direction = Quaternion.Euler(pitch, yaw, 0.0f); transform.rotation = baseRotation * direction; // vector pointing to center of this section var N = direction * Vector3.forward; // horizontal span of this section in degrees var phi0 = yaw - (du / 2); var phi1 = phi0 + du; // vertical span of this section in degrees var theta0 = pitch + (dv / 2); var theta1 = theta0 - dv; var midPhi = (phi0 + phi1) / 2; var baseTheta = Mathf.Abs(theta0) < Mathf.Abs(theta1) ? theta0 : theta1; // vectors pointing to corners of image closes to the equator var V00 = Quaternion.Euler(baseTheta, phi0, 0.0f) * Vector3.forward; var V01 = Quaternion.Euler(baseTheta, phi1, 0.0f) * Vector3.forward; // vectors pointing to top and bottom midsection of image var V0M = Quaternion.Euler(theta0, midPhi, 0.0f) * Vector3.forward; var V1M = Quaternion.Euler(theta1, midPhi, 0.0f) * Vector3.forward; // intersection points for each of the above var P00 = V00 / Vector3.Dot(V00, N); var P01 = V01 / Vector3.Dot(V01, N); var P0M = V0M / Vector3.Dot(V0M, N); var P1M = V1M / Vector3.Dot(V1M, N); // calculate basis vectors for plane var P00_P01 = P01 - P00; var P0M_P1M = P1M - P0M; var uMag = P00_P01.magnitude; var vMag = P0M_P1M.magnitude; var uScale = 1.0f / uMag; var vScale = 1.0f / vMag; var uAxis = P00_P01 * uScale; var vAxis = P0M_P1M * vScale; // update material constant buffer fx.Set(N, phi0, phi1, theta0, theta1, uAxis, P00, uScale, vAxis, P0M, vScale); camera.aspect = uMag / vMag; camera.Render(); RenderTexture.active = targetTexture; texture.ReadPixels(new Rect(0, 0, targetTexture.width, targetTexture.height), uTarget, vTarget); RenderTexture.active = null; } } } } // Save textures to disk. for (int i = 0; i < 2; i++) { var texture = textures[i]; texture.Apply(); var assetName = string.Format(nameFormat, assetPath, target.name, i); File.WriteAllBytes(assetName, texture.EncodeToPNG()); } // Cleanup. if (camera != tempCamera) { camera.targetTexture = oldTargetTexture; camera.orthographic = oldOrthographic; camera.fieldOfView = oldFieldOfView; camera.aspect = oldAspect; target.transform.localPosition = oldPosition; target.transform.localRotation = oldRotation; } else { tempCamera.targetTexture = null; } DestroyImmediate(targetTexture); DestroyImmediate(fx); timer.Stop(); Debug.Log(string.Format("Screenshot took {0} seconds.", timer.Elapsed)); } if (tempCamera != null) { DestroyImmediate(tempCamera.gameObject); } DestroyImmediate(textures[0]); DestroyImmediate(textures[1]); // Now that everything has be written out, reload the associated assets and assign them. AssetDatabase.Refresh(); foreach (SteamVR_Skybox target in targets) { var targetScene = target.gameObject.scene; var sceneName = Path.GetFileNameWithoutExtension(targetScene.path); var scenePath = Path.GetDirectoryName(targetScene.path); var assetPath = scenePath + "/" + sceneName; for (int i = 0; i < 2; i++) { var assetName = string.Format(nameFormat, assetPath, target.name, i); var importer = AssetImporter.GetAtPath(assetName) as TextureImporter; importer.mipmapEnabled = false; importer.wrapMode = TextureWrapMode.Repeat; #if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0) importer.SetPlatformTextureSettings("Standalone", width, TextureImporterFormat.RGB24); #else var settings = importer.GetPlatformTextureSettings("Standalone"); settings.textureCompression = TextureImporterCompression.Uncompressed; settings.maxTextureSize = width; importer.SetPlatformTextureSettings(settings); #endif importer.SaveAndReimport(); var texture = AssetDatabase.LoadAssetAtPath <Texture2D>(assetName); target.SetTextureByIndex(i, texture); } } } }
void OnGUI() { //Debug.Log (Application.dataPath); generalFold = EditorGUILayout.Foldout(generalFold, "General Settings"); if (generalFold) { GUILayout.Label("General Settings", EditorStyles.boldLabel); EditorGUILayout.HelpBox("Select the texture with the button below. Emission & Metallic textures are optional. Metallic shaders are experimental, expect issues.", MessageType.Info); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Image Texture"); //This little void allows me to open a file prompt looking for .png files (Must support transparency at the moment) if (GUILayout.Button("Select", GUILayout.Width(200))) { string path = EditorUtility.OpenFilePanel("Select Texture", "", "png"); if (path.Length != 0) { //The magical and still confusing process of reading bytes from the file into a var. var fileContent = File.ReadAllBytes(path); //Loading that magical var into the Texture2D's image slot. ShirtTex.LoadImage(fileContent); //This is the most important, as it applies the changes we have made to the texture. ShirtTex.Apply(); AssetDatabase.Refresh(); } } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Emission Texture"); if (GUILayout.Button("Select", GUILayout.Width(200))) { string path = EditorUtility.OpenFilePanel("Select Emission Texture", "", "png,jpeg,jpg"); if (path.Length != 0) { var fileContent = File.ReadAllBytes(path); ShirtEm.LoadImage(fileContent); ShirtEm.Apply(); mat.SetColor("_EmissionColor", Color.white); AssetDatabase.Refresh(); } } /*Honestly most of the following doesn't need explaining, it's just buttons and switches and sliders. * If you'd like to learn about how they work, I'd recommend searching "EditorGUILayout" and "GUILayout" and reading the unity documentation. * It's very helpful. * */ EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Metallic Texture"); if (GUILayout.Button("Select", GUILayout.Width(200))) { string path = EditorUtility.OpenFilePanel("Select Metallic Texture", "", "png"); if (path.Length != 0) { var fileContent = File.ReadAllBytes(path); ShirtMet.LoadImage(fileContent); ShirtMet.Apply(); mat.SetTexture("_MetallicGlossMap", ShirtMet); AssetDatabase.ImportAsset("Assets/Shirt_Assets/Resources/Bundles/Items/Shirts/Hoodie_Orange/Material.mat"); AssetDatabase.Refresh(); } UnityEditor.AssetDatabase.Refresh(); } EditorGUILayout.EndHorizontal(); smoothness = EditorGUILayout.Slider("Smoothness", smoothness, 0, 1, GUILayout.Width(350)); /*Honestly most of the following doesn't need explaining, it's just buttons and switches and sliders. * If you'd like to learn about how they work, I'd recommend searching "EditorGUILayout" and "GUILayout" and reading the unity documentation. * It's very helpful. * */ EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Reset Emission", GUILayout.Width(173))) { mat.SetColor("_EmissionColor", Color.black); var tempFile = File.ReadAllBytes(Application.dataPath + "/ClothingCreator/Icons/transparent.png"); ShirtEm.LoadImage(tempFile); ShirtEm.Apply(); } if (GUILayout.Button("Reset Metallic", GUILayout.Width(173))) { var tempFile = File.ReadAllBytes(Application.dataPath + "/ClothingCreator/Icons/black.png"); ShirtMet.LoadImage(tempFile); ShirtMet.Apply(); mat.SetFloat("_Metallic", 0); mat.SetTexture("_MetallicGlossMap", null); AssetDatabase.ImportAsset("Assets/Shirt_Assets/Resources/Bundles/Items/Shirts/Hoodie_Orange/Material.mat"); AssetDatabase.Refresh(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Texture Preview"); GUILayout.Label("In-Game Preview", GUILayout.Width(150)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Box(AssetPreview.GetAssetPreview(ShirtTex)); GUILayout.Box(ShirtScenePreview); EditorGUILayout.EndHorizontal(); camRotation = EditorGUILayout.Slider("Rotate Preview", camRotation, 0, 360, GUILayout.Width(350)); } bundleFold = EditorGUILayout.Foldout(bundleFold, "Bundler Settings"); if (bundleFold) { generateDats = EditorGUILayout.BeginToggleGroup("Generate .DAT Files", generateDats); EditorGUILayout.HelpBox("These are the stats files for your item.", MessageType.Info); itemName = EditorGUILayout.TextField("Item Name", itemName, GUILayout.Width(350)); itemDescription = EditorGUILayout.TextField("Item Description", itemDescription, GUILayout.Width(350)); EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("ID Number"); itemID = EditorGUILayout.IntSlider(itemID, 2000, 65000, GUILayout.Width(200)); EditorGUILayout.EndHorizontal(); shirtRarity = (RARENESS)EditorGUILayout.EnumPopup("Item Rarity", shirtRarity, GUILayout.Width(350)); /* * Currently unimplemented dynamic preview system for Width and Height of Item and storage size. Hopefully will be implemented at a later date. * * storageFold = EditorGUILayout.Foldout(storageFold, "Storage Preview"); * sizeFold = EditorGUILayout.Foldout (sizeFold, "Size Preview"); */ fireResistant = EditorGUILayout.Toggle("Fire Resistant", fireResistant, GUILayout.Width(350)); waterproof = EditorGUILayout.Toggle("Waterproof", waterproof, GUILayout.Width(350)); //Remind me to add a visual blueprint creator to this at some point standardBlueprints = EditorGUILayout.Toggle("Add Standard Blueprints", standardBlueprints, GUILayout.Width(350)); EditorGUILayout.HelpBox("The Standard Blueprints option adds the blueprint to scrap the shirt into cloth, and the blueprint to repair it with cloth.", MessageType.Info); customItemSize = EditorGUILayout.BeginToggleGroup("Custom Item Size", customItemSize); itemWidth = EditorGUILayout.IntSlider("Custom Item Width", itemWidth, 1, 5, GUILayout.Width(350)); itemHeight = EditorGUILayout.IntSlider("Custom Item Height", itemHeight, 1, 5, GUILayout.Width(350)); EditorGUILayout.HelpBox("This is how large in grid squares your item will take up. Disabling Custom Item Size will reset to the default size, 3 squares wide by 2 squares tall.", MessageType.Info); EditorGUILayout.EndToggleGroup(); armor = EditorGUILayout.BeginToggleGroup("Armor", armor); armorLevel = EditorGUILayout.IntSlider("Damage Absorption", armorLevel, 1, 100, GUILayout.Width(350)); GUILayout.Label(armorLevel + "% of any damage to the torso will be absorbed."); EditorGUILayout.EndToggleGroup(); GUILayout.Label("Item Storage Slots", EditorStyles.boldLabel); itemStorageWidth = EditorGUILayout.IntSlider("Storage Width", itemStorageWidth, 1, 15, GUILayout.Width(350)); itemStorageHeight = EditorGUILayout.IntSlider("Storage Height", itemStorageHeight, 1, 15, GUILayout.Width(350)); EditorGUILayout.HelpBox("This is how large in grid squares your item's storage slots will be when equipped. A good average is around 4-5 squares wide and tall.", MessageType.Info); EditorGUILayout.EndToggleGroup(); customNameString = EditorGUILayout.TextField("Custom File Name", customNameString, GUILayout.Width(350)); EditorGUILayout.HelpBox("This option is for advanced users who want to customize the name of mod files created. The standard option automatically removes spaces from the item name and uses that. If you aren't happy with that name being used as the File Name, use this to change it to a more preferable option.", MessageType.Info); if (itemNameFlat.Contains(" ")) { EditorGUILayout.HelpBox("Please note that any spaces added to the File Name input box will be automatically removed with spaces when processed.", MessageType.Warning); } KeepManifests = EditorGUILayout.Toggle("Keep Manifests", KeepManifests); cleanProject = EditorGUILayout.Toggle("Clean Project After Bundle", cleanProject); EditorGUILayout.HelpBox("This option allows your project to be automatically set up for the next item, i.e removing any objects currently in scene and deleting the Shirt_Assets file. Don't use this if you plan on making more shirts after this!", MessageType.Info); if (GUILayout.Button("Create Mod Files", GUILayout.Width(350))) { if (generateDats == false && customNameString == "" || itemName == "" && customNameString == "") { EditorGUILayout.HelpBox("You must specify a name for the mod, if you choose not to generate .DAT files. Enter one in the Custom File Name slot.", MessageType.Warning); } else { //The following line allows for the user inputted Item Name to have a dual purpose system, in which it is used to name the file and the in-game item. It removes any spaces with underlines, to maintain styling with SDG assets and to prevent any errors. //itemNameFlat = itemName.Replace (" ", "_"); /* Because I opted for an ease of use system in which the armor slider is shown as a percentage of damage absorbed, I have to convert it to the method used in the dat files. Basically, in the dat files it uses a multiplier like 0.55, which would multiply any incoming damage by 0.55. * This multiplier would essentially negate 45% of the damage. In order to make it easier to understand for inexperienced modders, I simply have to subtract * the float value I created earlier out of 100 to get the percentage of armor negated, then divide by 100 to get a decimal. Oh, and since you're here and reading this, I just wanted to say congrats to you for either attempting to learn programming or wanting to see how this works. You're * going to go far, kid. :) * */ Debug.Log(100 - armorLevel); actualArmor = (double)(100 - armorLevel) / 100; if (customNameString != "") { itemNameFlat = customNameString.Replace(" ", "_"); Debug.Log("cust name:" + itemNameFlat); Debug.Log(customNameString != ""); Debug.Log(customNameString != null); } else { itemNameFlat = itemName.Replace(" ", "_"); } //This is the new weird and wonky Unity 5+ asset bundling system. While I've never coded in Unity 4, this system definitely seems more complex. The function below gets the path to the Shirt_Assets folder and marks it as a "unity3d" bundle. This removes the need for user based renaming. AssetImporter.GetAtPath("Assets/Shirt_Assets").SetAssetBundleNameAndVariant("temp", "unity3d"); //Prompt for the user to select what folder they would like to save to. The window is called "Select Bundle Folder", the path is the string it returns, and "Mod Folder" is the default name shown when the window opens. path = EditorUtility.SaveFolderPanel("Select Bundle Folder", path, "Mod Folder"); System.IO.Directory.CreateDirectory(Application.dataPath + "/" + itemNameFlat + "/test"); Debug.Log(Application.dataPath + "/" + itemNameFlat + "/test"); System.IO.Directory.Delete(Application.dataPath + "/" + itemNameFlat + "/test", true); //Checking whether or not the user enabled creation of .dat files if (generateDats) { using (StreamWriter sw = File.CreateText(Application.dataPath + "/" + itemNameFlat + "/" + itemNameFlat + ".dat")) { Debug.Log(Application.dataPath + "/" + itemNameFlat + "/" + itemNameFlat + ".dat"); sw.WriteLine("Type Shirt"); sw.WriteLine("Rarity " + shirtRarity); sw.WriteLine("Useable Clothing"); sw.WriteLine("ID " + itemID); //This is added to make it look more human, human written dat files feature some spaces between lines sw.WriteLine(" "); if (customItemSize) { sw.WriteLine("Size_X " + itemWidth); sw.WriteLine("Size_Y " + itemHeight); sw.WriteLine("Size_Z 0.6"); } if (!customItemSize) { //If the user did not toggle custom item sizes, the default 3x2 will be used instead. sw.WriteLine("Size_X 3"); sw.WriteLine("Size_Y 2"); sw.WriteLine("Size_Z 0.6"); } sw.WriteLine(" "); sw.WriteLine("Width " + itemStorageWidth); sw.WriteLine("Height " + itemStorageHeight); sw.WriteLine(" "); if (armor) { sw.WriteLine("Armor " + actualArmor); sw.WriteLine(" "); } if (fireResistant) { sw.WriteLine("Proof_Fire"); } if (waterproof) { sw.WriteLine("Proof_Water"); } if (standardBlueprints) { sw.WriteLine(" "); sw.WriteLine("Blueprints 2"); sw.WriteLine("Blueprint_0_Type Apparel"); sw.WriteLine("Blueprint_0_Supply_0_ID 1421"); sw.WriteLine("Blueprint_0_Product 66"); sw.WriteLine("Blueprint_0_Products 3"); sw.WriteLine("Blueprint_0_Build 32"); sw.WriteLine("Blueprint_1_Type Repair"); sw.WriteLine("Blueprint_1_Supplies 1"); sw.WriteLine("Blueprint_1_Supply_0_ID 66"); sw.WriteLine("Blueprint_1_Supply_0_Amount 3"); sw.WriteLine("Blueprint_1_Build 32"); } } using (StreamWriter sx = File.CreateText(Application.dataPath + "/" + itemNameFlat + "/English.dat")) { sx.WriteLine("Name " + itemName); sx.WriteLine("Description " + itemDescription); } /* * NOTICE: THIS IS THE BROKEN AND LEGACY WAY I ATTEMPTED TO WRITE TO DAT FILES WITH. IT DOES NOT WORK AND IS ONLY BEING SAVED FOR THE SAKE OF POSTERITY. DO NOT ATTEMPT TO USE AS IT IS COMPLETELY BROKEN. * Basically, what I'm doing here is checking what the user requested to be added to any .dat files and writing it. The dat file is generated automatically if it doesn't exist (which it shouldn't) when the first WriteAllText is ran. * System.IO.File.WriteAllText (path + "/English.dat", "Name " + itemName + "\n" + "Description " + itemDescription); * System.IO.File.WriteAllText (path + "/" + itemNameFlat + ".dat", "\nType Shirt \n Rarity " + shirtRarity + "\n Useable Clothing \n ID " + itemID + "\n"); * if (customItemSize) { * System.IO.File.WriteAllText (path + "/" + itemNameFlat + ".dat", "Size_X " + itemWidth + "\n Size_Y " + itemHeight + "\n Size_Z 0.6 \n"); * } * if (!customItemSize) { * //If the user did not toggle custom item sizes, the default 3x2 will be used instead. * System.IO.File.WriteAllText (path + "/" + itemNameFlat + ".dat", "Size_X 3\n Size_Y 2\n Size_Z 0.6 \n"); * } * System.IO.File.WriteAllText (path + "/" + itemNameFlat + ".dat", "Width " + itemStorageWidth + "\n Height " + itemHeight); * if (armor) * System.IO.File.WriteAllText (path + "/" + itemNameFlat + ".dat", "\n Armor " + actualArmor); * if (fireResistant) * //In case you're wondering, \n is what's called an Escape Sequence. Basically, it allows you to escape the quotes and add extra stuff. I.e you can use \n to make a new line, \" to add a quote, and "\ " to add spaces when not in quotes. * System.IO.File.WriteAllText (path + "/" + itemNameFlat + ".dat", "\n Proof_Fire"); * if (waterproof) * System.IO.File.WriteAllText (path + "/" + itemNameFlat + ".dat", "\n Proof_Water"); * if (standardBlueprints) { * System.IO.File.WriteAllText (path + "/" + itemNameFlat + ".dat", "\nBlueprints 2 \nBlueprint_0_Type Apparel\nBlueprint_0_Supply_0_ID 1421\nBlueprint_0_Product 66\nBlueprint_0_Products 3\nBlueprint_0_Build 32\nBlueprint_1_Type Repair\nBlueprint_1_Supplies 1\nBlueprint_1_Supply_0_ID 66\nBlueprint_1_Supply_0_Amount 3\nBlueprint_1_Build 32\n"); * } */ } //Bundle the Unity3d file and place it in the same path folder mentioned early marked path. This isn't a reusable script as it doesn't carry over the parameters like a reusable void would, i.e getting the local class variable rather than bundleAssets(String path); bundleAssets(); UnityEditor.AssetDatabase.Refresh(); File.Delete(Application.dataPath + "/" + itemNameFlat + ".meta"); File.Move(Application.dataPath + "/" + itemNameFlat + "/temp.unity3d", Application.dataPath + "/" + itemNameFlat + "/" + itemNameFlat + ".unity3d"); File.Move(Application.dataPath + "/" + itemNameFlat, path + "/" + itemNameFlat); File.Delete(path + "/" + itemNameFlat + "/English.dat.meta"); File.Delete(path + "/" + itemNameFlat + "/temp.unity3d.manifest"); File.Delete(path + "/" + itemNameFlat + "/temp.unity3d.manifest.meta"); File.Delete(path + "/" + itemNameFlat + "/temp.unity3d.meta"); File.Delete(path + "/" + itemNameFlat + "/" + itemNameFlat); File.Delete(path + "/" + itemNameFlat + "/" + itemNameFlat + ".manifest"); File.Delete(path + "/" + itemNameFlat + "/" + itemNameFlat + ".meta"); File.Delete(path + "/" + itemNameFlat + "/" + itemNameFlat + ".manifest.meta"); File.Delete(path + "/" + itemNameFlat + "/" + itemNameFlat + ".dat.meta"); Debug.Log(Application.dataPath); } } if (generateDats == false && customNameString == "" || itemName == "" && customNameString == "") { EditorGUILayout.HelpBox("You must specify a name for the mod, in either the Item Name slot or in the Custom Name slot if you have chosen not to generate .DATs", MessageType.Error); } } devFold = EditorGUILayout.Foldout(devFold, "Dev Tests"); if (devFold) { EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Clean Tags/Layers", GUILayout.Width(150))) { RemoveTag("Logic"); RemoveTag("Enemy"); RemoveTag("Viewmodel"); RemoveTag("Debris"); RemoveTag("Item"); RemoveTag("Resource"); RemoveTag("Large"); RemoveTag("Medium"); RemoveTag("Small"); RemoveTag("Sky"); RemoveTag("Environment"); RemoveTag("Water"); RemoveTag("Ground"); RemoveTag("Clip"); RemoveTag("Navmesh"); RemoveTag("Zombie"); RemoveTag("Agent"); RemoveTag("Ladder"); RemoveTag("Vehicle"); RemoveTag("Barricade"); RemoveTag("Structure"); RemoveTag("Tire"); RemoveTag("Trap"); RemoveTag("Ground2"); RemoveTag("Animal"); RemoveTag("UI"); RemoveTag("Border"); RemoveLayer("Logic"); RemoveLayer("Player"); RemoveLayer("Enemy"); RemoveLayer("Viewmodel"); RemoveLayer("Debris"); RemoveLayer("Item"); RemoveLayer("Resource"); RemoveLayer("Large"); RemoveLayer("Medium"); RemoveLayer("Small"); RemoveLayer("Sky"); RemoveLayer("Environment"); RemoveLayer("Ground"); RemoveLayer("Clip"); RemoveLayer("Navmesh"); RemoveLayer("Zombie"); RemoveLayer("Agent"); RemoveLayer("Ladder"); RemoveLayer("Vehicle"); RemoveLayer("Barricade"); RemoveLayer("Structure"); RemoveLayer("Tire"); RemoveLayer("Trap"); RemoveLayer("Ground2"); RemoveLayer("Animal"); RemoveLayer("UI"); RemoveLayer("Border"); RemoveLayer("Entity"); } if (GUILayout.Button("Create Tags/Layers", GUILayout.Width(150))) { AddTag("Logic"); AddTag("Enemy"); AddTag("Viewmodel"); AddTag("Debris"); AddTag("Item"); AddTag("Resource"); AddTag("Large"); AddTag("Medium"); AddTag("Small"); AddTag("Sky"); AddTag("Environment"); AddTag("Water"); AddTag("Ground"); AddTag("Clip"); AddTag("Navmesh"); AddTag("Zombie"); AddTag("Agent"); AddTag("Ladder"); AddTag("Vehicle"); AddTag("Barricade"); AddTag("Structure"); AddTag("Tire"); AddTag("Trap"); AddTag("Ground2"); AddTag("Animal"); AddTag("UI"); AddTag("Border"); AddLayer("Logic"); AddLayer("Player"); AddLayer("Enemy"); AddLayer("Viewmodel"); AddLayer("Debris"); AddLayer("Item"); AddLayer("Resource"); AddLayer("Large"); AddLayer("Medium"); AddLayer("Small"); AddLayer("Sky"); AddLayer("Environment"); AddLayer("Ground"); AddLayer("Clip"); AddLayer("Navmesh"); AddLayer("Zombie"); AddLayer("Agent"); AddLayer("Ladder"); AddLayer("Vehicle"); AddLayer("Barricade"); AddLayer("Structure"); AddLayer("Tire"); AddLayer("Trap"); AddLayer("Ground2"); AddLayer("Animal"); AddLayer("UI"); AddLayer("Border"); AddLayer("Entity"); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Reset Scene", GUILayout.Width(150))) { AssetDatabase.DeleteAsset("Assets/Shirt_Assets"); GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType <GameObject>(); foreach (GameObject go in allObjects) { if (go.activeInHierarchy && (go.name != "Main Camera") && (go.name != "Directional Light")) { DestroyImmediate(go); } } Debug.Log("Forgot to tell you, this crashes the window. Just reopen it, and ignore any errors."); window.Close(); UnityEditor.AssetDatabase.Refresh(); } if (GUILayout.Button("Reimport PKGs", GUILayout.Width(150))) { AssetDatabase.ImportPackage("Assets/ClothingCreator/PKGs/Shirt.unitypackage", importdialog); } EditorGUILayout.EndHorizontal(); importdialog = EditorGUILayout.ToggleLeft("Import Dialogue", importdialog); displayErrors = EditorGUILayout.ToggleLeft("Display Errors", displayErrors); } }
/// <summary> /// 设置贴图 /// </summary> /// <param name="assetPath"></param> public static void SetTextureByTextureType(string assetPath) { //初始化忽略列表 InitIgnoreList(); //UI贴图判断 if (!assetPath.Contains(TEXTURE_ASSET_PATH)) { return; } //忽略列表判断 if (IgnoreFormatList.Contains(assetPath)) { return; } Texture2D cTexture2D = AssetDatabase.LoadAssetAtPath <Texture2D>(assetPath); if (cTexture2D == null) { Debug.LogError("Texture Is Nil Path : " + assetPath); return; } TextureImporter ti = AssetImporter.GetAtPath(assetPath) as TextureImporter; bool is2NSize = Is2NSizeTexture(cTexture2D); bool isTransparent = ti.DoesSourceTextureHaveAlpha(); //------------------Pc设置 var pfStandalone = ti.GetPlatformTextureSettings("Standalone"); pfStandalone.overridden = true; pfStandalone.resizeAlgorithm = TextureResizeAlgorithm.Mitchell; if (is2NSize) { pfStandalone.format = isTransparent ? TextureImporterFormat.DXT5 :TextureImporterFormat.DXT1; } else { pfStandalone.format = isTransparent ? TextureImporterFormat.RGBA32 : TextureImporterFormat.RGB16; } ti.SetPlatformTextureSettings(pfStandalone); pfStandalone.overridden = false; //-----------------Ios设置 var pfIPhone = ti.GetPlatformTextureSettings("iPhone"); pfIPhone.overridden = true; pfIPhone.resizeAlgorithm = TextureResizeAlgorithm.Mitchell; if (is2NSize) { pfIPhone.format = isTransparent ? TextureImporterFormat.ASTC_RGBA_4x4 : TextureImporterFormat.ASTC_RGB_4x4; } else { pfIPhone.format = isTransparent ? TextureImporterFormat.ASTC_RGBA_4x4 : TextureImporterFormat.RGB16; } ti.SetPlatformTextureSettings(pfIPhone); pfIPhone.overridden = false; //-----------------Android设置 var pfAndroid = ti.GetPlatformTextureSettings("Android"); pfAndroid.overridden = true; pfAndroid.resizeAlgorithm = TextureResizeAlgorithm.Mitchell; if (is2NSize) { pfAndroid.format = isTransparent ? TextureImporterFormat.ETC2_RGBA8 : TextureImporterFormat.ETC_RGB4; } else { pfAndroid.format = isTransparent ? TextureImporterFormat.RGBA16 : TextureImporterFormat.RGB16; } pfAndroid.androidETC2FallbackOverride = AndroidETC2FallbackOverride.UseBuildSettings; ti.SetPlatformTextureSettings(pfAndroid); pfAndroid.overridden = false; }
private void RenderSkinnedMesh(SkinnedMeshRenderer SMR, GameObject currentGO) { //make a copy of the source mesh Mesh sourceMesh = SMR.sharedMesh; /* * for (int x = 0; x < sourceMesh.blendShapeCount; x++) * { * FinalBSs.Add(sourceMesh.GetBlendShapeName(x)); * FinalBSWeights.Add(SMR.GetBlendShapeWeight(x)); * } */ foreach (Matrix4x4 matrix in sourceMesh.bindposes) { FinalBPs.Add(matrix); } //for every submesh, do all the work. for (int x = 0; x < sourceMesh.subMeshCount; x++) { List <Vector3> SMVerts = new List <Vector3>(); List <Vector2> SMUVs = new List <Vector2>(); List <Color32> SMVCs = new List <Color32>(); // List<int> SMTris = new List<int>(); List <BoneWeight> SMBWs = new List <BoneWeight>(); //triangle arrays point to the array index of the vertices in the vertex array int[] triList = sourceMesh.GetTriangles(x); //submesh's index number corresponds to the material index of the meshrendere component //get the diffuse texture. Hopefully the shader obeys the standard naming convention.. string path = AssetDatabase.GetAssetPath(SMR.sharedMaterials[x].GetTexture("_MainTex")); TextureImporter A = (TextureImporter)AssetImporter.GetAtPath(path); A.isReadable = true; AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate); Texture2D tex = (Texture2D)SMR.sharedMaterials[x].GetTexture("_MainTex"); Color matColor = SMR.sharedMaterials[x].GetColor("_Color"); //Coloring will not work with nonsquare textures. //we only want to go as far as 32x32 int mipAmount = tex.mipmapCount - 4;//(int)Mathf.Log((int)tex.width)+1; mipLevel = PickMipLevel(tex, mipAmount); if (mipLevel > 0) //if we chose to do blur amount.. { int mipSize = (int)Mathf.Pow(2f, (mipAmount - (mipLevel - 1)) + 4); //+4 since we are raising 2 to the x power. Color[] mcs = tex.GetPixels(0, 0, mipSize, mipSize, mipLevel - 2); tex = new Texture2D(mipSize, mipSize, TextureFormat.ARGB32, false); tex.SetPixels(mcs); } //to facet the submesh, go through each triangle. get each vertex, add it to an new vertex array. do same with uvs and boneweights for (int t = 0; t < triList.Length; t++) { //add the vertex to the new array. SMVerts.Add(sourceMesh.vertices[triList[t]]); SMUVs.Add(sourceMesh.uv[triList[t]]); //Add the bone weights if (sourceMesh.boneWeights.Length > 0) { SMBWs.Add(sourceMesh.boneWeights[triList[t]]); } } //make vertex colors from the diffuse but using the uvs and verts of the mesh we're making //second time around, vert length is already b for (int z = 0; z < SMVerts.Count; z++) { if (filterBilinear) { float UVx = SMUVs[z].x; float UVy = SMUVs[z].y; SMVCs.Add(((tex.GetPixelBilinear(UVx, UVy) + (Color32)brightenColor)) * (Color32)matColor); } else { int UVx = (int)(SMUVs[z].x * (tex.width)); int UVy = (int)(SMUVs[z].y * (tex.width)); SMVCs.Add(((tex.GetPixel(UVx, UVy) + (Color32)brightenColor)) * (Color32)matColor); } } //faceted submesh uv, verts, vert colors ready for the submesh. Add them to the master lists. foreach (Vector3 v in SMVerts) { FinalVerts.Add(v); } foreach (Vector2 v in SMUVs) { FinalUVS.Add(v); } foreach (Color32 c in SMVCs) { FinalVCs.Add(c); } foreach (BoneWeight b in SMBWs) { FinalBWs.Add(b); } } //all done, now recreate the triangle index for the new mesh, then average the vertex colors. for (int l = 0; l < FinalVerts.Count; l++) { FinalTris.Add(l); } //average the color to get faceted color for (int v = 0; v < FinalTris.Count; v += 3) { Color32 avg; int v1 = FinalTris[v]; int v2 = FinalTris[v + 1]; int v3 = FinalTris[v + 2]; Vector3 c1 = new Vector3(FinalVCs[v1].r, FinalVCs[v1].g, FinalVCs[v1].b); Vector3 c2 = new Vector3(FinalVCs[v2].r, FinalVCs[v2].g, FinalVCs[v2].b); Vector3 c3 = new Vector3(FinalVCs[v3].r, FinalVCs[v3].g, FinalVCs[v3].b); Vector3 avgC = (c1 + c2 + c3) / 3; avg = new Color32((byte)avgC.x, (byte)avgC.y, (byte)avgC.z, 1); FinalVCs[v1] = avg; FinalVCs[v2] = avg; FinalVCs[v3] = avg; } }
static void FixUnreadableSceneTexturesUsedForLidarSensor(bool selectOnly = true) { var tex2D_texImporter_map = new Dictionary <Texture2D, AssetImporter>(); var guids = AssetDatabase.FindAssets("t:texture2d", null); foreach (var guid in guids) { var path = AssetDatabase.GUIDToAssetPath(guid); var tex2D = AssetDatabase.LoadAssetAtPath <Texture2D>(path); if (tex2D != null) { tex2D_texImporter_map.Add(tex2D, AssetImporter.GetAtPath(path) as TextureImporter); } } var rends = FindObjectsOfType <Renderer>(); var unreadableTexturesUsedForLidar = new List <Texture2D>(); var visited = new HashSet <Texture2D>(); foreach (var rend in rends) { var meshCol = rend.GetComponent <MeshCollider>(); if (meshCol != null && meshCol.enabled) { var mainTex = rend.sharedMaterial?.mainTexture; var tex2D = mainTex != null ? (mainTex as Texture2D) : null; if (tex2D != null) { if (tex2D_texImporter_map.ContainsKey(tex2D)) { var astImporter = tex2D_texImporter_map[tex2D] as TextureImporter; if (!astImporter.isReadable) { if (!visited.Contains(tex2D)) { unreadableTexturesUsedForLidar.Add(tex2D); visited.Add(tex2D); if (selectOnly) { Debug.Log($"{tex2D.name} was not readable, put in selection."); } else { astImporter.isReadable = true; EditorUtility.SetDirty(astImporter); astImporter.SaveAndReimport(); Debug.Log($"{tex2D.name} was not readable, enabled now."); } } } } } } } if (selectOnly) { Selection.objects = unreadableTexturesUsedForLidar.ToArray(); } Debug.Log($"#################### processed {unreadableTexturesUsedForLidar.Count} texture assets ####################"); }
IEnumerator ImportAsset(string _directory, Ring _ring) { _hasRing = false; if (_ring != null) { _hasRing = true; } while (!System.IO.File.Exists(Application.dataPath + _directory + "/Assets/TextureMaps.png")) { yield return(null); } while (!System.IO.File.Exists(Application.dataPath + _directory + "/Assets/TexturePalette.png")) { yield return(null); } while (!System.IO.File.Exists(Application.dataPath + _directory + "/Assets/TextureBodyNormal.png")) { yield return(null); } while (!System.IO.File.Exists(Application.dataPath + _directory + "/Assets/TextureCapNormal.png")) { yield return(null); } while (!System.IO.File.Exists(Application.dataPath + _directory + "/Assets/TextureStormMask.png")) { yield return(null); } if (_hasRing) { while (!System.IO.File.Exists(Application.dataPath + _directory + "/Assets/TextureRing.png")) { yield return(null); } } AssetDatabase.ImportAsset("Assets" + _directory + "/Assets/TextureMaps.png", ImportAssetOptions.ForceUpdate); TextureImporter _ti; if (PlayerSettings.colorSpace == ColorSpace.Linear) { _ti = (TextureImporter)AssetImporter.GetAtPath("Assets" + _directory + "/Assets/TextureMaps.png"); _ti.sRGBTexture = false; EditorUtility.SetDirty(_ti); _ti.SaveAndReimport(); } AssetDatabase.ImportAsset("Assets" + _directory + "/Assets/TexturePalette.png", ImportAssetOptions.ForceUpdate); if (PlayerSettings.colorSpace == ColorSpace.Linear) { _ti = (TextureImporter)AssetImporter.GetAtPath("Assets" + _directory + "/Assets/TexturePalette.png"); _ti.sRGBTexture = false; EditorUtility.SetDirty(_ti); _ti.SaveAndReimport(); } AssetDatabase.ImportAsset("Assets" + _directory + "/Assets/TextureBodyNormal.png", ImportAssetOptions.ForceUpdate); _ti = (TextureImporter)AssetImporter.GetAtPath("Assets" + _directory + "/Assets/TextureBodyNormal.png"); _ti.textureType = TextureImporterType.NormalMap; if (PlayerSettings.colorSpace == ColorSpace.Linear) { _ti.sRGBTexture = false; } EditorUtility.SetDirty(_ti); _ti.SaveAndReimport(); AssetDatabase.ImportAsset("Assets" + _directory + "/Assets/TextureCapNormal.png", ImportAssetOptions.ForceUpdate); _ti = (TextureImporter)AssetImporter.GetAtPath("Assets" + _directory + "/Assets/TextureCapNormal.png"); if (PlayerSettings.colorSpace == ColorSpace.Linear) { _ti.sRGBTexture = false; } _ti.textureType = TextureImporterType.NormalMap; EditorUtility.SetDirty(_ti); _ti.SaveAndReimport(); AssetDatabase.ImportAsset("Assets" + _directory + "/Assets/TextureStormMask.png", ImportAssetOptions.ForceUpdate); if (PlayerSettings.colorSpace == ColorSpace.Linear) { _ti = (TextureImporter)AssetImporter.GetAtPath("Assets" + _directory + "/Assets/TextureStormMask.png"); _ti.sRGBTexture = false; EditorUtility.SetDirty(_ti); _ti.SaveAndReimport(); } if (_hasRing) { AssetDatabase.ImportAsset("Assets" + _directory + "/Assets/TextureRing.png", ImportAssetOptions.ForceUpdate); if (PlayerSettings.colorSpace == ColorSpace.Linear) { _ti = (TextureImporter)AssetImporter.GetAtPath("Assets" + _directory + "/Assets/TextureRing.png"); _ti.sRGBTexture = false; EditorUtility.SetDirty(_ti); _ti.SaveAndReimport(); } } Texture2D _tex2DMaps = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets" + _directory + "/Assets/TextureMaps.png"); Texture2D _tex2DPalette = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets" + _directory + "/Assets/TexturePalette.png"); Texture2D _tex2DBodyNormal = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets" + _directory + "/Assets/TextureBodyNormal.png"); Texture2D _tex2DCapNormal = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets" + _directory + "/Assets/TextureCapNormal.png"); Texture2D _tex2DStormMask = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets" + _directory + "/Assets/TextureStormMask.png"); Texture2D _tex2DRing = new Texture2D(2, 2); if (_hasRing) { _tex2DRing = AssetDatabase.LoadAssetAtPath <Texture2D>("Assets" + _directory + "/Assets/TextureRing.png"); } GameObject _goPlanet = new GameObject(); GameObject _goRing; Material _planetMaterial; if (PlayerSettings.colorSpace == ColorSpace.Linear) { _planetMaterial = new Material(Shader.Find("ProceduralPlanets/GasPlanetLinear")); } else { _planetMaterial = new Material(Shader.Find("ProceduralPlanets/GasPlanetGamma")); } if (_hasRing) { _goRing = new GameObject(); _goRing.name = "Ring"; _goRing.transform.SetParent(_goPlanet.transform); RingStatic _rs = _goRing.AddComponent <RingStatic>(); _rs.materials[0] = new Material(Shader.Find("ProceduralPlanets/Ring")); _rs.materials[1] = new Material(Shader.Find("ProceduralPlanets/Ring")); _rs.materials[0].SetTexture("_MainTex", _tex2DRing); _rs.materials[1].SetTexture("_MainTex", _tex2DRing); _rs.materials[0].renderQueue = 2800; _rs.materials[1].renderQueue = 3200; _rs.ringInnerRadius = _ring.GetPropertyFloatLerp("innerRadius") * 6.0f; _rs.ringOuterRadius = _ring.GetPropertyFloatLerp("outerRadius") * 6.0f; AssetDatabase.CreateAsset(_rs.materials[0], "Assets" + _directory + "/Assets/RingClose.mat"); AssetDatabase.CreateAsset(_rs.materials[1], "Assets" + _directory + "/Assets/RingFar.mat"); System.IO.StreamWriter _writerRing = new System.IO.StreamWriter("Assets" + _directory + "/Assets/jsonRingSettings.txt", false); _writerRing.WriteLine(_ring.ExportToJSON(Ring.StringFormat.JSON_EASY_READ)); _writerRing.Close(); AssetDatabase.ImportAsset("Assets" + _directory + "/Assets/jsonRingSettings.txt", ImportAssetOptions.ForceUpdate); } _planetMaterial.SetTexture("_BodyTexture", _tex2DMaps); _planetMaterial.SetTexture("_CapTexture", _tex2DMaps); _planetMaterial.SetTexture("_PaletteLookup", _tex2DPalette); _planetMaterial.SetTexture("_BodyNormal", _tex2DBodyNormal); _planetMaterial.SetTexture("_CapNormal", _tex2DCapNormal); _planetMaterial.SetTexture("_StormMask", _tex2DStormMask); _target.Update(); int _hTiling = (int)GetPropertyFloat("horizontalTiling").FindPropertyRelative("value").floatValue; int _vTiling = (int)GetPropertyFloat("verticalTiling").FindPropertyRelative("value").floatValue; float _stormIndex = (int)(GetPropertyFloat("stormMaskIndex").FindPropertyRelative("value").floatValue *(float)(_hTiling * _vTiling)); _planetMaterial.SetInt("_HTiling", _hTiling); _planetMaterial.SetInt("_VTiling", _vTiling); _planetMaterial.SetFloat("_Banding", Mathf.Lerp(GetPropertyFloat("banding").FindPropertyRelative("minValue").floatValue, GetPropertyFloat("banding").FindPropertyRelative("maxValue").floatValue, GetPropertyFloat("banding").FindPropertyRelative("value").floatValue)); _planetMaterial.SetFloat("_Solidness", Mathf.Lerp(GetPropertyFloat("solidness").FindPropertyRelative("minValue").floatValue, GetPropertyFloat("solidness").FindPropertyRelative("maxValue").floatValue, GetPropertyFloat("solidness").FindPropertyRelative("value").floatValue)); _planetMaterial.SetFloat("_Faintness", Mathf.Lerp(GetPropertyFloat("faintness").FindPropertyRelative("minValue").floatValue, GetPropertyFloat("faintness").FindPropertyRelative("maxValue").floatValue, GetPropertyFloat("faintness").FindPropertyRelative("value").floatValue)); _planetMaterial.SetFloat("_StormMaskIndex", (int)_stormIndex); _planetMaterial.SetFloat("_StormTint", Mathf.Lerp(GetPropertyFloat("stormTint").FindPropertyRelative("minValue").floatValue, GetPropertyFloat("stormTint").FindPropertyRelative("maxValue").floatValue, GetPropertyFloat("stormTint").FindPropertyRelative("value").floatValue)); _planetMaterial.SetFloat("_AtmosphereFalloff", Mathf.Lerp(GetPropertyFloat("atmosphereFalloff").FindPropertyRelative("minValue").floatValue, GetPropertyFloat("atmosphereFalloff").FindPropertyRelative("maxValue").floatValue, GetPropertyFloat("atmosphereFalloff").FindPropertyRelative("value").floatValue)); _planetMaterial.SetColor("_ColorTwilight", GetPropertyColor("twilightColor").FindPropertyRelative("color").colorValue); _planetMaterial.SetColor("_AtmosphereColor", GetPropertyColor("atmosphereColor").FindPropertyRelative("color").colorValue); _planetMaterial.SetColor("_StormColor", GetPropertyColor("stormColor").FindPropertyRelative("color").colorValue); _planetMaterial.SetColor("_FaintnessColor", GetPropertyColor("faintnessColor").FindPropertyRelative("color").colorValue); MeshRenderer _mr = _goPlanet.AddComponent <MeshRenderer>(); _goPlanet.AddComponent <MeshFilter>(); _mr.material = _planetMaterial; _goPlanet.AddComponent <GasPlanetStatic>(); AssetDatabase.CreateAsset(_planetMaterial, "Assets" + _directory + "/Assets/GasPlanet.mat"); //PrefabUtility.CreatePrefab("Assets" + _directory + "/GasPlanetPrefab.prefab", _goPlanet); PrefabUtility.SaveAsPrefabAsset(_goPlanet, "Assets" + _directory + "/GasPlanetPrefab.prefab"); System.IO.StreamWriter _writer = new System.IO.StreamWriter("Assets" + _directory + "/Assets/jsonPlanetSettings.txt", false); _writer.WriteLine(_script.ExportToJSON(SimpleJSON.StringFormat.JSON_EASY_READ)); _writer.Close(); AssetDatabase.ImportAsset("Assets" + _directory + "/Assets/jsonPlanetSettings.txt", ImportAssetOptions.ForceUpdate); DestroyImmediate(_goPlanet); Debug.Log("Planet Prefab Created: " + _directory); }
/// <summary> /// Generate the selected water tile /// </summary> /// <param name="path"></param> /// <param name="sub_blocks_water"></param> /// <param name="sub_blocks_water_to_import"></param> /// <param name="mini_tile_w"></param> /// <param name="mini_tile_h"></param> /// <param name="wBlock"></param> /// <param name="hBlock"></param> /// <param name="generate_sprite_sheet_image"></param> public static void Generate_Wall_Tiles(string path, List <Texture2D> sub_blocks_wall, List <bool> sub_blocks_wall_to_import, int mini_tile_w, int mini_tile_h, int wBlock, int hBlock, bool generate_sprite_sheet_image) { if (sub_blocks_wall == null) { return; } //create the final directory for the auto tile if (!Directory.Exists(Tiles_Utility.Auto_Tile_Folder_Path)) { Directory.CreateDirectory(Tiles_Utility.Auto_Tile_Folder_Path); } //create the final directory for the generated Images if (!Directory.Exists(Tiles_Utility.final_image_folder_path)) { Directory.CreateDirectory(Tiles_Utility.final_image_folder_path); } //create the folder for that specific file image string fileName = Path.GetFileNameWithoutExtension(path); string loaded_file_image_path = string.Format(@"{0}/_{1}", Tiles_Utility.final_image_folder_path, fileName); //ex rtp_import\Outside_A2\single_block_folder\final_tile\Image if (!Directory.Exists(loaded_file_image_path)) { Directory.CreateDirectory(loaded_file_image_path); } List <string> images_path = new List <string>();//list of the folder of the imported tiles Dictionary <byte, int> rule_tiles = new Dictionary <byte, int>(); //foreach sub pieces in the image. If it's an animated auto tile 3 consecutive sub blocks are 3 frame of the animation for (int i = 0; i < sub_blocks_wall_to_import.Count; i++) { //If the current sub is not selected to process than skip it if (!sub_blocks_wall_to_import[i]) { continue; } int tiles_counter = 0; //set zero to che final tile counter Texture2D sub_piece = sub_blocks_wall[i]; //temp array to store the sub mini tiles Texture2D[] bottom_left_mini_tiles, bottom_right_mini_tiles, top_left_mini_tiles, top_right_mini_tiles; Texture2D[,] raw_mini_tile; //generate the mini tiles to the following computation Tiles_A3_Utility.Generate_Mini_Tile_A3_Wall(sub_piece, mini_tile_w, mini_tile_h, out bottom_left_mini_tiles, out bottom_right_mini_tiles, out top_left_mini_tiles, out top_right_mini_tiles, out raw_mini_tile); if (generate_sprite_sheet_image) { Texture2D sprite_tiles = new Texture2D(wBlock * 8, hBlock * 2); string sprite_sheet_path = string.Format(@"{0}/_Wall_{1}_{2}.png", loaded_file_image_path, Path.GetFileNameWithoutExtension(path), i); //generate and iterate the final tile for the subs pieces foreach (KeyValuePair <byte, Texture2D> kvp in Tiles_A3_Utility.Generate_Final_Tiles_A3_Wall(mini_tile_w, mini_tile_h, bottom_left_mini_tiles, bottom_right_mini_tiles, top_left_mini_tiles, top_right_mini_tiles, rule_tiles)) { int xx = tiles_counter % 8 * wBlock; int yy = tiles_counter / 8 * hBlock; sprite_tiles.SetPixels(xx, sprite_tiles.height - yy - hBlock, wBlock, hBlock, kvp.Value.GetPixels()); tiles_counter++; } images_path.Add(sprite_sheet_path); File.WriteAllBytes(sprite_sheet_path, sprite_tiles.EncodeToPNG()); AssetDatabase.Refresh(); TextureImporter importer = AssetImporter.GetAtPath(sprite_sheet_path) as TextureImporter; if (importer != null) { importer.textureType = TextureImporterType.Sprite; importer.spriteImportMode = SpriteImportMode.Multiple; importer.filterMode = FilterMode.Point; importer.spritePixelsPerUnit = hBlock; importer.compressionQuality = 0; importer.textureCompression = TextureImporterCompression.Uncompressed; importer.maxTextureSize = sprite_tiles.width; SpriteMetaData[] tmps = new SpriteMetaData[8 * 2]; string tmpName = Path.GetFileNameWithoutExtension(sprite_sheet_path); for (int j = 0; j < 16; j++) { int xx = j % 8 * wBlock; int yy = (j / 8 + 1) * hBlock; SpriteMetaData smd = new SpriteMetaData(); smd = new SpriteMetaData(); smd.alignment = 0; smd.border = new Vector4(0, 0, 0, 0); smd.name = string.Format("{0}_{1:00}", tmpName, j); smd.pivot = new Vector2(.5f, .5f); smd.rect = new Rect(xx, sprite_tiles.height - yy, wBlock, hBlock); tmps[j] = smd; } importer.spritesheet = tmps; importer.SaveAndReimport(); } } else { //create the directory for the final images string tile_folder_path = string.Format(@"{0}/_Wall_{1}_{2}", loaded_file_image_path, Path.GetFileNameWithoutExtension(path), i); //add the path of the this that will contains alla the sub block final tiles images_path.Add(tile_folder_path); if (!Directory.Exists(tile_folder_path)) { Directory.CreateDirectory(tile_folder_path); } //generate and iterate the final tile for the subs pieces foreach (KeyValuePair <byte, Texture2D> kvp in Tiles_A3_Utility.Generate_Final_Tiles_A3_Wall(mini_tile_w, mini_tile_h, bottom_left_mini_tiles, bottom_right_mini_tiles, top_left_mini_tiles, top_right_mini_tiles, rule_tiles)) { //save each final tile to its own image var tile_bytes = kvp.Value.EncodeToPNG(); string tile_file_path = string.Format(@"{0}/_Water_{1}_{2}_{3:000}.png", tile_folder_path, Path.GetFileNameWithoutExtension(path), i, tiles_counter); File.WriteAllBytes(tile_file_path, tile_bytes); tiles_counter++; } } } AssetDatabase.Refresh(); //refresh asset database //generate the fixed Auto tiles for (int i = 0; i < images_path.Count; i++) { if (generate_sprite_sheet_image) { Tiles_A3_Utility.Generate_A3_Wall_tile_SS(path, images_path[i], rule_tiles); } else { Tiles_A3_Utility.Generate_A3_Wall_Tile(path, images_path[i], rule_tiles, wBlock); } } }
protected static void setAssetBundleName(string fullPath) { string[] files = Directory.GetFiles(fullPath); if (files == null || files.Length == 0) { return; } string pathUnderResources = fullPath.Substring(RES_SRC_PATH.Length); int unpackCount = mUnPackFolder.Length; for (int i = 0; i < unpackCount; ++i) { // 如果该文件夹是不打包的文件夹,则直接返回 if (startWith(pathUnderResources, mUnPackFolder[i], false)) { return; } } Debug.Log("Set AssetBundleName Start......"); string dirBundleName = pathUnderResources.Replace("/", "@") + ASSET_BUNDLE_SUFFIX; foreach (string file in files) { // .asset文件和.meta不打包 if (file.EndsWith(".meta") || file.EndsWith(".asset")) { continue; } AssetImporter importer = AssetImporter.GetAtPath(file); if (importer != null) { string ext = Path.GetExtension(file); string bundleName = dirBundleName; // prefab和unity(但是一般情况下unity场景文件不打包)单个文件打包 if (ext != null && (ext.Equals(".prefab") || ext.Equals(".unity"))) { bundleName = file.Substring(RES_SRC_PATH.Length); bundleName = bundleName.Replace("/", "@"); if (null != ext) { bundleName = bundleName.Replace(ext, ASSET_BUNDLE_SUFFIX); } else { bundleName += ASSET_BUNDLE_SUFFIX; } } rightToLeft(ref bundleName); bundleName = bundleName.ToLower(); Debug.LogFormat("Set AssetName Succ, File:{0}, AssetName:{1}", file, bundleName); importer.assetBundleName = bundleName; EditorUtility.UnloadUnusedAssetsImmediate(); string fileName = file; fileName = fileName.ToLower(); rightToLeft(ref fileName); // 存储bundleInfo AssetBuildBundleInfo info = new AssetBuildBundleInfo(); info.assetName = fileName; info.bundleName = bundleName; if (ext != null) { int index = fileName.IndexOf(ext.ToLower()); info.fileName = fileName.Substring(0, index); } else { info.fileName = fileName; } fileMap.Add(fileName, info); List <AssetBuildBundleInfo> infoList = null; bundleMap.TryGetValue(info.bundleName, out infoList); if (null == infoList) { infoList = new List <AssetBuildBundleInfo>(); bundleMap.Add(info.bundleName, infoList); } infoList.Add(info); } else { Debug.LogFormat("Set AssetName Fail, File:{0}, Msg:Importer is null", file); } } Debug.Log("Set AssetBundleName End......"); }
private void GenerateVegetationShadowMask(VegetationSystemPro vegetationSystem) { string path = EditorUtility.SaveFilePanelInProject("Save mask background", "", "png", "Please enter a file name to save the mask background to"); if (path.Length != 0) { ShadowMaskCreator shadowMaskCreator = (ShadowMaskCreator)target; //Terrain selectedTerrain = vegetationSystem.currentTerrain; //if (selectedTerrain == null) return; GameObject cameraObject = new GameObject { name = "Mask Background camera" }; int textureResolution = shadowMaskCreator.GetShadowMaskQualityPixelResolution(shadowMaskCreator.ShadowMaskQuality); Shader heightShader = Shader.Find("AwesomeTechnologies/Shadows/ShadowHeight"); RenderTexture rtDown = new RenderTexture(textureResolution, textureResolution, 24, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Trilinear, autoGenerateMips = false }; RenderTexture rtUp = new RenderTexture(textureResolution, textureResolution, 24, RenderTextureFormat.RFloat, RenderTextureReadWrite.Linear) { wrapMode = TextureWrapMode.Clamp, filterMode = FilterMode.Trilinear, autoGenerateMips = false }; Camera backgroundCamera = cameraObject.AddComponent <Camera>(); backgroundCamera.targetTexture = rtDown; backgroundCamera.clearFlags = CameraClearFlags.Color; backgroundCamera.backgroundColor = Color.black; backgroundCamera.orthographic = true; backgroundCamera.orthographicSize = shadowMaskCreator.AreaRect.size.x / 2f; backgroundCamera.farClipPlane = 20000; backgroundCamera.cullingMask = 1 << shadowMaskCreator.InvisibleLayer; backgroundCamera.SetReplacementShader(heightShader, ""); cameraObject.transform.position = new Vector3(shadowMaskCreator.AreaRect.x, 0, shadowMaskCreator.AreaRect.y) + new Vector3(shadowMaskCreator.AreaRect.size.x / 2f, 1000, shadowMaskCreator.AreaRect.size.y / 2f); cameraObject.transform.rotation = Quaternion.Euler(90, 0, 0); RenderTexture.active = rtDown; Graphics.SetRenderTarget(rtDown); GL.Viewport(new Rect(0, 0, rtDown.width, rtDown.height)); GL.Clear(true, true, new Color(0, 0, 0, 0), 1f); GL.PushMatrix(); GL.LoadProjectionMatrix(backgroundCamera.projectionMatrix); GL.modelview = backgroundCamera.worldToCameraMatrix; GL.PushMatrix(); RenderVegetationNow(vegetationSystem, shadowMaskCreator); GL.PopMatrix(); GL.PopMatrix(); cameraObject.transform.position = new Vector3(shadowMaskCreator.AreaRect.x, 0, shadowMaskCreator.AreaRect.y) + new Vector3(shadowMaskCreator.AreaRect.size.x / 2f, -1000, shadowMaskCreator.AreaRect.size.y / 2f); cameraObject.transform.rotation = Quaternion.Euler(-90, 0, 0); RenderTexture.active = rtUp; backgroundCamera.targetTexture = rtUp; Graphics.SetRenderTarget(rtUp); GL.Viewport(new Rect(0, 0, rtUp.width, rtUp.height)); GL.Clear(true, true, new Color(0, 0, 0, 0), 1f); GL.PushMatrix(); GL.LoadProjectionMatrix(backgroundCamera.projectionMatrix); GL.modelview = backgroundCamera.worldToCameraMatrix; GL.PushMatrix(); RenderVegetationNow(vegetationSystem, shadowMaskCreator); GL.PopMatrix(); GL.PopMatrix(); EditorUtility.DisplayProgressBar("Create shadow mask", "Render vegetation", 0f); RenderTexture.active = null; ShadowMapData[] outputHeights = new ShadowMapData[textureResolution * textureResolution]; ComputeBuffer outputHeightBuffer = new ComputeBuffer(textureResolution * textureResolution, 8); ComputeShader decodeShader = (ComputeShader)Resources.Load("DecodeShadowHeight"); int decodeKernelHandle = decodeShader.FindKernel("CSMain"); decodeShader.SetTexture(decodeKernelHandle, "InputDown", rtDown); decodeShader.SetTexture(decodeKernelHandle, "InputUp", rtUp); decodeShader.SetBuffer(decodeKernelHandle, "OutputHeightBuffer", outputHeightBuffer); decodeShader.SetInt("TextureResolution", textureResolution); decodeShader.Dispatch(decodeKernelHandle, textureResolution / 8, textureResolution / 8, 1); outputHeightBuffer.GetData(outputHeights); outputHeightBuffer.Dispose(); EditorUtility.DisplayProgressBar("Create shadow mask", "Calculate heights", 0.33f); Texture2D outputTexture = new Texture2D(textureResolution, textureResolution, TextureFormat.RGBA32, true); Color32[] outputColors = new Color32[outputHeights.Length]; float minTerrainHeight = vegetationSystem.VegetationSystemBounds.min.y; for (int x = 0; x <= textureResolution - 1; x++) { for (int y = 0; y <= textureResolution - 1; y++) { int i = x + y * textureResolution; float xNormalized = (float)x / textureResolution; float yNormalized = (float)y / textureResolution; float terrainHeight = sampleTerrainHeight(xNormalized, yNormalized, shadowMaskCreator.AreaRect); float vegetationHeightUp = outputHeights[i].BottomHeight - minTerrainHeight; float relativeHeightUp = Mathf.Clamp((vegetationHeightUp - terrainHeight) * 4, 0, 255); float vegetationHeightDown = outputHeights[i].TopHeight - minTerrainHeight; float relativeHeightDown = Mathf.Clamp((vegetationHeightDown - terrainHeight) * 4, 0, 255); if (relativeHeightUp > relativeHeightDown) { relativeHeightUp = relativeHeightDown; } outputColors[i].a = 255; outputColors[i].r = (byte)relativeHeightDown; outputColors[i].g = 0; outputColors[i].b = 0; } } outputTexture.SetPixels32(outputColors); outputTexture.Apply(); backgroundCamera.targetTexture = null; DestroyImmediate(rtDown); DestroyImmediate(rtUp); SaveTexture(outputTexture, path); DestroyImmediate(cameraObject); DestroyImmediate(outputTexture); GC.Collect(); EditorUtility.DisplayProgressBar("Create shadow mask", "importing asset", 0.66f); string assetPath = path; var tImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (tImporter != null) { tImporter.textureType = TextureImporterType.Default; tImporter.filterMode = FilterMode.Point; tImporter.maxTextureSize = 8192; tImporter.SaveAndReimport(); } EditorUtility.ClearProgressBar(); } }
public static void Replace() { string dir = "common"; try { // AssetDatabase.StartAssetEditing(); TextureImporter packed_importer = AssetImporter.GetAtPath("Assets/UI8/" + dir + ".png") as TextureImporter; List <SpriteMetaData> newDataList = new List <SpriteMetaData>(packed_importer.spritesheet); // packed_importer.spriteImportMode = SpriteImportMode.Single; for (int i = 0; i < newDataList.Count; i++) { SpriteMetaData metaData = newDataList[i]; TextureImporter single_importer = AssetImporter.GetAtPath("Assets/UI8/" + dir + "/" + metaData.name + ".png") as TextureImporter; if (metaData.border != single_importer.spriteBorder) { if (single_importer.spriteBorder.sqrMagnitude < 0.1f) { Debug.LogFormat("change signel border {2} {0} <- {1}", metaData.border, single_importer.spriteBorder, metaData.name); single_importer.spriteBorder = metaData.border; AssetDatabase.ImportAsset("Assets/UI8/" + dir + ".png", ImportAssetOptions.ForceUpdate); } else { Debug.LogFormat("change packed border {2} {0} -> {1}", metaData.border, single_importer.spriteBorder, metaData.name); metaData.border = single_importer.spriteBorder; } AssetDatabase.ImportAsset(single_importer.assetPath, ImportAssetOptions.ForceUpdate); } newDataList[i] = metaData; /* * List < SpriteMetaData > metaData = new List<SpriteMetaData>(); * * SpriteMetaData smd = new SpriteMetaData(); * smd.pivot = new Vector2(0.5f, 0.5f); * smd.alignment = 9; * smd.name = (myTexture.height - j) / SliceHeight + ", " + i / SliceWidth; * smd.rect = new Rect(i, j - SliceHeight, SliceWidth, SliceHeight); * smd.border = sprite.border; * * importer.spritesheet = smd; * * Sprite sep = AssetDatabase.LoadAssetAtPath<Sprite>(); * * sep.border = sprite.border; */ } // packed_importer.spriteImportMode = SpriteImportMode.Single; // AssetDatabase.ImportAsset(packed_importer.assetPath, ImportAssetOptions.ForceUpdate); packed_importer.spritesheet = newDataList.ToArray(); packed_importer.spriteImportMode = SpriteImportMode.Multiple; EditorUtility.SetDirty(packed_importer); AssetDatabase.ImportAsset(packed_importer.assetPath, ImportAssetOptions.ForceUpdate); } catch (System.Exception e) { Debug.LogError(e); } finally { // AssetDatabase.StopAssetEditing(); } // AssetDatabase.FindAssets(""); // ScanDir("Assets"); EditorUtility.ClearProgressBar(); }
IEnumerable <UnityObjectTreeViewItem> GetTreeViewItems() { var scene = SceneManager.GetActiveScene(); var dependencies = AssetDatabase.GetDependencies(scene.path, true); var importers = dependencies.Select(path => (AssetDatabase.LoadAssetAtPath <Texture>(path), AssetImporter.GetAtPath(path) as TextureImporter)).Where(i => i.Item2 != null && IsEnabled(i.Item1)); return(importers.Select(i => new TextureTreeViewItem(i.Item1.GetInstanceID(), i.Item1, i.Item2)).ToArray()); }
public static float GetSpritePixelsPerUnit(Sprite sprite) { TextureImporter textureImporter = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(sprite)) as TextureImporter; return(textureImporter.spritePixelsPerUnit); }
private void NormalMapCreator() { GUILayout.Label("Normal Map Creator", bigLabel); GUILayout.Space(20); GUILayout.Label("Select the folder where new Normal Maps will be saved when the Create Normal Map button of the asset component is pressed (URP only)", EditorStyles.boldLabel); HandleSaveFolderEditorPref("All1ShaderNormals", normalMapSavesPath, "Normal Maps"); GUILayout.Space(20); GUILayout.Label("Assign a sprite you want to create a normal map from. Choose the normal map settings and press the 'Create And Save Normal Map' button", EditorStyles.boldLabel); targetNormalImage = (Texture2D)EditorGUILayout.ObjectField("Target Image", targetNormalImage, typeof(Texture2D), false, GUILayout.MaxWidth(225)); EditorGUILayout.BeginHorizontal(); { GUILayout.Label("Normal Strength:", GUILayout.MaxWidth(150)); normalStrength = EditorGUILayout.Slider(normalStrength, 1f, 20f, GUILayout.MaxWidth(400)); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); { GUILayout.Label("Normal Smoothing:", GUILayout.MaxWidth(150)); normalSmoothing = EditorGUILayout.IntSlider(normalSmoothing, 0, 3, GUILayout.MaxWidth(400)); } EditorGUILayout.EndHorizontal(); if (isComputingNormals == 0) { if (targetNormalImage != null) { if (GUILayout.Button("Create And Save Normal Map")) { isComputingNormals = 1; return; } } else { GUILayout.Label("Add a Target Image to use this feature", EditorStyles.boldLabel); } } else { GUILayout.Label("Normal Map is currently being created, be patient", EditorStyles.boldLabel, GUILayout.Height(40)); Repaint(); isComputingNormals++; if (isComputingNormals > 5) { string assetPath = AssetDatabase.GetAssetPath(targetNormalImage); var tImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (tImporter != null) { tImporter.isReadable = true; tImporter.SaveAndReimport(); } Texture2D normalToSave = CreateNormalMap(targetNormalImage, normalStrength, normalSmoothing); string prefSavedPath = PlayerPrefs.GetString("All1ShaderNormals") + "/"; string path = prefSavedPath + "NormalMap.png"; if (System.IO.File.Exists(path)) { path = GetNewValidPath(path); } string texName = path.Replace(prefSavedPath, ""); path = EditorUtility.SaveFilePanel("Save texture as PNG", prefSavedPath, texName, "png"); if (path.Length != 0) { byte[] pngData = normalToSave.EncodeToPNG(); if (pngData != null) { File.WriteAllBytes(path, pngData); } AssetDatabase.Refresh(); if (path.IndexOf("Assets/") >= 0) { string subPath = path.Substring(path.IndexOf("Assets/")); TextureImporter importer = AssetImporter.GetAtPath(subPath) as TextureImporter; if (importer != null) { Debug.Log("Normal Map saved inside the project: " + subPath); importer.filterMode = FilterMode.Bilinear; importer.textureType = TextureImporterType.NormalMap; importer.wrapMode = TextureWrapMode.Repeat; importer.SaveAndReimport(); EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(subPath, typeof(Texture))); } } else { Debug.Log("Normal Map saved outside the project: " + path); } } isComputingNormals = 0; } } GUILayout.Label("*This process will freeze the editor for some seconds, larger images will take longer", EditorStyles.boldLabel); }
//设置AB的名字 static bool SetAllABName() { string[] files = Directory.GetFiles(PathManager.RES_EXPORT_ROOT_PATH, "*.*", SearchOption.AllDirectories); if (files != null) { Dictionary <string, string> resMap = new Dictionary <string, string>(); for (int i = 0; i < files.Length; i++) { string ext = Path.GetExtension(files[i]); if (ext != ".meta") { string abName = GetABName(files[i]); if (resMap.ContainsKey(abName)) { if (!files[i].Replace("\\", "/").Contains("Export/Merge/") && !files[i].Replace("\\", "/").Contains("Export/Variant/")) { Debug.LogError(string.Format("重名资源{0},请检测Export下的文件!", abName)); return(false); } } else { resMap.Add(abName, abName); } } } for (int i = 0; i < files.Length; i++) { string ext = Path.GetExtension(files[i]); files[i] = files[i].Replace("\\", "/"); if (ext != ".meta") { if (files[i].Contains("Shader")) { AssetImporter ai = AssetImporter.GetAtPath(files[i]); ai.assetBundleName = "allshader"; } else if (files[i].Contains("Font")) { AssetImporter ai = AssetImporter.GetAtPath(files[i]); ai.assetBundleName = "font"; } else if (files[i].Contains("Export/Merge/")) //这个目录下的东西,按照子目录作为一个AB { AssetImporter ai = AssetImporter.GetAtPath(files[i]); ai.assetBundleName = GetABName(files[i]); } else if (files[i].Contains("Export/Variant/")) //这个目录下的东西,子目录下的资源加上子目录名字作为variant名 { string fileName = Path.GetFileNameWithoutExtension(files[i]); AssetImporter ai = AssetImporter.GetAtPath(files[i]); ai.assetBundleName = fileName; ai.assetBundleVariant = GetVariantName(files[i]); } else { string fileName = Path.GetFileNameWithoutExtension(files[i]); AssetImporter ai = AssetImporter.GetAtPath(files[i]); ai.assetBundleName = fileName; } } } return(true); } else { Debug.LogError(string.Format("目录{0}资源为空,请确认!", PathManager.RES_EXPORT_ROOT_PATH)); return(false); ; } }
private void CopyTexture(string texturePath, Texture2D texture2D, BabylonTexture babylonTexture, bool isLightmap = false) { bool needToDelete = false; var useJPG = !texture2D.alphaIsTransparency; // Convert unsupported file extensions if (texturePath.EndsWith(".psd") || texturePath.EndsWith(".tif") || texturePath.EndsWith(".exr")) { try { // Change texture import settings to be able to read texture data var textureImporter = AssetImporter.GetAtPath(texturePath) as TextureImporter; var previousIsReadable = textureImporter.isReadable; var previousNormalMap = textureImporter.normalmap; var previousLightmap = textureImporter.lightmap; var previousConvertToNormalmap = textureImporter.convertToNormalmap; var previousTextureType = textureImporter.textureType; var previousGrayscaleToAlpha = textureImporter.grayscaleToAlpha; textureImporter.textureType = TextureImporterType.Advanced; textureImporter.isReadable = true; textureImporter.lightmap = false; textureImporter.normalmap = false; textureImporter.convertToNormalmap = false; textureImporter.grayscaleToAlpha = false; AssetDatabase.ImportAsset(texturePath); texturePath = Path.Combine(Path.GetTempPath(), Path.GetFileName(texturePath)); var extension = useJPG ? ".jpg" : ".png"; texturePath = texturePath.Replace(".psd", extension).Replace(".tif", extension).Replace(".exr", extension); var tempTexture = new Texture2D(texture2D.width, texture2D.height, TextureFormat.ARGB32, false); if (isLightmap) { Color[] pixels = texture2D.GetPixels(0, 0, texture2D.width, texture2D.height); for (int index = 0; index < pixels.Length; index++) { pixels[index].r = pixels[index].r * pixels[index].a * 5; pixels[index].g = pixels[index].g * pixels[index].a * 5; pixels[index].b = pixels[index].b * pixels[index].a * 5; } tempTexture.SetPixels(pixels); } else { tempTexture.SetPixels32(texture2D.GetPixels32()); } tempTexture.Apply(); File.WriteAllBytes(texturePath, useJPG ? tempTexture.EncodeToJPG() : tempTexture.EncodeToPNG()); needToDelete = true; // Restore textureImporter.isReadable = previousIsReadable; textureImporter.normalmap = previousNormalMap; textureImporter.lightmap = previousLightmap; textureImporter.convertToNormalmap = previousConvertToNormalmap; textureImporter.textureType = previousTextureType; textureImporter.grayscaleToAlpha = previousGrayscaleToAlpha; AssetDatabase.ImportAsset(texturePath, ImportAssetOptions.ForceUpdate); } catch (Exception ex) { Debug.LogException(ex); } } var textureName = Path.GetFileName(texturePath); babylonTexture.name = textureName; babylonScene.AddTexture(texturePath); if (needToDelete) { File.Delete(texturePath); } }