public static ShowMessage ( string message, string title = "Babylon.js", string ok = "OK", string cancel = "Cancel" ) : bool | ||
message | string | |
title | string | |
ok | string | |
cancel | string | |
return | bool |
public static void InitUpdate() { string prodVersion = ExporterWindow.exportationOptions.ProductionVersion.ToString(); if (prodVersion.IndexOf(".", StringComparison.OrdinalIgnoreCase) < 0) { prodVersion += ".0"; } string updateMsg = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "Are you sure you want to update libraries using the github preview release version?" : "Are you sure you want to update libraries using the github stable release version " + prodVersion + "?"; if (ExporterWindow.ShowMessage(updateMsg, "Babylon.js", "Update")) { EditorUtility.DisplayProgressBar("Babylon.js", "Updating github editor toolkit library files...", 1); string libPath = Path.Combine(Application.dataPath, "Babylon/Library/"); string bjsPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/babylon.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".js"; string bjsTsPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/babylon.d.ts" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".d.ts"; string c2dPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/canvas2D/babylon.canvas2d.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".canvas2d.js"; string c2dTsPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/canvas2D/babylon.canvas2d.d.ts" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".canvas2d.d.ts"; string cannonPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/cannon.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/cannon.js"; string oimoPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/Oimo.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/Oimo.js"; try { EditorUtility.DisplayProgressBar("Babylon.js", "Updating babylon.bjs...", 0.10f); Tools.DownloadFile(bjsPath, Path.Combine(libPath, "babylon.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating babylon.d.ts...", 0.20f); Tools.DownloadFile(bjsTsPath, Path.Combine(libPath, "babylon.d.ts")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating canvas2d.bjs...", 0.30f); Tools.DownloadFile(c2dPath, Path.Combine(libPath, "canvas2d.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating canvas2d.d.ts...", 0.40f); Tools.DownloadFile(c2dTsPath, Path.Combine(libPath, "canvas2d.d.ts")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating cannon.bjs...", 0.50f); Tools.DownloadFile(cannonPath, Path.Combine(libPath, "cannon.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating oimo.bjs...", 0.60f); Tools.DownloadFile(oimoPath, Path.Combine(libPath, "oimo.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating navmesh.bjs...", 0.70f); Tools.DownloadFile("https://raw.githubusercontent.com/BabylonJS/Extensions/master/SceneManager/dist/babylon.navigation.mesh.js", Path.Combine(libPath, "navmesh.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating manager.bjs...", 0.80f); Tools.DownloadFile("https://raw.githubusercontent.com/BabylonJS/Extensions/master/SceneManager/dist/babylon.scenemanager.js", Path.Combine(libPath, "manager.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating manager.d.ts...", 0.90f); Tools.DownloadFile("https://raw.githubusercontent.com/BabylonJS/Extensions/master/SceneManager/dist/babylon.scenemanager.d.ts", Path.Combine(libPath, "manager.d.ts")); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); } finally { EditorUtility.DisplayProgressBar("Babylon.js", "Refresing assets database...", 1.0f); AssetDatabase.Refresh(); EditorUtility.ClearProgressBar(); } } }
public void OnGUI() { GUILayout.Label("Heightmap File", EditorStyles.boldLabel); EditorGUI.BeginDisabledGroup(true); heightmapLabel = EditorGUILayout.TextField(String.Empty, heightmapLabel); EditorGUI.EndDisabledGroup(); if (GUILayout.Button("Load Heightmap Data")) { LoadHeightmap(); } EditorGUILayout.Space(); exportFormat = (BabylonHeightmapFormat)EditorGUILayout.EnumPopup("Export Format:", exportFormat, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); // .. EditorGUILayout.BeginHorizontal(); enableResolution = EditorGUILayout.Toggle("Scale Resolution:", enableResolution); if (enableResolution == false) { exportResolution = heightmapResolution; } EditorGUI.BeginDisabledGroup(enableResolution == false); exportResolution = (int)EditorGUILayout.Slider("", exportResolution, 0, heightmapResolution); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportScaling = (BabylonTextureScale)EditorGUILayout.EnumPopup("Map Image Scaling:", (BabylonTextureScale)exportScaling, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); EditorGUI.EndDisabledGroup(); // .. EditorGUILayout.BeginHorizontal(); keepGeneratorOpen = EditorGUILayout.Toggle("Keep Generator Open:", keepGeneratorOpen); int vertexCount = (exportResolution * exportResolution); string vertextLabel = String.Format("Estimated Mesh Density - {0}", (vertexCount > 0) ? vertexCount.ToString("#,#") : "0"); GUILayout.Label(vertextLabel, EditorStyles.boldLabel); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); // .. if (heightmapTexture == null) { heightmapTexture = new Texture2D(500, 500, TextureFormat.RGBA32, false); heightmapTexture.Clear(Color.black); } if (heightmapTexture != null) { GUI.DrawTexture(new Rect(10.0f, 180.0f, 500.0f, 500.0f), heightmapTexture, ScaleMode.ScaleToFit); } GUILayout.Space(510.0f); if (GUILayout.Button("Export Heightmap")) { if (heightmapTexture != null && !String.IsNullOrEmpty(heightmapFile)) { ExportHeightmap(); } else { ExporterWindow.ShowMessage("No heightmap data generated."); } } }
public void Bake() { // Validate Project Platform if (generateSkybox == false && generateRadiance == false) { ExporterWindow.ShowMessage("You must select generate skybox and/or radiance"); return; } if (!Unity3D2Babylon.Tools.ValidateProjectPlatform()) { return; } try { string inputFile = AssetDatabase.GetAssetPath(convertCube); string inputExt = Path.GetExtension(inputFile); if (skyboxOption == BabylonSkyboxOption.SixSidedCubemap) { Split(inputFile, inputExt, true); Filter(inputFile, inputExt, false, true); } else if (skyboxOption == BabylonSkyboxOption.DirectDrawSurface) { Filter(inputFile, inputExt, true, true); } } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { ExporterWindow.ReportProgress(1, "Refresing assets database..."); AssetDatabase.Refresh(); } ExporterWindow.ReportProgress(1, "Cubemap conversion complete."); EditorUtility.ClearProgressBar(); if (this.keepGeneratorOpen) { ExporterWindow.ShowMessage("Cubemap optimzation complete.", "Babylon.js"); } else { this.Close(); } }
public void OnGUI() { GUILayout.Label("Choose the Cubemap you want to split into 6 images", EditorStyles.boldLabel); EditorGUILayout.Space(); splitCube = EditorGUILayout.ObjectField("Cubemap:", splitCube, typeof(Cubemap), false) as Cubemap; EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Split Cubemap")) { if (splitCube) { Split(); } if (!splitCube) { ExporterWindow.ShowMessage("You must select a cubemap"); } } }
public void OnGUI() { // Update texture atlas window EditorGUILayout.Space(); skinMeshRenderer = EditorGUILayout.ObjectField("Skin Mesh Renderer:", skinMeshRenderer, typeof(SkinnedMeshRenderer), true) as SkinnedMeshRenderer; EditorGUILayout.Space(); bakeTextureMaps = EditorGUILayout.Toggle("Bake Texture Maps:", bakeTextureMaps); EditorGUILayout.Space(); bakeAlphaEncoding = EditorGUILayout.Toggle("Bake Image Alpha:", bakeAlphaEncoding); EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(true); EditorGUI.EndDisabledGroup(); textureAtlasSize = (int)EditorGUILayout.Slider("Texture Atlas Size:", textureAtlasSize, 128, 8192); EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(true); textureAtlasShader = EditorGUILayout.ObjectField("Texture Atlas Shader:", textureAtlasShader, typeof(Shader), true) as Shader; EditorGUILayout.Space(); textureAtlasFormat = (BabylonImageFormat)EditorGUILayout.EnumPopup("Texture Atlas Format:", textureAtlasFormat, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); EditorGUI.EndDisabledGroup(); textureImageScaling = (BabylonTextureScale)EditorGUILayout.EnumPopup("Texture Image Scale:", textureImageScaling, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); maxTextureImageSize = (int)EditorGUILayout.Slider("Texture Image Max:", maxTextureImageSize, 0, 4096); EditorGUILayout.Space(); linearInterpolation = EditorGUILayout.Toggle("Use Linear Interpolation:", linearInterpolation); EditorGUILayout.Space(); updateSkinRenderer = EditorGUILayout.Toggle("Update Skin Renderers:", updateSkinRenderer); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Bake Texture Atlas Skin")) { if (skinMeshRenderer) { Bake(); } if (!skinMeshRenderer) { ExporterWindow.ShowMessage("You must select a skin mesh renderer"); } } }
void SwitchSandbox() { if (sandboxType == SandboxType.Custom && String.IsNullOrEmpty(ExporterWindow.exportationOptions.CustomWindowsSandbox)) { ExporterWindow.ShowMessage("You must enter a custom sandbox.", "Babylon.js"); return; } this.logs.Clear(); ExporterWindow.ReportProgress(1, "Switching windows sandbox... This may take a while."); string sandbox = (sandboxType == SandboxType.Custom) ? ExporterWindow.exportationOptions.CustomWindowsSandbox : "RETAIL"; string command = "\"" + Path.Combine(Application.dataPath, "Babylon/Plugins/Windows/SwitchSandbox.cmd") + "\""; this.logs.Add("Switching windows sandbox to: " + sandbox); int result = Tools.ExecuteProcess(command, sandbox, ref this.logs); EditorUtility.ClearProgressBar(); if (result != 0) { ExporterWindow.ShowMessage("Failed to switch windows sandbox.", "Babylon.js"); } if (this.keepGeneratorOpen == false) { this.Close(); } }
public void OnGUI() { EditorGUILayout.Space(); babylonParticles = EditorGUILayout.ObjectField("Babylon Particle System:", babylonParticles, typeof(ParticleSystems), true) as ParticleSystems; EditorGUILayout.Space(); shurikenParticles = EditorGUILayout.ObjectField("Shuriken Particle System:", shurikenParticles, typeof(ParticleSystem), true) as ParticleSystem; EditorGUILayout.Space(); defaultColor = EditorGUILayout.ColorField("Default Particle Color:", defaultColor); EditorGUILayout.Space(); updateSpeedModifier = (float)EditorGUILayout.Slider("Start Speed Modifier:", updateSpeedModifier, 0.0f, 1.0f); EditorGUILayout.Space(); emitRateModifier = (float)EditorGUILayout.Slider("Emit Rate Modifier:", emitRateModifier, 0.0f, 100.0f); EditorGUILayout.Space(); convertCurveValues = (BabylonCurveValues)EditorGUILayout.EnumPopup("Convert Curve Values:", convertCurveValues, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportShurikenData = EditorGUILayout.Toggle("Custom Shuriken Data:", exportShurikenData); EditorGUILayout.Space(); keepGeneratorOpen = EditorGUILayout.Toggle("Keep Generator Open:", keepGeneratorOpen); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Parse Shuriken Particle System")) { if (shurikenParticles && babylonParticles) { Parse(); } if (!shurikenParticles) { ExporterWindow.ShowMessage("You must select a shuriken particle system"); } else if (!babylonParticles) { ExporterWindow.ShowMessage("You must select a babylon particle system"); } } }
public void ConvertFromUnity() { ExporterWindow.ReportProgress(0, "Starting Babylon.js exportation process..."); gameObjects = Object.FindObjectsOfType(typeof(GameObject)) as GameObject[]; if (gameObjects.Length == 0) { ExporterWindow.ShowMessage("No gameobject! - Please add at least a gameobject to export"); return; } var itemsCount = gameObjects.Length; var index = 0; foreach (var gameObject in gameObjects) { var progress = ((float)index / itemsCount); index++; // Static meshes var meshFilter = gameObject.GetComponent <MeshFilter>(); if (meshFilter != null) { ConvertUnityMeshToBabylon(meshFilter.sharedMesh, meshFilter.transform, gameObject, progress); continue; } // Skinned meshes var skinnedMesh = gameObject.GetComponent <SkinnedMeshRenderer>(); if (skinnedMesh != null) { var babylonMesh = ConvertUnityMeshToBabylon(skinnedMesh.sharedMesh, skinnedMesh.transform, gameObject, progress); var skeleton = ConvertUnitySkeletonToBabylon(skinnedMesh.bones, skinnedMesh.sharedMesh.bindposes, skinnedMesh.transform, gameObject, progress); babylonMesh.skeletonId = skeleton.id; ExportSkeletonAnimation(skinnedMesh, babylonMesh, skeleton); continue; } // Light var light = gameObject.GetComponent <Light>(); if (light != null) { ConvertUnityLightToBabylon(light, progress); continue; } // Camera var camera = gameObject.GetComponent <Camera>(); if (camera != null) { ConvertUnityCameraToBabylon(camera, progress); ConvertUnitySkyboxToBabylon(camera, progress); continue; } // Empty ConvertUnityEmptyObjectToBabylon(gameObject); } // Materials foreach (var mat in materialsDictionary) { babylonScene.MaterialsList.Add(mat.Value); } foreach (var multiMat in multiMatDictionary) { babylonScene.MultiMaterialsList.Add(multiMat.Value); } // Collisions if (exportationOptions.ExportCollisions) { babylonScene.gravity = exportationOptions.Gravity.ToFloat(); } }
public void Export(bool preview) { try { // Validate lightmap bake in progress if (exportationOptions.ExportLightmaps && exportationOptions.DefaultLightmapBaking == (int)BabylonLightmapBaking.Enabled && Lightmapping.isRunning) { ShowMessage("There is a bake already in progress."); return; } // Validate default project folder selected if (String.IsNullOrEmpty(exportationOptions.DefaultProjectFolder)) { ShowMessage("No default project file selected."); return; } // Validate default project folder exists if (!Directory.Exists(exportationOptions.DefaultProjectFolder)) { if (ExporterWindow.ShowMessage("Create default project folder: " + exportationOptions.DefaultProjectFolder, "Babylon.js - Project not found", "Create")) { Directory.CreateDirectory(exportationOptions.DefaultProjectFolder); } else { return; } } // Get validate scene path info string[] sceneInfo = GetSceneInfomation(true); string sceneName = sceneInfo[0]; string scenePath = sceneInfo[1]; string scriptPath = sceneInfo[2]; string outputFile = sceneInfo[3]; string projectScript = sceneInfo[4]; if (!ExporterWindow.ShowMessage("Export current scene to babylon: " + sceneName, "Babylon.js", "Export")) { return; } // Save current scene info SaveSettings(); ExporterWindow.logs.Clear(); Stopwatch watch = new Stopwatch(); watch.Start(); ReportProgress(0, "Exporting " + scenePath); // Auto lightmap baking if (exportationOptions.ExportLightmaps && exportationOptions.DefaultLightmapBaking == (int)BabylonLightmapBaking.Enabled) { ReportProgress(1, "Baking lightmap textures... This may take a while."); Lightmapping.GIWorkflowMode workflow = Lightmapping.giWorkflowMode; Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand; Lightmapping.Bake(); Lightmapping.giWorkflowMode = workflow; } // Save all open scenes ReportProgress(1, "Saving open scene information..."); UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes(); // Build project preview if (preview) { Tools.GenerateProjectIndexPage(exportationOptions.DefaultProjectFolder, exportationOptions.ShowDebugControls, exportationOptions.DefaultScenePath, Path.GetFileName(outputFile), exportationOptions.DefaultScriptPath, Path.GetFileName(projectScript)); if (exportationOptions.BuildJavaScript || exportationOptions.CompileTypeScript) { Build(false, sceneInfo); } } // Build current scene BabylonSceneController sceneController = Tools.GetSceneController(); var sceneBuilder = new SceneBuilder(scenePath, sceneName, exportationOptions, sceneController, scriptPath); sceneBuilder.ConvertFromUnity(); ReportProgress(1, "Generating babylon scene... This may take a while."); sceneBuilder.WriteToBabylonFile(outputFile); watch.Stop(); ReportProgress(1, string.Format("Exportation done in {0:0.00}s", watch.Elapsed.TotalSeconds)); EditorUtility.ClearProgressBar(); sceneBuilder.GenerateStatus(logs); string done = preview ? "Preview" : "OK"; bool ok = ShowMessage("Scene exportation complete.", "Babylon.js", done); if (preview && ok) { Preview(); } } catch (Exception ex) { EditorUtility.ClearProgressBar(); ShowMessage("A problem occurred: " + ex.Message + ex.StackTrace, "Error"); } }
public void OnGUI() { GUILayout.Label("BabylonJS Toolkit - Version: " + ExporterWindow.ToolkitVersion, EditorStyles.boldLabel); EditorGUI.BeginDisabledGroup(true); exportationOptions.DefaultProjectFolder = EditorGUILayout.TextField("", exportationOptions.DefaultProjectFolder); EditorGUI.EndDisabledGroup(); if (GUILayout.Button("Select Project Folder")) { SelectFolder(); } if (GUILayout.Button("Save Export Settings")) { SaveSettings(); ShowMessage("Export settings saved."); } scrollPosMain = EditorGUILayout.BeginScrollView(scrollPosMain, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true)); EditorGUILayout.Space(); exportationOptions.DefaultBuildPath = EditorGUILayout.TextField(" Project Build Path", exportationOptions.DefaultBuildPath); EditorGUILayout.Space(); exportationOptions.DefaultScenePath = EditorGUILayout.TextField(" Project Scene Path", exportationOptions.DefaultScenePath); EditorGUILayout.Space(); exportationOptions.DefaultScriptPath = EditorGUILayout.TextField(" Project Script Path", exportationOptions.DefaultScriptPath); EditorGUILayout.Space(); exportationOptions.DefaultIndexPage = EditorGUILayout.TextField(" Project Index Page", exportationOptions.DefaultIndexPage); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); exportationOptions.ExportPhysics = EditorGUILayout.Toggle(" Enable Physics Engine", exportationOptions.ExportPhysics); exportationOptions.DefaultPhysicsEngine = (int)(BabylonPhysicsEngine)EditorGUILayout.EnumPopup("Default Physics Engine", (BabylonPhysicsEngine)exportationOptions.DefaultPhysicsEngine, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); GUILayout.Label(" Light Rotation Offset"); exportationOptions.LightRotationOffset = EditorGUILayout.Vector3Field("", exportationOptions.LightRotationOffset, GUILayout.ExpandWidth(false)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportationOptions.LightIntensityFactor = EditorGUILayout.Slider(" Light Intensity Factor", exportationOptions.LightIntensityFactor, 0, 10.0f); EditorGUILayout.Space(); exportationOptions.ReflectionDefaultLevel = EditorGUILayout.Slider(" Default Reflection Level", exportationOptions.ReflectionDefaultLevel, 0, 1.0f); EditorGUILayout.Space(); exportationOptions.DefaultImageFormat = (int)(BabylonImageFormat)EditorGUILayout.EnumPopup(" Prefered Texture Format", (BabylonImageFormat)exportationOptions.DefaultImageFormat, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.DefaultQualityLevel = (int)EditorGUILayout.Slider(" Texture Image Quality", exportationOptions.DefaultQualityLevel, 0, 100); EditorGUILayout.Space(); showCollision = EditorGUILayout.Foldout(showCollision, "Scene Collision Options"); if (showCollision) { EditorGUILayout.Space(); exportationOptions.ExportCollisions = EditorGUILayout.Toggle(" Enable Collisions", exportationOptions.ExportCollisions); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); GUILayout.Label(" Camera Ellipsoid"); exportationOptions.CameraEllipsoid = EditorGUILayout.Vector3Field("", exportationOptions.CameraEllipsoid, GUILayout.ExpandWidth(false)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); GUILayout.Label(" Default Scene Gravity"); exportationOptions.Gravity = EditorGUILayout.Vector3Field("", exportationOptions.Gravity, GUILayout.ExpandWidth(false)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportationOptions.DefaultColliderDetail = (int)(BabylonColliderDetail)EditorGUILayout.EnumPopup(" Default Collider Detail", (BabylonColliderDetail)exportationOptions.DefaultColliderDetail, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.WorkerCollisions = EditorGUILayout.Toggle(" Enable Worker Collisions", exportationOptions.WorkerCollisions); EditorGUILayout.Space(); } showShader = EditorGUILayout.Foldout(showShader, "Shader Program Options"); if (showShader) { EditorGUILayout.Space(); exportationOptions.EmbeddedShaders = EditorGUILayout.Toggle(" Embed Shader Files", exportationOptions.EmbeddedShaders); EditorGUILayout.Space(); exportationOptions.DefaultShaderFolder = EditorGUILayout.TextField(" Output Src Shader Path", exportationOptions.DefaultShaderFolder); EditorGUILayout.Space(); } showLighting = EditorGUILayout.Foldout(showLighting, "Lightmap Baking Options"); if (showLighting) { EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); exportationOptions.ExportLightmaps = EditorGUILayout.Toggle(" Export Lightmaps", exportationOptions.ExportLightmaps); exportationOptions.DefaultLightmapBaking = (int)(BabylonLightmapBaking)EditorGUILayout.EnumPopup(" Synchronous Baking", (BabylonLightmapBaking)exportationOptions.DefaultLightmapBaking, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportationOptions.DefaultLightmapMode = (int)(BabylonLightmapMode)EditorGUILayout.EnumPopup(" Light Mapper Mode", (BabylonLightmapMode)exportationOptions.DefaultLightmapMode, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.DefaultCoordinatesIndex = (int)EditorGUILayout.Slider(" Coordinates Index", exportationOptions.DefaultCoordinatesIndex, 0, 1); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); exportationOptions.ExportShadows = EditorGUILayout.Toggle(" Enable Shadow Map", exportationOptions.ExportShadows); GUILayout.Label(" Default Shadow Map Size"); exportationOptions.ShadowMapSize = EditorGUILayout.IntField("", exportationOptions.ShadowMapSize, GUILayout.Width(50)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportationOptions.DefaultLightFilter = (int)(BabylonLightingFilter)EditorGUILayout.EnumPopup(" Shadow Map Filter", (BabylonLightingFilter)exportationOptions.DefaultLightFilter, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.ShadowMapBias = EditorGUILayout.Slider(" Shadow Map Bias", exportationOptions.ShadowMapBias, 0, 1.0f); EditorGUILayout.Space(); exportationOptions.ShadowBlurScale = EditorGUILayout.Slider(" Shadow Blur Scale", exportationOptions.ShadowBlurScale, 0, 5.0f); EditorGUILayout.Space(); } showPreview = EditorGUILayout.Foldout(showPreview, "Default Exporting Options"); if (showPreview) { EditorGUILayout.Space(); exportationOptions.AttachUnityEditor = EditorGUILayout.Toggle(" Attach Unity Editor", exportationOptions.AttachUnityEditor); EditorGUILayout.Space(); exportationOptions.HostPreviewPage = EditorGUILayout.Toggle(" Host Preview Server", exportationOptions.HostPreviewPage); EditorGUILayout.Space(); exportationOptions.ShowDebugControls = EditorGUILayout.Toggle(" Show Debug Controls", exportationOptions.ShowDebugControls); EditorGUILayout.Space(); exportationOptions.DefaultServerPort = EditorGUILayout.IntField(" Default Server Port", exportationOptions.DefaultServerPort); EditorGUILayout.Space(); exportationOptions.DefaultPreviewWindow = (int)(BabylonPreviewWindow)EditorGUILayout.EnumPopup(" Default Preview Window", (BabylonPreviewWindow)exportationOptions.DefaultPreviewWindow, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.BuildJavaScript = EditorGUILayout.Toggle(" Build Javascript Files", exportationOptions.BuildJavaScript); EditorGUILayout.Space(); exportationOptions.CompileTypeScript = EditorGUILayout.Toggle(" Build Typescript Files", exportationOptions.CompileTypeScript); EditorGUILayout.Space(); exportationOptions.DefaultTypeSriptPath = EditorGUILayout.TextField(" Typescript Compiler", exportationOptions.DefaultTypeSriptPath); EditorGUILayout.Space(); exportationOptions.DefaultNodeRuntimePath = EditorGUILayout.TextField(" Node Runtime System", exportationOptions.DefaultNodeRuntimePath); EditorGUILayout.Space(); exportationOptions.ProductionVersion = EditorGUILayout.FloatField(" Stable Babylon Version", exportationOptions.ProductionVersion); EditorGUILayout.Space(); exportationOptions.DefaultUpdateOptions = (int)(BabylonUpdateOptions)EditorGUILayout.EnumPopup(" Github Update Version", (BabylonUpdateOptions)exportationOptions.DefaultUpdateOptions, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); } EditorGUILayout.EndScrollView(); EditorGUILayout.Space(); // Exporter buttons if (GUILayout.Button("Build Script")) { if (ExporterWindow.ShowMessage("Are you sure you want to build the project script files?", "Babylon.js", "Build")) { Build(true); } } if (GUILayout.Button("Export Scene")) { Export(false); } if (GUILayout.Button("Export & Preview")) { Export(true); } if (ExporterWindow.exportationOptions.HostPreviewPage == true) { if (GUILayout.Button("Start Preview Server")) { StartServer(); } } if (GUILayout.Button("Launch Preview Window")) { Execute(); } EditorGUILayout.Space(); }
public void ConvertFromUnity() { ExporterWindow.ReportProgress(0, "Starting Babylon.js exportation process..."); gameObjects = Object.FindObjectsOfType(typeof(GameObject)) as GameObject[]; if (gameObjects.Length == 0) { ExporterWindow.ShowMessage("No gameobject! - Please add at least a gameobject to export"); return; } var itemsCount = gameObjects.Length; var index = 0; //Dictionary to store prefabs and their instances Dictionary <GameObject, List <BabylonAbstractMesh> > dicPrefabs = new Dictionary <GameObject, List <BabylonAbstractMesh> >(); foreach (var gameObject in gameObjects) { var progress = ((float)index / itemsCount); index++; /* * The order of processing is important here. * We will only check if this is a mesh prefab if it is not a light or camera */ // Light var light = gameObject.GetComponent <Light>(); if (light != null) { ConvertUnityLightToBabylon(light, progress); continue; } // Camera var camera = gameObject.GetComponent <Camera>(); if (camera != null) { ConvertUnityCameraToBabylon(camera, progress); continue; } // Check if this is a prefab instance GameObject gobjPrefab = (GameObject)PrefabUtility.GetPrefabParent(gameObject); if (gobjPrefab != null) { //Add prefab to dictionary if it doesn't already exist if (!dicPrefabs.ContainsKey(gobjPrefab)) { dicPrefabs[gobjPrefab] = new List <BabylonAbstractMesh>(); } List <BabylonAbstractMesh> lstInstances = dicPrefabs[gobjPrefab]; BabylonAbstractMesh instance = ConvertUnityMeshToInstance(gameObject); lstInstances.Add(instance); continue; } // Static meshes var meshFilter = gameObject.GetComponent <MeshFilter>(); if (meshFilter != null) { ConvertUnityMeshToBabylon(meshFilter.sharedMesh, meshFilter.transform, gameObject, progress); continue; } // Skinned meshes var skinnedMesh = gameObject.GetComponent <SkinnedMeshRenderer>(); if (skinnedMesh != null) { ConvertUnityMeshToBabylon(skinnedMesh.sharedMesh, skinnedMesh.transform, gameObject, progress); continue; } // Empty ConvertUnityEmptyObjectToBabylon(gameObject); } index = 0; itemsCount = dicPrefabs.Count; //Convert prefabs foreach (KeyValuePair <GameObject, List <BabylonAbstractMesh> > pair in dicPrefabs) { var progress = ((float)index / itemsCount); index++; List <BabylonAbstractMesh> lstValue = pair.Value; GameObject prefab = pair.Key; BabylonAbstractMesh[] lstInstance = lstValue.ToArray(); // Static meshes var meshFilter = prefab.GetComponent <MeshFilter>(); if (meshFilter != null) { ConvertUnityMeshToBabylon(meshFilter.sharedMesh, meshFilter.transform, prefab, progress, lstInstance); continue; } // Skinned meshes var skinnedMesh = prefab.GetComponent <SkinnedMeshRenderer>(); if (skinnedMesh != null) { ConvertUnityMeshToBabylon(skinnedMesh.sharedMesh, skinnedMesh.transform, prefab, progress, lstInstance); continue; } // Empty ConvertUnityEmptyObjectToBabylon(prefab, lstInstance); } // Materials foreach (var mat in materialsDictionary) { babylonScene.MaterialsList.Add(mat.Value); } foreach (var multiMat in multiMatDictionary) { babylonScene.MultiMaterialsList.Add(multiMat.Value); } // Collisions if (exportationOptions.ExportCollisions) { babylonScene.gravity = exportationOptions.Gravity.ToFloat(); } }
public void OnGUI() { EditorGUILayout.Space(); cubemapTool = (BabylonCubemapTool)EditorGUILayout.EnumPopup("Cubemap Texture Tool:", cubemapTool, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); if (cubemapTool == BabylonCubemapTool.PixelPerfectTools) { splitLabel = "Open Pixel Perfect"; if (this.maxSize.y != 94.0f) { this.maxSize = new Vector2(500.0f, 94.0f); this.minSize = this.maxSize; } } else if (cubemapTool == BabylonCubemapTool.ReflectionProbes) { splitLabel = "Bake Reflection Probe"; if (this.maxSize.y != 222.0f) { this.maxSize = new Vector2(500.0f, 222.0f); this.minSize = this.maxSize; } } else { splitLabel = "Bake Cubemap Faces"; if (this.maxSize.y != 248.0f) { this.maxSize = new Vector2(500.0f, 248.0f); this.minSize = this.maxSize; } } if (cubemapTool == BabylonCubemapTool.CubemapSplitter || cubemapTool == BabylonCubemapTool.ReflectionProbes) { imageLibrary = (BabylonImageLibrary)EditorGUILayout.EnumPopup("Default Image Library:", imageLibrary, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); convertCube = EditorGUILayout.ObjectField("Source Cubemap Image:", convertCube, typeof(Cubemap), false) as Cubemap; EditorGUILayout.Space(); } if (cubemapTool == BabylonCubemapTool.CubemapSplitter) { imageFormat = (BabylonImageFormat)EditorGUILayout.EnumPopup("Output Image Format:", imageFormat, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); } if (cubemapTool == BabylonCubemapTool.ReflectionProbes) { reflectionType = (BabylonProbeFormat)EditorGUILayout.EnumPopup("Reflection Probe Size:", reflectionType, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); } if (cubemapTool == BabylonCubemapTool.CubemapSplitter) { createSkyboxMaterial = EditorGUILayout.Toggle("Create Skybox Material:", createSkyboxMaterial); EditorGUILayout.Space(); } keepGeneratorOpen = EditorGUILayout.Toggle("Keep Generator Open:", keepGeneratorOpen); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button(splitLabel)) { if (cubemapTool == BabylonCubemapTool.PixelPerfectTools) { bool jpeg = (imageFormat == BabylonImageFormat.JPEG); string splitter = (ExporterWindow.PixelPrefect + "?jpeg=" + jpeg.ToString().ToLower()); Application.OpenURL(splitter); this.Close(); } else { if (convertCube) { Bake(); } if (!convertCube) { ExporterWindow.ShowMessage("You must select a cubemap"); } } } }
public void Bake() { // Validate Project Platform if (!Unity3D2Babylon.Tools.ValidateProjectPlatform()) { return; } try { string inputFile = AssetDatabase.GetAssetPath(convertCube); string inputExt = Path.GetExtension(inputFile); if (cubemapTool == BabylonCubemapTool.ReflectionProbes) { if (inputExt.Equals(".hdr", StringComparison.OrdinalIgnoreCase) || inputExt.Equals(".exr", StringComparison.OrdinalIgnoreCase)) { ExporterWindow.ReportProgress(1, "Baking cubemap reflection probe... This may take a while."); string outputFile = inputFile.Replace(inputExt, "Probe.hdr"); int reflectionResolution = (int)reflectionType; FREE_IMAGE_FORMAT srcType = FREE_IMAGE_FORMAT.FIF_HDR; if (inputExt.Equals(".hdr", StringComparison.OrdinalIgnoreCase)) { srcType = FREE_IMAGE_FORMAT.FIF_HDR; } else if (inputExt.Equals(".exr", StringComparison.OrdinalIgnoreCase)) { srcType = FREE_IMAGE_FORMAT.FIF_EXR; } FREE_IMAGE_FILTER rescaleFilter = FREE_IMAGE_FILTER.FILTER_LANCZOS3; int rescaleWidth = reflectionResolution * 4; int rescaleHeight = rescaleWidth / 2; FileStream destStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write); FileStream sourceStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read); try { Tools.ConvertFreeImage(sourceStream, srcType, destStream, FREE_IMAGE_FORMAT.FIF_HDR, FREE_IMAGE_TYPE.FIT_UNKNOWN, true, FREE_IMAGE_COLOR_DEPTH.FICD_AUTO, FREE_IMAGE_LOAD_FLAGS.DEFAULT, FREE_IMAGE_SAVE_FLAGS.DEFAULT, 0.0, false, false, rescaleWidth, rescaleHeight, rescaleFilter); } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { destStream.Close(); sourceStream.Close(); } if (System.IO.File.Exists(outputFile)) { AssetDatabase.ImportAsset(outputFile, ImportAssetOptions.ForceUpdate); var importTool = new BabylonTextureImporter(outputFile); importTool.textureImporter.textureShape = TextureImporterShape.TextureCube; importTool.textureImporter.isReadable = true; importTool.ForceUpdate(); } } else { ExporterWindow.ShowMessage("You must select a high dynamic range cubemap"); } } else if (cubemapTool == BabylonCubemapTool.CubemapSplitter) { ExporterWindow.ReportProgress(1, "Baking cubemap texture faces... This may take a while."); bool jpeg = (imageFormat == BabylonImageFormat.JPEG); string faceExt = (jpeg) ? ".jpg" : ".png"; var splitterOpts = new BabylonSplitterOptions(); var outputFile = inputFile.Replace(inputExt, faceExt); Tools.ExportCubemap(convertCube, outputFile, imageFormat, splitterOpts); if (createSkyboxMaterial == true) { ExporterWindow.ReportProgress(1, "Generating skybox material assets... This may take a while."); AssetDatabase.Refresh(); Material skyboxMaterial = new Material(Shader.Find("Mobile/Skybox")); if (skyboxMaterial != null) { string frontFilename = outputFile.Replace(faceExt, ("_pz" + faceExt)); AssetDatabase.ImportAsset(frontFilename, ImportAssetOptions.ForceUpdate); Texture2D frontTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(frontFilename, typeof(Texture2D)); if (frontTexture != null) { skyboxMaterial.SetTexture("_FrontTex", frontTexture); } string backFilename = outputFile.Replace(faceExt, ("_nz" + faceExt)); AssetDatabase.ImportAsset(backFilename, ImportAssetOptions.ForceUpdate); Texture2D backTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(backFilename, typeof(Texture2D)); if (backTexture != null) { skyboxMaterial.SetTexture("_BackTex", backTexture); } string leftFilename = outputFile.Replace(faceExt, ("_px" + faceExt)); AssetDatabase.ImportAsset(leftFilename, ImportAssetOptions.ForceUpdate); Texture2D leftTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(leftFilename, typeof(Texture2D)); if (leftTexture != null) { skyboxMaterial.SetTexture("_LeftTex", leftTexture); } string rightFilename = outputFile.Replace(faceExt, ("_nx" + faceExt)); AssetDatabase.ImportAsset(rightFilename, ImportAssetOptions.ForceUpdate); Texture2D rightTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(rightFilename, typeof(Texture2D)); if (rightTexture != null) { skyboxMaterial.SetTexture("_RightTex", rightTexture); } string upFilename = outputFile.Replace(faceExt, ("_py" + faceExt)); AssetDatabase.ImportAsset(upFilename, ImportAssetOptions.ForceUpdate); Texture2D upTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(upFilename, typeof(Texture2D)); if (upTexture != null) { skyboxMaterial.SetTexture("_UpTex", upTexture); } string downFilename = outputFile.Replace(faceExt, ("_ny" + faceExt)); AssetDatabase.ImportAsset(downFilename, ImportAssetOptions.ForceUpdate); Texture2D downTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(downFilename, typeof(Texture2D)); if (downTexture != null) { skyboxMaterial.SetTexture("_DownTex", downTexture); } string outputMaterialName = Path.GetFileNameWithoutExtension(inputFile); string outputMaterialPath = Path.GetDirectoryName(inputFile); string outputMaterialFile = outputMaterialPath + "/" + outputMaterialName + ".mat"; AssetDatabase.CreateAsset(skyboxMaterial, outputMaterialFile); } else { throw new Exception("Failed to create 'Mobile/Skybox' material"); } } } } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { ExporterWindow.ReportProgress(1, "Refresing assets database..."); AssetDatabase.Refresh(); } ExporterWindow.ReportProgress(1, "Cubemap conversion complete."); EditorUtility.ClearProgressBar(); if (this.keepGeneratorOpen) { ExporterWindow.ShowMessage("Cubemap optimzation complete.", "Babylon.js"); } else { this.Close(); } }
public void OnGUI() { splitLabel = "Bake Cubemap Textures"; if (this.maxSize.y != 602f) { this.maxSize = new Vector2(500.0f, 602.0f); this.minSize = this.maxSize; } EditorGUILayout.Space(); convertCube = EditorGUILayout.ObjectField("Source Cubemap Image:", convertCube, typeof(Cubemap), false) as Cubemap; EditorGUILayout.Space(); generateSkybox = EditorGUILayout.Toggle("Create Skybox:", generateSkybox); EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(generateSkybox == false); skyboxOption = (BabylonSkyboxOption)EditorGUILayout.EnumPopup("Skybox Option:", skyboxOption, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); if (skyboxOption == BabylonSkyboxOption.SixSidedCubemap) { skyboxSplitter = (BabylonImageFormat)EditorGUILayout.EnumPopup("Skybox Format:", skyboxSplitter, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); } else if (skyboxOption == BabylonSkyboxOption.DirectDrawSurface) { skyboxConverter = (BabylonFilterFormat)EditorGUILayout.EnumPopup("Skybox Format:", skyboxConverter, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); } EditorGUI.EndDisabledGroup(); generateRadiance = EditorGUILayout.Toggle("Generate Radiance:", generateRadiance); EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(generateRadiance == false); radianceSize = (BabylonReflectionProbe)EditorGUILayout.EnumPopup("Radiance Size:", radianceSize, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); excludeBase = EditorGUILayout.Toggle("Exclude Base:", excludeBase); EditorGUILayout.Space(); glossScale = (int)EditorGUILayout.Slider("Gloss Scale", glossScale, 0, 20); EditorGUILayout.Space(); gloassBias = (int)EditorGUILayout.Slider("Gloss Bias", gloassBias, 0, 10); EditorGUILayout.Space(); EditorGUI.EndDisabledGroup(); EditorGUILayout.LabelField(new GUIContent("Filtering Options"), EditorStyles.boldLabel); EditorGUILayout.Space(); filterOutput = (BabylonCubemapFormat)EditorGUILayout.EnumPopup("Filter Output:", filterOutput, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); filterLighting = (BabylonCubemapLight)EditorGUILayout.EnumPopup("Filter Lighting:", filterLighting, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); EditorGUILayout.LabelField(new GUIContent("Processing Options"), EditorStyles.boldLabel); EditorGUILayout.Space(); inputGammaNumerator = (float)EditorGUILayout.Slider("Input Numerator", inputGammaNumerator, 0.0f, 10.0f); EditorGUILayout.Space(); inputGammaDenominator = (float)EditorGUILayout.Slider("Input Denominator", inputGammaDenominator, 0.0f, 10.0f); EditorGUILayout.Space(); outputGammaNumerator = (float)EditorGUILayout.Slider("Output Numerator", outputGammaNumerator, 0.0f, 10.0f); EditorGUILayout.Space(); outputGammaDenominator = (float)EditorGUILayout.Slider("Output Denominator", outputGammaDenominator, 0.0f, 10.0f); EditorGUILayout.Space(); numberOfCpus = (int)EditorGUILayout.Slider("Number Of Processors", numberOfCpus, 1, 32); EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(generateSkybox == false); createSkyboxMaterial = EditorGUILayout.Toggle("Create Skybox Material:", createSkyboxMaterial); EditorGUILayout.Space(); EditorGUI.EndDisabledGroup(); keepGeneratorOpen = EditorGUILayout.Toggle("Keep Generator Open:", keepGeneratorOpen); EditorGUILayout.Space(); if (GUILayout.Button(splitLabel)) { if (convertCube) { Bake(); } if (!convertCube) { ExporterWindow.ShowMessage("You must select a cubemap"); } } }
public void Parse() { // Validate Project Platform if (!Unity3D2Babylon.Tools.ValidateProjectPlatform()) { return; } try { ExporterWindow.ReportProgress(1, "Generating particle system data... This may take a while."); System.Threading.Thread.Sleep(500); bool starting = (convertCurveValues == BabylonCurveValues.StartCurveValue); var renderer = shurikenParticles.GetComponent <Renderer>(); if (renderer != null) { babylonParticles.textureImage = renderer.sharedMaterial.mainTexture as Texture2D; } babylonParticles.loopPlay = shurikenParticles.main.loop; babylonParticles.duration = shurikenParticles.main.duration; babylonParticles.capacity = shurikenParticles.main.maxParticles; // Bursting babylonParticles.emitBurst = null; if (shurikenParticles.emission.burstCount > 0) { ParticleSystem.Burst[] bursts = new ParticleSystem.Burst[shurikenParticles.emission.burstCount]; shurikenParticles.emission.GetBursts(bursts); var burstList = new List <BabylonParticleBusrt>(); foreach (var burst in bursts) { burstList.Add(new BabylonParticleBusrt() { time = burst.time, minCount = burst.minCount, maxCount = burst.maxCount }); } if (burstList.Count > 0) { babylonParticles.emitBurst = burstList.ToArray(); } } // TODO: Direction // TODO: Volume // Gravity if (shurikenParticles.main.gravityModifier.mode == ParticleSystemCurveMode.Constant) { babylonParticles.gravityMultiplier = shurikenParticles.main.gravityModifier.constant; } else if (shurikenParticles.main.gravityModifier.mode == ParticleSystemCurveMode.TwoConstants) { babylonParticles.gravityMultiplier = (starting) ? shurikenParticles.main.gravityModifier.constantMin : shurikenParticles.main.gravityModifier.constantMax; } else if (shurikenParticles.main.gravityModifier.mode == ParticleSystemCurveMode.Curve) { int curves = (starting) ? 0 : shurikenParticles.main.gravityModifier.curve.keys.Length - 1; babylonParticles.gravityMultiplier = shurikenParticles.main.gravityModifier.curve.keys[curves].value; } else if (shurikenParticles.main.gravityModifier.mode == ParticleSystemCurveMode.TwoCurves) { int curves = (starting) ? 0 : shurikenParticles.main.gravityModifier.curveMin.keys.Length - 1; babylonParticles.gravityMultiplier = shurikenParticles.main.gravityModifier.curveMin.keys[curves].value; } else { babylonParticles.gravityMultiplier = 1.0f; } // Delay if (shurikenParticles.main.startDelay.mode == ParticleSystemCurveMode.Constant) { babylonParticles.delayTime = shurikenParticles.main.startDelay.constant; } else if (shurikenParticles.main.startDelay.mode == ParticleSystemCurveMode.TwoConstants) { babylonParticles.delayTime = (starting) ? shurikenParticles.main.startDelay.constantMin : shurikenParticles.main.startDelay.constantMax; } else if (shurikenParticles.main.startDelay.mode == ParticleSystemCurveMode.Curve) { int curves = (starting) ? 0 : shurikenParticles.main.startDelay.curve.keys.Length - 1; babylonParticles.delayTime = shurikenParticles.main.startDelay.curve.keys[curves].value; } else if (shurikenParticles.main.startDelay.mode == ParticleSystemCurveMode.TwoCurves) { int curves = (starting) ? 0 : shurikenParticles.main.startDelay.curveMin.keys.Length - 1; babylonParticles.delayTime = shurikenParticles.main.startDelay.curveMin.keys[curves].value; } else { babylonParticles.delayTime = 0.0f; } // Speed if (shurikenParticles.main.startSpeed.mode == ParticleSystemCurveMode.Constant) { babylonParticles.startSpeed = shurikenParticles.main.startSpeed.constant * this.updateSpeedModifier; } else if (shurikenParticles.main.startSpeed.mode == ParticleSystemCurveMode.TwoConstants) { float constant = (starting) ? shurikenParticles.main.startSpeed.constantMin : shurikenParticles.main.startSpeed.constantMax; babylonParticles.startSpeed = constant * this.updateSpeedModifier; } else if (shurikenParticles.main.startSpeed.mode == ParticleSystemCurveMode.Curve) { int curves = (starting) ? 0 : shurikenParticles.main.startSpeed.curve.keys.Length - 1; babylonParticles.startSpeed = shurikenParticles.main.startSpeed.curve.keys[curves].value * this.updateSpeedModifier; } else if (shurikenParticles.main.startSpeed.mode == ParticleSystemCurveMode.TwoCurves) { int curves = (starting) ? 0 : shurikenParticles.main.startSpeed.curveMin.keys.Length - 1; babylonParticles.startSpeed = shurikenParticles.main.startSpeed.curveMin.keys[curves].value * this.updateSpeedModifier; } else { babylonParticles.startSpeed = 0.01f; } // Emission babylonParticles.emitPower = new Vector2(1.0f, 1.0f); if (shurikenParticles.emission.rateOverTime.mode == ParticleSystemCurveMode.Constant) { babylonParticles.emitRate = shurikenParticles.emission.rateOverTime.constant * this.emitRateModifier; } else if (shurikenParticles.emission.rateOverTime.mode == ParticleSystemCurveMode.TwoConstants) { float constant = (starting) ? shurikenParticles.emission.rateOverTime.constantMin : shurikenParticles.emission.rateOverTime.constantMax; babylonParticles.emitRate = constant * this.emitRateModifier; } else if (shurikenParticles.emission.rateOverTime.mode == ParticleSystemCurveMode.Curve) { int curves = (starting) ? 0 : shurikenParticles.emission.rateOverTime.curve.keys.Length - 1; babylonParticles.emitRate = shurikenParticles.emission.rateOverTime.curve.keys[curves].value * this.emitRateModifier; } else if (shurikenParticles.emission.rateOverTime.mode == ParticleSystemCurveMode.TwoCurves) { int curves = (starting) ? 0 : shurikenParticles.emission.rateOverTime.curveMin.keys.Length - 1; babylonParticles.emitRate = shurikenParticles.emission.rateOverTime.curveMin.keys[curves].value * this.emitRateModifier; } else { babylonParticles.emitRate = 10.0f; } // Lifetime if (shurikenParticles.main.startLifetime.mode == ParticleSystemCurveMode.Constant) { babylonParticles.lifeTime.x = shurikenParticles.main.startLifetime.constant; babylonParticles.lifeTime.y = shurikenParticles.main.startLifetime.constant; } else if (shurikenParticles.main.startLifetime.mode == ParticleSystemCurveMode.TwoConstants) { babylonParticles.lifeTime.x = shurikenParticles.main.startLifetime.constantMin; babylonParticles.lifeTime.y = shurikenParticles.main.startLifetime.constantMax; } else if (shurikenParticles.main.startLifetime.mode == ParticleSystemCurveMode.Curve) { int curves = shurikenParticles.main.startLifetime.curve.keys.Length - 1; babylonParticles.lifeTime.x = shurikenParticles.main.startLifetime.curve.keys[0].value; babylonParticles.lifeTime.y = shurikenParticles.main.startLifetime.curve.keys[curves].value; } else if (shurikenParticles.main.startLifetime.mode == ParticleSystemCurveMode.TwoCurves) { int curves = shurikenParticles.main.startLifetime.curveMin.keys.Length - 1; babylonParticles.lifeTime.x = shurikenParticles.main.startLifetime.curveMin.keys[0].value; babylonParticles.lifeTime.y = shurikenParticles.main.startLifetime.curveMin.keys[curves].value; } else { babylonParticles.lifeTime.x = 1.0f; babylonParticles.lifeTime.y = 1.0f; } // Sizing if (shurikenParticles.main.startSize.mode == ParticleSystemCurveMode.Constant) { babylonParticles.particleSize.x = shurikenParticles.main.startSize.constant; babylonParticles.particleSize.y = shurikenParticles.main.startSize.constant; } else if (shurikenParticles.main.startSize.mode == ParticleSystemCurveMode.TwoConstants) { babylonParticles.particleSize.x = shurikenParticles.main.startSize.constantMin; babylonParticles.particleSize.y = shurikenParticles.main.startSize.constantMax; } else if (shurikenParticles.main.startSize.mode == ParticleSystemCurveMode.Curve) { int curves = shurikenParticles.main.startSize.curve.keys.Length - 1; babylonParticles.particleSize.x = shurikenParticles.main.startSize.curve.keys[0].value; babylonParticles.particleSize.y = shurikenParticles.main.startSize.curve.keys[curves].value; } else if (shurikenParticles.main.startSize.mode == ParticleSystemCurveMode.TwoCurves) { int curves = shurikenParticles.main.startSize.curveMin.keys.Length - 1; babylonParticles.particleSize.x = shurikenParticles.main.startSize.curveMin.keys[0].value; babylonParticles.particleSize.y = shurikenParticles.main.startSize.curveMin.keys[curves].value; } else { babylonParticles.particleSize.x = 1.0f; babylonParticles.particleSize.y = 1.0f; } // Rotation if (shurikenParticles.main.startRotation.mode == ParticleSystemCurveMode.Constant) { babylonParticles.angularSpeed.x = shurikenParticles.main.startRotation.constant; babylonParticles.angularSpeed.y = shurikenParticles.main.startRotation.constant; } else if (shurikenParticles.main.startRotation.mode == ParticleSystemCurveMode.TwoConstants) { babylonParticles.angularSpeed.x = shurikenParticles.main.startRotation.constantMin; babylonParticles.angularSpeed.y = shurikenParticles.main.startRotation.constantMax; } else if (shurikenParticles.main.startRotation.mode == ParticleSystemCurveMode.Curve) { int curves = shurikenParticles.main.startRotation.curve.keys.Length - 1; babylonParticles.angularSpeed.x = shurikenParticles.main.startRotation.curve.keys[0].value; babylonParticles.angularSpeed.y = shurikenParticles.main.startRotation.curve.keys[curves].value; } else if (shurikenParticles.main.startRotation.mode == ParticleSystemCurveMode.TwoCurves) { int curves = shurikenParticles.main.startRotation.curveMin.keys.Length - 1; babylonParticles.angularSpeed.x = shurikenParticles.main.startRotation.curveMin.keys[0].value; babylonParticles.angularSpeed.y = shurikenParticles.main.startRotation.curveMax.keys[curves].value; } else { babylonParticles.angularSpeed.x = 0.0f; babylonParticles.angularSpeed.y = 0.0f; } // Color if (shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.Color) { babylonParticles.color1 = shurikenParticles.main.startColor.color; babylonParticles.color2 = shurikenParticles.main.startColor.color; } else if (shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.TwoColors) { babylonParticles.color1 = shurikenParticles.main.startColor.colorMin; babylonParticles.color2 = shurikenParticles.main.startColor.colorMax; } else if (shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.Gradient || shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.RandomColor) { int gradients = shurikenParticles.main.startColor.gradient.colorKeys.Length - 1; babylonParticles.color1 = shurikenParticles.main.startColor.gradient.colorKeys[0].color; babylonParticles.color2 = shurikenParticles.main.startColor.gradient.colorKeys[gradients].color; } else if (shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.TwoGradients) { int gradients = shurikenParticles.main.startColor.gradientMin.colorKeys.Length - 1; babylonParticles.color1 = shurikenParticles.main.startColor.gradientMin.colorKeys[0].color; babylonParticles.color2 = shurikenParticles.main.startColor.gradientMin.colorKeys[gradients].color; } else { babylonParticles.color1 = defaultColor; babylonParticles.color2 = defaultColor; } // Shuriken if (this.exportShurikenData) { // TODO: Parse Shuriken Particle System Metadata } } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { ExporterWindow.ReportProgress(1, "Refresing assets database..."); AssetDatabase.Refresh(); } System.Threading.Thread.Sleep(500); ExporterWindow.ReportProgress(1, "Particle system generation complete."); EditorUtility.ClearProgressBar(); if (this.keepGeneratorOpen) { ExporterWindow.ShowMessage("Particle system generation complete.", "Babylon.js"); } else { this.Close(); } }
public void ExportHeightmap() { // Validate Project Platform if (!Unity3D2Babylon.Tools.ValidateProjectPlatform()) { return; } if (heightmapTexture == null || String.IsNullOrEmpty(heightmapFile)) { return; } // .. bool exportRaw = (exportFormat == BabylonHeightmapFormat.RAW); string exportExt = (exportRaw) ? "raw" : "png"; string exportDir = Path.GetDirectoryName(heightmapFile); string exportFile = Path.GetFileNameWithoutExtension(heightmapFile); // .. string filename = EditorUtility.SaveFilePanel("Export Heightmap Image", exportDir, exportFile, exportExt); if (String.IsNullOrEmpty(filename)) { return; } if (File.Exists(filename)) { if (!ExporterWindow.ShowMessage("Overwrite the selected file?", "Babylon.js", "Overwrite", "Cancel")) { return; } } // .. try { ExporterWindow.ReportProgress(1, "Baking heightmap image data... This may take a while."); Texture2D exportTexture = heightmapTexture.Copy(heightmapTexture.format); if (enableResolution == true && exportResolution != heightmapResolution) { int saveResolution = exportResolution; if (saveResolution <= 0) { saveResolution = 1; } exportTexture.Scale(saveResolution, saveResolution, (exportScaling == BabylonTextureScale.Bilinear)); } if (exportRaw) { exportTexture = Tools.FlipTexture(exportTexture); } if (exportRaw) { exportTexture.WriteImageRAW16(filename); } else { exportTexture.WriteImagePNG16(filename, true); } } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { ExporterWindow.ReportProgress(1, "Refresing assets database..."); AssetDatabase.Refresh(); ExporterWindow.ReportProgress(1, "Heightmap conversion complete."); EditorUtility.ClearProgressBar(); } if (this.keepGeneratorOpen) { ExporterWindow.ShowMessage("Heightmap exportation complete.", "Babylon.js"); } else { this.Close(); } }
public void CreateTextureAtlas() { if (skinMeshRenderer != null && skinMeshRenderer.sharedMaterials != null && skinMeshRenderer.sharedMaterials.Length > 1) { string filename = EditorUtility.SaveFilePanelInProject("Texture Atlas Skin", "", "asset", "Bake Skin Mesh Renderer Texture Atlas"); if (!String.IsNullOrEmpty(filename)) { ExporterWindow.ReportProgress(1, "Baking texture atlas skin... This may take a while."); string filepath = Path.GetDirectoryName(filename); string filelabel = Path.GetFileNameWithoutExtension(filename); Tools.ValidateAssetFolders(filepath.TrimEnd('/')); // Texture atlas file info bool jpeg = (textureAtlasFormat == BabylonImageFormat.JPEG); string atlasExt = (jpeg) ? "jpg" : "png"; string atlasName = String.Format("{0}_Atlas", filelabel); string atlasFile = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), atlasName, atlasExt); string bumpName = String.Format("{0}_Normal", filelabel); string bumpFile = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), bumpName, atlasExt); string materialName = String.Format("{0}_Material", filelabel); string materialFile = String.Format("{0}/Materials/{1}.asset", filepath.TrimEnd('/'), materialName); // Create atlas textures mainTextures = new List <Texture2D>(); bumpTextures = new List <Texture2D>(); foreach (var material in skinMeshRenderer.sharedMaterials) { Texture2D colorTexture = null; Texture2D normalTexture = null; if (material.mainTexture != null) { Texture2D primaryTexture = material.mainTexture as Texture2D; primaryTexture.ForceReadable(); colorTexture = primaryTexture.Copy(); if (bakeTextureNormals) { if (material.HasProperty("_BumpMap")) { Texture2D bumpTexture = material.GetTexture("_BumpMap") as Texture2D; if (bumpTexture != null && bumpTexture.width == colorTexture.width && bumpTexture.height == colorTexture.height) { // Format texture import settings string bumpTexturePath = AssetDatabase.GetAssetPath(bumpTexture); var importTool = new BabylonTextureImporter(bumpTexturePath); var importType = importTool.textureImporter.textureType; try { importTool.textureImporter.isReadable = true; importTool.textureImporter.textureType = TextureImporterType.Default; importTool.ForceUpdate(); normalTexture = bumpTexture.Copy(); hasBumpTexture = true; } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { // Restore texture importer type importTool.textureImporter.textureType = importType; importTool.ForceUpdate(); } } } } } if (colorTexture == null) { colorTexture = new Texture2D(128, 128, TextureFormat.RGBA32, false); colorTexture.Clear(material.color); normalTexture = null; } if (normalTexture == null) { normalTexture = Tools.CreateBlankNormalMap(colorTexture.width, colorTexture.height); } // Buffer baked material info mainTextures.Add(colorTexture); bumpTextures.Add(normalTexture); } // Encode atlas textures bool bilinearScaling = (textureImageScaling == BabylonTextureScale.Bilinear); Texture2D skinnedMeshAtlas = new Texture2D(128, 128, TextureFormat.RGBA32, false); Rect[] atlasPackingResult = Tools.PackTextureAtlas(skinnedMeshAtlas, mainTextures.ToArray(), textureAtlasSize, maxTextureImageSize, bilinearScaling, false, removeAlphaEncoding); Texture2D skinnedMeshBuffer = skinnedMeshAtlas.Copy(); skinnedMeshBuffer.WriteImage(atlasFile, textureAtlasFormat); AssetDatabase.ImportAsset(atlasFile, ImportAssetOptions.ForceUpdate); // Create atlas material if (textureAtlasShader == null) { textureAtlasShader = Shader.Find("BabylonJS/System/Standard Material"); } atlasMaterial = new Material(textureAtlasShader); atlasMaterial.name = materialName; atlasMaterial.mainTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(atlasFile, typeof(Texture2D)); AssetDatabase.CreateAsset(atlasMaterial, materialFile); if (bakeTextureNormals && hasBumpTexture) { bumpFilename = bumpFile; } // Texture atlas uv coordinates Mesh mesh = skinMeshRenderer.sharedMesh; int numSubs = mesh.subMeshCount; int uvCount = mesh.uv.Length; List <Vector2> uvList = new List <Vector2>(); if (atlasPackingResult != null && atlasPackingResult.Length > 0) { for (int ctr = 0; ctr < numSubs; ctr++) { Mesh sub = mesh.GetSubmesh(ctr); Vector2[] uvs = Tools.GetTextureAtlasCoordinates(sub.uv, ctr, atlasPackingResult, linearInterpolation); uvList.AddRange(uvs); } if (uvList.Count != uvCount) { throw new Exception("Skin vertex count mismatch. Failed to convert uv coordinates."); } } else { UnityEngine.Debug.LogError("Null atlas packing result rects"); } // Create new mesh asset Mesh newmesh = mesh.Copy(); if (uvList.Count > 0) { newmesh.uv = uvList.ToArray(); } // Save new mesh asset string label = Tools.FirstUpper(materialName.Replace("_Material", "")); string meshName = String.Format("{0}_{1}_Mesh", label, skinMeshRenderer.name); string meshFile = String.Format("{0}/Geometry/{1}.asset", filepath.TrimEnd('/'), meshName); AssetDatabase.CreateAsset(newmesh, meshFile); if (updateSkinRenderer) { skinMeshRenderer.sharedMesh = (Mesh)AssetDatabase.LoadAssetAtPath(meshFile, typeof(Mesh)); skinMeshRenderer.sharedMaterials = new Material[] { (Material)AssetDatabase.LoadAssetAtPath(materialFile, typeof(Material)) }; } } } else { ExporterWindow.ShowMessage("At least 2 materials required for texture atlas skin"); } }
public void CreateTextureAtlas() { if (skinMeshRenderer != null && skinMeshRenderer.sharedMaterials != null && skinMeshRenderer.sharedMaterials.Length > 1) { string filename = EditorUtility.SaveFilePanelInProject("Texture Atlas Skin", "", "asset", "Bake Skin Mesh Renderer Texture Atlas"); if (!String.IsNullOrEmpty(filename)) { ExporterWindow.ReportProgress(1, "Baking texture atlas skin... This may take a while."); string filepath = Path.GetDirectoryName(filename); string filelabel = Path.GetFileNameWithoutExtension(filename); Tools.ValidateAssetFolders(filepath.TrimEnd('/')); // Texture atlas file info string atlasExt = "png"; string atlasName = String.Format("{0}_Texture_Atlas", filelabel); string atlasFile = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), atlasName, atlasExt); string bumpName = String.Format("{0}_Normal_Atlas", filelabel); string bumpFile = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), bumpName, atlasExt); string ambientName = String.Format("{0}_Ambient_Atlas", filelabel); string ambientFile = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), ambientName, atlasExt); string emissionName = String.Format("{0}_Emission_Atlas", filelabel); string emissionFile = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), emissionName, atlasExt); string metallicName = String.Format("{0}_Metallic_Atlas", filelabel); string metallicFile = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), metallicName, atlasExt); string specularName = String.Format("{0}_Specular_Atlas", filelabel); string specularFile = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), specularName, atlasExt); string materialName = String.Format("{0}_Material", filelabel); string materialFile = String.Format("{0}/Materials/{1}.asset", filepath.TrimEnd('/'), materialName); // Create atlas textures mainTextures = new List <Texture2D>(); bumpTextures = new List <Texture2D>(); ambientTextures = new List <Texture2D>(); emissionTextures = new List <Texture2D>(); metallicTextures = new List <Texture2D>(); specularTextures = new List <Texture2D>(); foreach (var material in skinMeshRenderer.sharedMaterials) { Texture2D colorTexture = null; Texture2D normalTexture = null; Texture2D ambientTexture = null; Texture2D emissionTexture = null; Texture2D metallicTexture = null; Texture2D specularTexture = null; bool metallicTextureSRGB = true; if (material.mainTexture != null) { Texture2D primaryTexture = material.mainTexture as Texture2D; primaryTexture.ForceReadable(); colorTexture = primaryTexture.Copy(); if (colorTexture != null && bakeTextureMaps == true) { if (material.HasProperty("_BumpMap")) { Texture2D bumpTexture = material.GetTexture("_BumpMap") as Texture2D; if (bumpTexture != null) { // Format texture import settings string bumpTexturePath = AssetDatabase.GetAssetPath(bumpTexture); var importTool = new BabylonTextureImporter(bumpTexturePath); var importType = importTool.textureImporter.textureType; try { importTool.textureImporter.isReadable = true; importTool.textureImporter.textureType = TextureImporterType.Default; importTool.ForceUpdate(); normalTexture = bumpTexture.Copy(); if (normalTexture.width != colorTexture.width || normalTexture.height != colorTexture.height) { normalTexture.Scale(colorTexture.width, colorTexture.height); } } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { // Restore texture importer type importTool.textureImporter.textureType = importType; importTool.ForceUpdate(); } } } if (material.HasProperty("_EmissionMap")) { Texture2D emitTexture = material.GetTexture("_EmissionMap") as Texture2D; if (emitTexture != null) { // Format texture import settings string emissionTexturePath = AssetDatabase.GetAssetPath(emitTexture); var importTool = new BabylonTextureImporter(emissionTexturePath); var importType = importTool.textureImporter.textureType; try { importTool.textureImporter.isReadable = true; importTool.textureImporter.textureType = TextureImporterType.Default; importTool.ForceUpdate(); emissionTexture = emitTexture.Copy(); if (emissionTexture.width != colorTexture.width || emissionTexture.height != colorTexture.height) { emissionTexture.Scale(colorTexture.width, colorTexture.height); } } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { // Restore texture importer type importTool.textureImporter.textureType = importType; importTool.ForceUpdate(); } } } if (material.HasProperty("_OcclusionMap")) { Texture2D occlusionTexture = material.GetTexture("_OcclusionMap") as Texture2D; if (occlusionTexture != null) { // Format texture import settings string occlusionTexturePath = AssetDatabase.GetAssetPath(occlusionTexture); var importTool = new BabylonTextureImporter(occlusionTexturePath); var importType = importTool.textureImporter.textureType; try { importTool.textureImporter.isReadable = true; importTool.textureImporter.textureType = TextureImporterType.Default; importTool.ForceUpdate(); ambientTexture = occlusionTexture.Copy(); if (ambientTexture.width != colorTexture.width || ambientTexture.height != colorTexture.height) { ambientTexture.Scale(colorTexture.width, colorTexture.height); } } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { // Restore texture importer type importTool.textureImporter.textureType = importType; importTool.ForceUpdate(); } } } if (material.HasProperty("_MetallicGlossMap")) { Texture2D metalnessTexture = material.GetTexture("_MetallicGlossMap") as Texture2D; if (metalnessTexture != null) { // Format texture import settings metallicTextureSRGB = metalnessTexture.IsSRGB(); string metalnessTexturePath = AssetDatabase.GetAssetPath(metalnessTexture); var importTool = new BabylonTextureImporter(metalnessTexturePath); var importType = importTool.textureImporter.textureType; try { importTool.textureImporter.isReadable = true; importTool.textureImporter.textureType = TextureImporterType.Default; importTool.ForceUpdate(); metallicTexture = metalnessTexture.Copy(); if (metallicTexture.width != colorTexture.width || metallicTexture.height != colorTexture.height) { metallicTexture.Scale(colorTexture.width, colorTexture.height); } } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { // Restore texture importer type importTool.textureImporter.textureType = importType; importTool.ForceUpdate(); } } } if (material.HasProperty("_SpecGlossMap")) { Texture2D glossTexture = material.GetTexture("_SpecGlossMap") as Texture2D; if (glossTexture != null) { // Format texture import settings string specularTexturePath = AssetDatabase.GetAssetPath(glossTexture); var importTool = new BabylonTextureImporter(specularTexturePath); var importType = importTool.textureImporter.textureType; try { importTool.textureImporter.isReadable = true; importTool.textureImporter.textureType = TextureImporterType.Default; importTool.ForceUpdate(); specularTexture = glossTexture.Copy(); if (specularTexture.width != colorTexture.width || specularTexture.height != colorTexture.height) { specularTexture.Scale(colorTexture.width, colorTexture.height); } } catch (Exception ex) { UnityEngine.Debug.LogException(ex); } finally { // Restore texture importer type importTool.textureImporter.textureType = importType; importTool.ForceUpdate(); } } } } } if (colorTexture == null) { colorTexture = Tools.CreateBlankTextureMap(256, 256, material.color); normalTexture = null; ambientTexture = null; emissionTexture = null; metallicTexture = null; specularTexture = null; } var mode = material.HasProperty("_Mode") ? (BlendMode)material.GetFloat("_Mode") : BlendMode.Opaque; if (colorTexture != null && mode == BlendMode.Opaque) { colorTexture.MakeAlpha(1.0f); } if (normalTexture == null) { normalTexture = Tools.CreateBlankNormalMap(colorTexture.width, colorTexture.height); } if (emissionTexture == null) { Color emissionColor = material.HasProperty("_EmissionColor") ? material.GetColor("_EmissionColor") : material.HasProperty("_Emission") ? material.GetColor("_Emission") : Color.black; emissionTexture = Tools.CreateBlankTextureMap(colorTexture.width, colorTexture.height, emissionColor); } if (ambientTexture == null) { Color ambientColor = material.HasProperty("_AmbientColor") ? material.GetColor("_AmbientColor") : Color.white; ambientTexture = Tools.CreateBlankTextureMap(colorTexture.width, colorTexture.height, ambientColor); } float metalness = 0.0f, glossiness = 0.5f; if (material.HasProperty("_Metallic")) { metalness = Tools.GammaToLinearSpace(material.GetFloat("_Metallic")); } if (material.HasProperty("_Roughness")) { glossiness = (1.0f - material.GetFloat("_Roughness")); } else if (material.HasProperty("_Glossiness")) { glossiness = material.GetFloat("_Glossiness"); } else if (material.HasProperty("_Gloss")) { glossiness = material.GetFloat("_Gloss"); } float glossinessScale = material.HasProperty("_GlossMapScale") ? material.GetFloat("_GlossMapScale") : 0.5f; bool glossyRelfections = (material.HasProperty("_GlossyReflections") && material.GetFloat("_GlossyReflections") != 0.0f); if (glossyRelfections == false) { glossiness = 0.0f; glossinessScale = 0.0f; } glossiness = Tools.GetGlossinessScale(glossiness); glossinessScale = Tools.GetGlossinessScale(glossinessScale); if (metallicTexture == null) { Color metallicColor = Color.white; metallicTexture = Tools.CreateBlankTextureMap(colorTexture.width, colorTexture.height, metallicColor); metallicTexture = Tools.EncodeMetallicTextureMap(metallicTexture, metalness, glossinessScale); } else { metallicTexture = Tools.CreateMetallicTextureMap(metallicTexture, glossinessScale, metallicTextureSRGB); } if (specularTexture == null) { Color specularColor = material.HasProperty("_SpecColor") ? material.GetColor("_SpecColor") : Color.black; specularColor.a *= glossiness; specularTexture = Tools.CreateBlankTextureMap(colorTexture.width, colorTexture.height, specularColor); } else { specularTexture = Tools.CreateSpecularTextureMap(specularTexture, glossiness); } // Buffer baked material info mainTextures.Add(colorTexture); bumpTextures.Add(normalTexture); ambientTextures.Add(ambientTexture); emissionTextures.Add(emissionTexture); metallicTextures.Add(metallicTexture); specularTextures.Add(specularTexture); } // Encode atlas textures bool bilinearScaling = (textureImageScaling == BabylonTextureScale.Bilinear); Texture2D skinnedMeshAtlas = new Texture2D(128, 128, TextureFormat.RGBA32, false); Rect[] atlasPackingResult = Tools.PackTextureAtlas(skinnedMeshAtlas, mainTextures.ToArray(), textureAtlasSize, maxTextureImageSize, bilinearScaling, false); Texture2D skinnedMeshBuffer = skinnedMeshAtlas.Copy(); skinnedMeshBuffer.alphaIsTransparency = true; skinnedMeshBuffer.WriteImage(atlasFile, textureAtlasFormat); AssetDatabase.ImportAsset(atlasFile, ImportAssetOptions.ForceUpdate); // Create atlas material(s) if (textureAtlasShader == null) { textureAtlasShader = Shader.Find("Standard"); } atlasMaterial = new Material(textureAtlasShader); atlasMaterial.name = materialName; atlasMaterial.mainTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(atlasFile, typeof(Texture2D)); AssetDatabase.CreateAsset(atlasMaterial, materialFile); if (bakeTextureMaps) { bumpFilename = bumpFile; ambientFilename = ambientFile; emissionFilename = emissionFile; metallicFilename = metallicFile; specularFilename = specularFile; } // Texture atlas uv coordinates Mesh mesh = skinMeshRenderer.sharedMesh; int numSubs = mesh.subMeshCount; int uvCount = mesh.uv.Length; List <Vector2> uvList = new List <Vector2>(); if (atlasPackingResult != null && atlasPackingResult.Length > 0) { for (int ctr = 0; ctr < numSubs; ctr++) { Mesh sub = mesh.GetSubmesh(ctr); Vector2[] uvs = Tools.GetTextureAtlasCoordinates(sub.uv, ctr, atlasPackingResult, linearInterpolation); uvList.AddRange(uvs); } if (uvList.Count != uvCount) { throw new Exception("Skin vertex count mismatch. Failed to convert uv coordinates."); } } else { UnityEngine.Debug.LogError("Null atlas packing result rects"); } // Create new mesh asset Mesh newmesh = mesh.Copy(); if (uvList.Count > 0) { newmesh.uv = uvList.ToArray(); } // Save new mesh asset string label = Tools.FirstUpper(materialName.Replace("_Material", "")); string meshName = String.Format("{0}_{1}_Mesh", label, skinMeshRenderer.name.MakeSafe()); string meshFile = String.Format("{0}/Geometry/{1}.asset", filepath.TrimEnd('/'), meshName); AssetDatabase.CreateAsset(newmesh, meshFile); if (updateSkinRenderer) { skinMeshRenderer.sharedMesh = (Mesh)AssetDatabase.LoadAssetAtPath(meshFile, typeof(Mesh)); skinMeshRenderer.sharedMaterials = new Material[] { (Material)AssetDatabase.LoadAssetAtPath(materialFile, typeof(Material)) }; } } } else { ExporterWindow.ShowMessage("At least 2 materials required for texture atlas skin"); } }