private void SetupProjectParameters() { EditorApplication.LockReloadAssemblies(); m_EditorBuildSettings = EditorBuildSettings.scenes; #pragma warning disable 618 m_DisplayResolutionDialog = PlayerSettings.displayResolutionDialog; PlayerSettings.displayResolutionDialog = ResolutionDialogSetting.Disabled; #pragma warning restore 618 m_RunInBackground = PlayerSettings.runInBackground; PlayerSettings.runInBackground = true; m_FullScreenMode = PlayerSettings.fullScreenMode; PlayerSettings.fullScreenMode = FullScreenMode.Windowed; m_OldAotOptions = PlayerSettings.aotOptions; PlayerSettings.aotOptions = "nimt-trampolines=1024"; m_ResizableWindow = PlayerSettings.resizableWindow; PlayerSettings.resizableWindow = true; m_ShowUnitySplashScreen = PlayerSettings.SplashScreen.show; PlayerSettings.SplashScreen.show = false; #pragma warning disable 618 m_OldLightmapping = Lightmapping.giWorkflowMode; Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand; #pragma warning restore 618 m_explicitNullChecks = EditorUserBuildSettings.explicitNullChecks; EditorUserBuildSettings.explicitNullChecks = true; }
/// <summary> /// Changes the lighting GI workflow of a scene asset /// </summary> /// <param name="workflow"></param> /// <param name="targetSceneAsset"></param> private void ChangeSceneLightingGIWorkflow(SceneAsset targetSceneAsset, Lightmapping.GIWorkflowMode workflow) { var originalSelection = Selection.activeObject; var originalContext = Selection.activeContext; var originalScene = EditorSceneManager.GetActiveScene(); // Find the scene we are on so we can change back to it later string newScenePath = AssetDatabase.GetAssetPath(targetSceneAsset); var newScene = EditorSceneManager.GetSceneByPath(newScenePath); // Get the scene reference of the target scene bool requireSceneLoad = !SceneManagerExtensions.IsSceneLoaded(newScene); // If the scene we are going to change lightmaps on is loaded and dirty, warn the user any changes will be saved if (!requireSceneLoad && newScene.isDirty) { if (!EditorUtility.DisplayDialog("Confirm changing GI Lighting Workflow", $"By changing the GI lighting workflow on \"{newScene.name}\" it will have to be saved, do you want to continue?", "Continue", "Cancel")) { return; } } // If the scene we are trying to change isn't loaded load it if (requireSceneLoad) { EditorSceneManager.OpenScene(newScenePath, OpenSceneMode.Additive); } var loadedScene = EditorSceneManager.GetSceneByPath(newScenePath); // Change active scenes to the target so we can change the settings bool requireSceneChange = originalScene != newScene; if (requireSceneChange) { EditorSceneManager.SetActiveScene(loadedScene); } // Change the lightmap workflow Lightmapping.giWorkflowMode = workflow; EditorSceneManager.SaveScene(loadedScene); // Change back to the original scene if (requireSceneChange) { EditorSceneManager.SetActiveScene(originalScene); } // If we loaded the scene unload it when we're done if (requireSceneLoad) { EditorSceneManager.CloseScene(loadedScene, true); } Selection.SetActiveObjectWithContext(originalSelection, originalContext); }
/// <inheritdoc /> protected override IEnumerator OnExecute(JobContext context) { _initialWorkflowMode = Lightmapping.giWorkflowMode; Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand; if (ClearFirst) { Lightmapping.Clear(); } IsSuccess = Lightmapping.BakeAsync(); while (Lightmapping.isRunning) { yield return(null); } Lightmapping.giWorkflowMode = _initialWorkflowMode; LightingDataAssetPath = AssetDatabase.GetAssetPath(Lightmapping.lightingDataAsset); }
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 Save() { if (_ambientEquatorColor != RenderSettings.ambientEquatorColor) { _ambientEquatorColor = RenderSettings.ambientEquatorColor; } if (_ambientGroundColor != RenderSettings.ambientGroundColor) { _ambientGroundColor = RenderSettings.ambientGroundColor; } if (_ambientIntensity != RenderSettings.ambientIntensity) { _ambientIntensity = RenderSettings.ambientIntensity; } if (_subtractiveShadowColor != RenderSettings.subtractiveShadowColor) { _subtractiveShadowColor = RenderSettings.subtractiveShadowColor; } if (_ambientProbe != RenderSettings.ambientProbe) { _ambientProbe = RenderSettings.ambientProbe; } if (_ambientMode != RenderSettings.ambientMode) { _ambientMode = RenderSettings.ambientMode; } if (_ambientSkyColor != RenderSettings.ambientSkyColor) { _ambientSkyColor = RenderSettings.ambientSkyColor; } if (_defaultReflectionMode != RenderSettings.defaultReflectionMode) { _defaultReflectionMode = RenderSettings.defaultReflectionMode; } if (_defaultReflectionResolution != RenderSettings.defaultReflectionResolution) { _defaultReflectionResolution = RenderSettings.defaultReflectionResolution; } if (_reflectionBounces != RenderSettings.reflectionBounces) { _reflectionBounces = RenderSettings.reflectionBounces; } if (_reflectionIntensity != RenderSettings.reflectionIntensity) { _reflectionIntensity = RenderSettings.reflectionIntensity; } if (_aoExponentDirect != LightmapEditorSettings.aoExponentDirect) { _aoExponentDirect = LightmapEditorSettings.aoExponentDirect; } if (_aoExponentIndirect != LightmapEditorSettings.aoExponentIndirect) { _aoExponentIndirect = LightmapEditorSettings.aoExponentIndirect; } if (_aoMaxDistance != LightmapEditorSettings.aoMaxDistance) { _aoMaxDistance = LightmapEditorSettings.aoMaxDistance; } if (_bakeResolution != LightmapEditorSettings.bakeResolution) { _bakeResolution = LightmapEditorSettings.bakeResolution; } if (_enableAmbientOcclusion != LightmapEditorSettings.enableAmbientOcclusion) { _enableAmbientOcclusion = LightmapEditorSettings.enableAmbientOcclusion; } if (_maxAtlasSize != LightmapEditorSettings.maxAtlasSize) { _maxAtlasSize = LightmapEditorSettings.maxAtlasSize; } if (_padding != LightmapEditorSettings.padding) { _padding = LightmapEditorSettings.padding; } if (_realtimeResolution != LightmapEditorSettings.realtimeResolution) { _realtimeResolution = LightmapEditorSettings.realtimeResolution; } if (_reflectionCubemapCompression != LightmapEditorSettings.reflectionCubemapCompression) { _reflectionCubemapCompression = LightmapEditorSettings.reflectionCubemapCompression; } if (_textureCompression != LightmapEditorSettings.textureCompression) { _textureCompression = LightmapEditorSettings.textureCompression; } if (_bakedGI != Lightmapping.bakedGI) { _bakedGI = Lightmapping.bakedGI; } if (_bounceBoost != Lightmapping.bounceBoost) { _bounceBoost = Lightmapping.bounceBoost; } if (_giWorkflowMode != Lightmapping.giWorkflowMode) { _giWorkflowMode = Lightmapping.giWorkflowMode; } if (_indirectOutputScale != Lightmapping.indirectOutputScale) { _indirectOutputScale = Lightmapping.indirectOutputScale; } if (_realtimeGI != Lightmapping.realtimeGI) { _realtimeGI = Lightmapping.realtimeGI; } if (_lightmapsMode != LightmapSettings.lightmapsMode) { _lightmapsMode = LightmapSettings.lightmapsMode; } }
public void Prepare() { _oldLodBias = QualitySettings.lodBias; if (Config.ChangeLODBias) { QualitySettings.lodBias = 20000; } _oldQualityLevel = QualitySettings.GetQualityLevel(); var qualityNames = QualitySettings.names; for (int i = 0; i < qualityNames.Length; ++i) { if (qualityNames[i].Contains(LowLevelName)) { QualitySettings.SetQualityLevel(i); } } _oldShadowQuality = QualitySettings.shadows; QualitySettings.shadows = ShadowQuality.Disable; _oldGiWorkflowMode = Lightmapping.giWorkflowMode; Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.Legacy; var probes = GameObject.FindObjectsOfType <ReflectionProbe>(); foreach (var probe in probes) { if (probe.enabled) { probe.enabled = false; _reflectionProbeList.Add(probe); } } var lights = GameObject.FindObjectsOfType <Light>(); foreach (var light in lights) { if (light.enabled) { light.enabled = false; _lightList.Add(light); } } var lightProbeGroup = GameObject.FindObjectsOfType <LightProbeGroup>(); foreach (var lightProbe in lightProbeGroup) { if (lightProbe.enabled) { lightProbe.enabled = false; _lightProbeGroupList.Add(lightProbe); } } Projector[] projectList = Object.FindObjectsOfType <Projector>(); foreach (var p in projectList) { if (p != null && p.enabled) { p.enabled = false; projects.Add(p); } } //set terrain materials _oldTerrainMats.Clear(); Terrain[] terrains = Object.FindObjectsOfType <Terrain>(); foreach (var terrain in terrains) { _oldTerrainMats.Add(terrain, terrain.drawTreesAndFoliage); //terrain.materialType = Terrain.MaterialType.Custom; //terrain.materialTemplate = terrainMaterial; terrain.drawTreesAndFoliage = false; } Renderer[] mrs = Object.FindObjectsOfType <Renderer>(); // Debug.LogFormat("DisableInvisibleRenderers call, find all meshrenderer count:{0} time:{1}", mrs.Length, System.DateTime.Now); // 查找所有潜在可视集合 _visibleSet.Clear(); _oldTransparentMats.Clear(); for (int i = 0; i < mrs.Length; i++) { Renderer mr = mrs[i]; if (mr == null || !mr.gameObject.activeSelf || !mr.enabled || mr.sharedMaterials.Length <= 0) { continue; } if (SetTransparentAlpha(mr)) { continue; } //cutoff if (Util.ContainAnyTransparentOrCutOff(mr)) { continue; } MeshFilter mf = mr.GetComponent <MeshFilter>(); if (mf == null || mf.sharedMesh == null) { continue; } var meshRenderer = mr as MeshRenderer; _visibleSet.Add(meshRenderer); } // Debug.LogFormat("DisableInvisibleRenderers call, find potential meshrenderer count:{0} time:{1}", visibleSet.Count, System.DateTime.Now); // 替换为纯色shader _oldRenderMats.Clear(); _renderColors.Clear(); int maxKey = -int.MaxValue; //System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < _visibleSet.Count; i++) { MeshRenderer mr = _visibleSet[i]; if (mr == null || mr.sharedMaterials.Length <= 0) { continue; } _oldRenderMats.Add(mr, mr.sharedMaterials); Material mat = new Material(shader); Color32 color = _colorN.IntToColorN(i); mat.SetColor("_Color", color); Material[] mats = new Material[mr.sharedMaterials.Length]; for (int k = 0; k < mats.Length; k++) { mats[k] = mat; } mr.sharedMaterials = mats; //var key = (color.r << 16) | (color.g << 8) | color.b; var key = i; _renderColors.Add(key, mr); if (maxKey < key) { maxKey = key; } // Debug.LogFormat("{3} key {4} Set Color is {0} {1} {2}", color.r, color.g, color.b, mr.name, key); //sb.AppendLine(color.ToString()); } // Debug.LogFormat("DisableInvisibleRenderers call, replace color shader, count:{0} time:{1}", oldRenderMats.Count, System.DateTime.Now); //System.IO.File.WriteAllText(@"C:\Users\Myself\Desktop\writePixels.txt", sb.ToString()); // 关闭相机的可能的后效组件影响 _cameraComps.Clear(); var cs = cam.GetComponents <Component>(); foreach (Component c in cs) { if (c != null) { Transform tr = c as Transform; Camera ca = c as Camera; Behaviour beh = c as Behaviour; if (tr == null && ca == null && beh != null) { _cameraComps.Add(c, beh.enabled); beh.enabled = false; } } } _oldTarget = cam.targetTexture; _oldActive = RenderTexture.active; _oldCamFov = cam.fieldOfView; _oldAspect = cam.aspect; _oldNear = cam.nearClipPlane; _oldFar = cam.farClipPlane; _oldCullingMask = cam.cullingMask; _oldClearFlags = cam.clearFlags; _oldBackgroundColor = cam.backgroundColor; _oldRenderingPath = cam.renderingPath; if (Config.CameraRect) { _textureWidth = (int)Camera.main.pixelRect.width; _textureHeight = (int)Camera.main.pixelRect.height; } else { _textureWidth = Config.ScreenWidth; _textureHeight = Config.ScreenHeight; } if (_newTarget != null) { RenderTexture.ReleaseTemporary(_newTarget); } if (Config.UseComputeShader) { _newTarget = RenderTexture.GetTemporary(_textureWidth, _textureHeight, 16, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.sRGB); } else { _newTarget = RenderTexture.GetTemporary(_textureWidth, _textureHeight, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); } if (_dummyTarget != null) { RenderTexture.ReleaseTemporary(_dummyTarget); } _dummyTarget = RenderTexture.GetTemporary(_textureWidth, _textureHeight, 16, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.sRGB); _newTarget.autoGenerateMips = false; _newTarget.DiscardContents(); cam.targetTexture = _newTarget; if (Config.ChangeCameraFOV) { cam.fieldOfView = 90.0f; //cam.aspect = 1.0f; //cam.nearClipPlane = 0.01f; //cam.farClipPlane = 20000; } //cam.cullingMask &= ~UnityLayerManager.GetLayerMask(EUnityLayerName.UI); cam.clearFlags = CameraClearFlags.Color; cam.backgroundColor = Color.white; cam.renderingPath = RenderingPath.Forward; // Debug.LogFormat("MiniRenderer Prepare Sreen Width {0} Height {1} Aspect {2}", Screen.width, Screen.height, _oldAspect); if (Config.UseComputeShader) { if (_computeBuffer != null) { _computeBuffer.Dispose(); } if (_computeIndexBuffer != null) { _computeIndexBuffer.Dispose(); } if (_computeIndexLengthBuffer != null) { _computeIndexLengthBuffer.Dispose(); } if (maxKey < 0) { maxKey = 0; } maxKey += 1; Debug.LogFormat("batch mode MinRenderer Max Key {0}", maxKey); _computeBuffer = new ComputeBuffer(maxKey, sizeof(int)); _computeIndexBuffer = new ComputeBuffer(maxKey, sizeof(int)); _computeIndexLengthBuffer = new ComputeBuffer(1, sizeof(int)); _computeLengthData = new int[1]; _computeIndexData = new int[maxKey]; var computeShader = _computeShader; var prepareKernal = computeShader.FindKernel("OCVisPrepare"); computeShader.SetBuffer(prepareKernal, "OCResultBuffer", _computeBuffer); computeShader.SetBuffer(prepareKernal, "OCIndexBuffer", _computeIndexBuffer); computeShader.SetBuffer(prepareKernal, "OCIndexLengthBuffer", _computeIndexLengthBuffer); var computeKernal = computeShader.FindKernel("OCVisCompute"); computeShader.SetBuffer(computeKernal, "OCResultBuffer", _computeBuffer); computeShader.SetBuffer(computeKernal, "OCIndexBuffer", _computeIndexBuffer); computeShader.SetBuffer(computeKernal, "OCIndexLengthBuffer", _computeIndexLengthBuffer); computeShader.SetInt("BufferLength", _computeBuffer.count); computeShader.SetInt("Offset", _colorN.Offset); computeShader.SetInt("Alpha", _colorN.Alpha); computeShader.SetTexture(computeKernal, "OCTexture", _newTarget); } else { _texture = new Texture2D(_textureWidth, _textureHeight, TextureFormat.ARGB32, false); } }