// Pressure Chamber venue import for The_Pressure_Chamber (URP 17, Unity 6000.3). // Source: Desktop/Pressure Chamber Blender Files/Pressure_Chamber_v1.1.blend, exported by // "Desktop/Pressure Chamber Blender Files/Unity export/export_unity.py" (FBX + manifest). // // What this does (Editor only; never touches scenes you have open with unsaved changes): // * import settings for Assets/PressureChamber/Models/*.fbx (metres, no cameras/lights/animation, no axis bake) // * URP Lit materials from the manifest (flat approximations of the procedural Blender materials) remapped onto the FBX // * builds Assets/PressureChamber/Scenes/PressureChamber_Venue.unity in a separate additive scene: // venue model (static), collision proxies (MeshColliders, no renderers), the 193 venue preview/readability lights, // the 8 venue cameras (physical, CAM_03 is the main camera), flat dusk ambient, a scene volume (Neutral tonemapping + bloom) // * Blender -> Unity axis mapping is MEASURED from the _UnityAxisReference empties inside the FBX, not assumed // * writes Logs/PressureChamberImport/import_report.json (+ camera previews when the venue scene could be opened) // Auto-runs when a new export arrives (manifest exportId changes) ONLY if the generated scene is unmodified since the last // build (sha1 recorded in Logs/PressureChamberImport/last_build.json) and no open scene has unsaved changes; otherwise it logs // a warning and you use Tools > Pressure Chamber > Rebuild Venue Scene. #if UNITY_EDITOR using System; using System.Collections.Generic; using System.IO; using System.Linq; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.Universal; using UnityEngine.SceneManagement; namespace PressureChamber.EditorTools { [Serializable] public class MatSpec { public string name; public float[] baseColor; public float metallic; public float smoothness; public float[] emission; public bool emissive; public string note; } [Serializable] public class LightSpec { public string name; public string group; public string blenderType; public string unityType; public float[] pos; public float[] dir; public float[] up; public float[] color; public float intensity; public float range; public float spotAngle; public float innerSpotAngle; public bool shadows; public float blenderPower; } [Serializable] public class CamSpec { public string name; public float[] pos; public float[] dir; public float[] up; public float focalLength; public float sensorWidth; public float clipStart; public float clipEnd; public bool main; } [Serializable] public class CheckSpec { public string name; public float[] center; public float[] size; } [Serializable] public class Manifest { public int version; public string exportId; public string source; public string venueModel; public string collisionModel; public string axisReferenceRoot; public float axisReferenceLength; public float[] ambientColor; public float[] backgroundColor; public int expectedMeshObjects; public int expectedTriangles; public int expectedCollisionObjects; public MatSpec[] materials; public LightSpec[] lights; public CamSpec[] cameras; public CheckSpec[] checks; } [Serializable] class CheckResult { public string name; public float[] expectedUnityCenter; public float[] actualUnityCenter; public float errorMetres; public bool found; } [Serializable] class Report { public string status; public string time; public string scenePath; public bool sceneOpened; public string previewsSkippedReason; public string exportId; public int builderVersion; public float[] axisColumnX; public float[] axisColumnY; public float[] axisColumnZ; public float axisOrthoError; public float[] venueRootEuler; public float[] sampleMeshWorldEuler; public string upAxisCheck; public string floorRaycast; public int meshRenderers; public int expectedMeshObjects; public int triangles; public int expectedTriangles; public int collisionColliders; public int materialsCreated; public string[] fbxMaterialNames; public string[] unmatchedFbxMaterials; public string[] renderersWithoutManifestMaterial; public int lightsCreated; public int shadowedLights; public int camerasCreated; public string mainCamera; public List checks = new List(); public float maxCheckError; public List previews = new List(); public List warnings = new List(); } [Serializable] class LastBuild { public string exportId; public string sceneSha1; public int builderVersion; public string time; } public class PressureChamberModelPostprocessor : AssetPostprocessor { public override uint GetVersion() => 2; static void OnPostprocessAllAssets(string[] imported, string[] deleted, string[] moved, string[] movedFrom) { if (imported.Any(a => a.StartsWith(PressureChamberVenueBuilder.Root + "/Data/") || a.StartsWith(PressureChamberVenueBuilder.Root + "/Models/"))) PressureChamberVenueBuilder.ScheduleAutoCheck(); } void OnPreprocessModel() { if (!assetPath.StartsWith(PressureChamberVenueBuilder.Root + "/Models/")) return; var mi = (ModelImporter)assetImporter; bool collision = assetPath.Contains("Collision"); mi.globalScale = 1f; mi.useFileScale = true; mi.bakeAxisConversion = true; // FBX is Blender Z-up; bake the Y-up conversion (no root rotation) mi.importCameras = false; mi.importLights = false; mi.importVisibility = true; mi.importAnimation = false; mi.animationType = ModelImporterAnimationType.None; mi.importBlendShapes = false; mi.meshCompression = ModelImporterMeshCompression.Off; mi.importNormals = ModelImporterNormals.Import; mi.preserveHierarchy = true; mi.addCollider = false; mi.generateSecondaryUV = false; mi.isReadable = collision; mi.materialImportMode = collision ? ModelImporterMaterialImportMode.None : ModelImporterMaterialImportMode.ImportStandard; } } [InitializeOnLoad] public static class PressureChamberVenueBuilder { public const string Root = "Assets/PressureChamber"; const string ManifestPath = Root + "/Data/PressureChamber_venue_manifest.json"; const string ScenePath = Root + "/Scenes/PressureChamber_Venue.unity"; const string ProfilePath = Root + "/Settings/PressureChamber_Venue_Volume.asset"; const string ReportDir = "Logs/PressureChamberImport"; const string LastBuildPath = ReportDir + "/last_build.json"; public const int BuilderVersion = 2; static int waits; static bool scheduled; static bool building; static string failedExportId; static PressureChamberVenueBuilder() { ScheduleAutoCheck(); } public static void ScheduleAutoCheck() { if (scheduled || building) return; // the builder's own (re)imports must not re-trigger it scheduled = true; waits = 0; EditorApplication.delayCall += AutoCheck; } static string Sha1(string path) { using (var sha = System.Security.Cryptography.SHA1.Create()) return BitConverter.ToString(sha.ComputeHash(File.ReadAllBytes(path))).Replace("-", "").ToLowerInvariant(); } static void AutoCheck() { if (!File.Exists(ManifestPath)) { scheduled = false; return; } if (EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isCompiling || EditorApplication.isUpdating || AssetDatabase.LoadAssetAtPath(Root + "/Models/PressureChamber_Venue.fbx") == null) { if (++waits < 20000) EditorApplication.delayCall += AutoCheck; else scheduled = false; return; } scheduled = false; var man = LoadManifest(); if (failedExportId != null && failedExportId == (man.exportId ?? "")) return; // failed once this session: never auto-retry var last = File.Exists(LastBuildPath) ? JsonUtility.FromJson(File.ReadAllText(LastBuildPath)) : null; if (File.Exists(ScenePath)) { if (last != null && last.exportId == man.exportId && last.builderVersion == BuilderVersion) return; // up to date if (last == null || Sha1(ScenePath) != last.sceneSha1) { Debug.LogWarning("[PressureChamber] a new venue export is available but " + ScenePath + " was modified (or has no build record); " + "not overwriting it. Use Tools > Pressure Chamber > Rebuild Venue Scene."); return; } if (AnySceneDirty()) { Debug.LogWarning("[PressureChamber] a new venue export is available but an open scene has unsaved changes; " + "save them, then use Tools > Pressure Chamber > Rebuild Venue Scene."); return; } } Debug.Log("[PressureChamber] auto-building the venue scene for export " + man.exportId); Build(true); } static bool AnySceneDirty() { for (int i = 0; i < SceneManager.sceneCount; i++) if (SceneManager.GetSceneAt(i).isDirty) return true; return false; } [MenuItem("Tools/Pressure Chamber/Rebuild Venue Scene")] static void RebuildMenu() { if (File.Exists(ScenePath) && !EditorUtility.DisplayDialog("Rebuild venue scene", "This regenerates " + ScenePath + " and the PressureChamber materials from the manifest. Changes made inside that scene are lost.", "Rebuild", "Cancel")) return; if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo()) return; Build(true); } [MenuItem("Tools/Pressure Chamber/Render Venue Camera Previews")] static void PreviewMenu() { var r = new Report(); RenderPreviews(LoadManifest(), r); Debug.Log("[PressureChamber] previews: " + string.Join(", ", r.previews)); } static Manifest LoadManifest() => JsonUtility.FromJson(File.ReadAllText(ManifestPath)); static Color Lin(float[] c, float a = 1f) => new Color(c[0], c[1], c[2], a); static Vector3 V(float[] v) => new Vector3(v[0], v[1], v[2]); static float[] F(Vector3 v) => new[] { v.x, v.y, v.z }; static void EnsureFolder(string path) { if (AssetDatabase.IsValidFolder(path)) return; var parent = Path.GetDirectoryName(path).Replace('\\', '/'); EnsureFolder(parent); AssetDatabase.CreateFolder(parent, Path.GetFileName(path)); } public static void Build(bool openIfClean) { var rep = new Report { time = DateTime.Now.ToString("s"), scenePath = ScenePath, status = "FAILED", builderVersion = BuilderVersion }; Directory.CreateDirectory(ReportDir); building = true; try { BuildInner(openIfClean, rep); rep.status = rep.warnings.Count == 0 ? "OK" : "OK_WITH_WARNINGS"; } catch (Exception e) { rep.warnings.Add("EXCEPTION: " + e); Debug.LogException(e); } finally { building = false; failedExportId = rep.status == "FAILED" ? (rep.exportId ?? "") : null; File.WriteAllText(Path.Combine(ReportDir, "import_report.json"), JsonUtility.ToJson(rep, true)); if (rep.status != "FAILED" && File.Exists(ScenePath)) File.WriteAllText(LastBuildPath, JsonUtility.ToJson(new LastBuild { exportId = rep.exportId, sceneSha1 = Sha1(ScenePath), builderVersion = BuilderVersion, time = rep.time }, true)); Debug.Log("[PressureChamber] VENUE_BUILD_" + rep.status + " renderers=" + rep.meshRenderers + "/" + rep.expectedMeshObjects + " lights=" + rep.lightsCreated + " cameras=" + rep.camerasCreated + " maxCheckError=" + rep.maxCheckError.ToString("F3") + "m report=" + ReportDir + "/import_report.json"); } } static void BuildInner(bool openIfClean, Report rep) { var man = LoadManifest(); rep.exportId = man.exportId; foreach (var f in new[] { Root + "/Materials", Root + "/Scenes", Root + "/Settings" }) EnsureFolder(f); // ---------------------------------------------------------------- materials + remap var shader = Shader.Find("Universal Render Pipeline/Lit"); if (shader == null) throw new Exception("URP Lit shader not found"); var mats = new Dictionary(); foreach (var s in man.materials) { var path = Root + "/Materials/" + s.name + ".mat"; var m = AssetDatabase.LoadAssetAtPath(path); bool created = m == null; if (created) m = new Material(shader) { name = s.name }; else m.shader = shader; var bc = Lin(s.baseColor).gamma; m.SetColor("_BaseColor", bc); m.SetColor("_Color", bc); m.SetFloat("_Metallic", s.metallic); m.SetFloat("_Smoothness", s.smoothness); if (s.emissive) { m.EnableKeyword("_EMISSION"); m.SetColor("_EmissionColor", Lin(s.emission).gamma); m.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmissive; } else { m.DisableKeyword("_EMISSION"); m.SetColor("_EmissionColor", Color.black); m.globalIlluminationFlags = MaterialGlobalIlluminationFlags.EmissiveIsBlack; } if (created) AssetDatabase.CreateAsset(m, path); else EditorUtility.SetDirty(m); mats[s.name] = m; } AssetDatabase.SaveAssets(); rep.materialsCreated = mats.Count; // re-import both models so the import settings above are guaranteed to be applied AssetDatabase.ImportAsset(man.venueModel, ImportAssetOptions.ForceUpdate); AssetDatabase.ImportAsset(man.collisionModel, ImportAssetOptions.ForceUpdate); var venuePath = man.venueModel; var imp = (ModelImporter)AssetImporter.GetAtPath(venuePath); if (imp == null) throw new Exception("venue model not imported: " + venuePath); var fbxMatNames = new HashSet(); foreach (var r in AssetDatabase.LoadAssetAtPath(venuePath).GetComponentsInChildren(true)) foreach (var sm in r.sharedMaterials) if (sm != null) fbxMatNames.Add(sm.name); foreach (var kv in imp.GetExternalObjectMap()) if (kv.Key.type == typeof(Material)) fbxMatNames.Add(kv.Key.name); rep.fbxMaterialNames = fbxMatNames.OrderBy(x => x).ToArray(); rep.unmatchedFbxMaterials = fbxMatNames.Where(n => !mats.ContainsKey(n)).OrderBy(x => x).ToArray(); foreach (var kv in mats) imp.AddRemap(new AssetImporter.SourceAssetIdentifier(typeof(Material), kv.Key), kv.Value); imp.SaveAndReimport(); var venueModel = AssetDatabase.LoadAssetAtPath(venuePath); var collisionModel = AssetDatabase.LoadAssetAtPath(man.collisionModel); // ---------------------------------------------------------------- volume profile var profile = AssetDatabase.LoadAssetAtPath(ProfilePath); if (profile == null) { profile = ScriptableObject.CreateInstance(); AssetDatabase.CreateAsset(profile, ProfilePath); } if (!profile.TryGet(out var tm)) { tm = profile.Add(true); AssetDatabase.AddObjectToAsset(tm, profile); } tm.mode.Override(TonemappingMode.Neutral); if (!profile.TryGet(out var bloom)) { bloom = profile.Add(true); AssetDatabase.AddObjectToAsset(bloom, profile); } bloom.threshold.Override(1.0f); bloom.intensity.Override(0.6f); bloom.scatter.Override(0.6f); EditorUtility.SetDirty(profile); AssetDatabase.SaveAssets(); // ---------------------------------------------------------------- build the scene // nothing unsaved open -> build in Single mode (replaces the open scenes, nothing is lost); // otherwise build additively next to the user's scenes, which requires the venue scene itself not to be open // and no untitled scene (Unity refuses additive scene creation while an untitled scene is unsaved) bool single = !AnySceneDirty(); if (!single) { var loadedVenue = SceneManager.GetSceneByPath(ScenePath); if (loadedVenue.IsValid() && loadedVenue.isLoaded) throw new Exception("the venue scene is open with unsaved changes; save or discard them first"); for (int i = 0; i < SceneManager.sceneCount; i++) if (string.IsNullOrEmpty(SceneManager.GetSceneAt(i).path)) throw new Exception("an untitled scene with unsaved changes is open; save it first"); } var previousActive = SceneManager.GetActiveScene(); var scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, single ? NewSceneMode.Single : NewSceneMode.Additive); if (!single) SceneManager.SetActiveScene(scene); bool saved = false; try { var venue = (GameObject)PrefabUtility.InstantiatePrefab(venueModel, scene); venue.name = "PressureChamber_Venue"; // axis mapping measured from the reference empties (Blender world -> Unity world) var refRoot = venue.GetComponentsInChildren(true).FirstOrDefault(t => t.name == man.axisReferenceRoot); if (refRoot == null) throw new Exception("axis reference empties missing in FBX"); Func refPos = n => refRoot.GetComponentsInChildren(true).First(t => t.name == n).position; var o = refPos("REF_O"); float L = man.axisReferenceLength; var cx = (refPos("REF_X") - o) / L; var cy = (refPos("REF_Y") - o) / L; var cz = (refPos("REF_Z") - o) / L; rep.axisColumnX = F(cx); rep.axisColumnY = F(cy); rep.axisColumnZ = F(cz); rep.axisOrthoError = Mathf.Max(Mathf.Abs(cx.magnitude - 1), Mathf.Abs(cy.magnitude - 1), Mathf.Abs(cz.magnitude - 1), Mathf.Abs(Vector3.Dot(cx, cy)), Mathf.Abs(Vector3.Dot(cy, cz)), Mathf.Abs(Vector3.Dot(cx, cz)), o.magnitude / L); if (rep.axisOrthoError > 1e-3f) rep.warnings.Add("axis reference not orthonormal / offset: " + rep.axisOrthoError); Func P = b => o + cx * b[0] + cy * b[1] + cz * b[2]; Func D = b => (cx * b[0] + cy * b[1] + cz * b[2]).normalized; refRoot.gameObject.SetActive(false); // Blender +Z (up) must be Unity +Y, and the import must not leave a rotation on the root rep.venueRootEuler = F(venue.transform.localEulerAngles); var sampleMesh = venue.GetComponentsInChildren(true).FirstOrDefault(r => r.name == "ST_DJ_Booth"); if (sampleMesh != null) rep.sampleMeshWorldEuler = F(sampleMesh.transform.eulerAngles); bool upOk = Vector3.Dot(cz, Vector3.up) > 0.9999f; rep.upAxisCheck = (upOk ? "OK" : "FAIL") + ": Blender +Z -> Unity " + cz.ToString("F4") + ", +Y (rear) -> " + cy.ToString("F4") + ", +X -> " + cx.ToString("F4"); if (!upOk) rep.warnings.Add("venue is not upright in Unity: " + rep.upAxisCheck); if (Quaternion.Angle(venue.transform.localRotation, Quaternion.identity) > 0.01f) rep.warnings.Add("venue root carries a rotation " + venue.transform.localEulerAngles); int renderers = 0; long tris = 0; var missing = new List(); foreach (var t in venue.GetComponentsInChildren(true)) { if (t == refRoot || t.IsChildOf(refRoot)) continue; var mr = t.GetComponent(); var mf = t.GetComponent(); if (mr == null || mf == null) continue; renderers++; if (mf.sharedMesh != null) tris += mf.sharedMesh.triangles.LongLength / 3; GameObjectUtility.SetStaticEditorFlags(t.gameObject, StaticEditorFlags.ContributeGI | StaticEditorFlags.BatchingStatic | StaticEditorFlags.OccluderStatic | StaticEditorFlags.OccludeeStatic | StaticEditorFlags.ReflectionProbeStatic); foreach (var sm in mr.sharedMaterials) if (sm == null || !mats.ContainsValue(sm)) { missing.Add(t.name); break; } } rep.meshRenderers = renderers; rep.triangles = (int)tris; rep.expectedMeshObjects = man.expectedMeshObjects; rep.expectedTriangles = man.expectedTriangles; rep.renderersWithoutManifestMaterial = missing.Take(50).ToArray(); if (renderers != man.expectedMeshObjects) rep.warnings.Add($"mesh renderers {renderers} != expected {man.expectedMeshObjects}"); if (missing.Count > 0) rep.warnings.Add(missing.Count + " renderers use a material not from the manifest"); // placement checks: Blender AABB centre mapped through the measured axes vs Unity renderer bounds foreach (var c in man.checks) { var cr = new CheckResult { name = c.name, expectedUnityCenter = F(P(c.center)) }; var t = venue.GetComponentsInChildren(true).FirstOrDefault(x => x.name == c.name); var r = t != null ? t.GetComponent() : null; if (r != null) { cr.found = true; cr.actualUnityCenter = F(r.bounds.center); cr.errorMetres = Vector3.Distance(r.bounds.center, P(c.center)); rep.maxCheckError = Mathf.Max(rep.maxCheckError, cr.errorMetres); } else rep.warnings.Add("check object not found: " + c.name); rep.checks.Add(cr); } if (rep.maxCheckError > 0.02f) rep.warnings.Add("placement check error " + rep.maxCheckError + " m"); // collision proxies: MeshColliders, renderers removed if (collisionModel != null) { var col = (GameObject)PrefabUtility.InstantiatePrefab(collisionModel, scene); PrefabUtility.UnpackPrefabInstance(col, PrefabUnpackMode.Completely, InteractionMode.AutomatedAction); col.name = "PressureChamber_Collision"; foreach (var mf in col.GetComponentsInChildren(true)) { var mc = mf.gameObject.AddComponent(); mc.sharedMesh = mf.sharedMesh; var mr = mf.GetComponent(); if (mr) UnityEngine.Object.DestroyImmediate(mr); UnityEngine.Object.DestroyImmediate(mf); rep.collisionColliders++; } if (rep.collisionColliders != man.expectedCollisionObjects) rep.warnings.Add("collision colliders " + rep.collisionColliders + " != " + man.expectedCollisionObjects); // gravity sanity: a ray cast straight down (Unity -Y) above the crowd floor centre must hit a proxy at about y = 0 Physics.SyncTransforms(); var ps = scene.GetPhysicsScene(); var from = P(new[] { 0f, -10f, 0f }) + Vector3.up * 30f; if (ps.Raycast(from, Vector3.down, out var hit, 100f)) { rep.floorRaycast = hit.collider.name + " at " + hit.point.ToString("F3"); if (Mathf.Abs(hit.point.y - P(new[] { 0f, -10f, 0f }).y) > 0.25f) rep.warnings.Add("floor raycast hit at unexpected height: " + rep.floorRaycast); } else rep.floorRaycast = "no hit (collision proxies do not cover the crowd floor centre)"; } else rep.warnings.Add("collision model not found"); // lights var lightsRoot = new GameObject("Venue Lights (Blender preview + readability)"); var groups = new Dictionary(); Light sun = null; foreach (var s in man.lights) { if (!groups.TryGetValue(s.group, out var g)) { g = new GameObject(s.group).transform; g.SetParent(lightsRoot.transform, false); groups[s.group] = g; } var go = new GameObject(s.name); go.transform.SetParent(g, false); go.transform.position = P(s.pos); var fwd = D(s.dir); var up = D(s.up); go.transform.rotation = Quaternion.LookRotation(fwd, up); var l = go.AddComponent(); l.type = s.unityType == "Directional" ? LightType.Directional : s.unityType == "Spot" ? LightType.Spot : LightType.Point; l.color = Lin(s.color).gamma; l.useColorTemperature = false; l.intensity = s.intensity; if (l.type != LightType.Directional) l.range = s.range; if (l.type == LightType.Spot) { l.spotAngle = s.spotAngle; l.innerSpotAngle = Mathf.Min(s.innerSpotAngle, s.spotAngle - 0.1f); } l.shadows = s.shadows ? LightShadows.Soft : LightShadows.None; l.lightmapBakeType = LightmapBakeType.Realtime; if (s.shadows && l.type != LightType.Directional) { var so = new SerializedObject(l.GetUniversalAdditionalLightData()); var tier = so.FindProperty("m_AdditionalLightsShadowResolutionTier"); if (tier != null) { tier.intValue = 0; so.ApplyModifiedPropertiesWithoutUndo(); } } if (l.type == LightType.Directional) sun = l; rep.lightsCreated++; if (s.shadows) rep.shadowedLights++; } // cameras var camRoot = new GameObject("Venue Cameras"); foreach (var s in man.cameras) { var go = new GameObject(s.name); go.transform.SetParent(camRoot.transform, false); go.transform.position = P(s.pos); go.transform.rotation = Quaternion.LookRotation(D(s.dir), D(s.up)); var cam = go.AddComponent(); cam.usePhysicalProperties = true; cam.sensorSize = new Vector2(s.sensorWidth, s.sensorWidth * 9f / 16f); cam.focalLength = s.focalLength; cam.gateFit = Camera.GateFitMode.Horizontal; cam.nearClipPlane = Mathf.Max(0.05f, s.clipStart); cam.farClipPlane = s.clipEnd; cam.clearFlags = CameraClearFlags.SolidColor; cam.backgroundColor = Lin(man.backgroundColor).gamma; var cd = cam.GetUniversalAdditionalCameraData(); cd.renderPostProcessing = true; cd.antialiasing = AntialiasingMode.SubpixelMorphologicalAntiAliasing; if (s.main) { go.tag = "MainCamera"; go.AddComponent(); rep.mainCamera = s.name; } else cam.enabled = false; rep.camerasCreated++; } // environment + volume RenderSettings.skybox = null; RenderSettings.ambientMode = AmbientMode.Flat; RenderSettings.ambientLight = Lin(man.ambientColor).gamma; RenderSettings.fog = false; if (sun != null) RenderSettings.sun = sun; var volGo = new GameObject("Venue Volume (Neutral tonemapping + bloom)"); var vol = volGo.AddComponent(); vol.isGlobal = true; vol.priority = 1; vol.sharedProfile = profile; if (!EditorSceneManager.SaveScene(scene, ScenePath)) throw new Exception("scene save failed: " + ScenePath); saved = true; } finally { if (!single) { if (previousActive.IsValid() && previousActive.isLoaded) SceneManager.SetActiveScene(previousActive); EditorSceneManager.CloseScene(scene, true); } else if (!saved) EditorSceneManager.NewScene(NewSceneSetup.EmptyScene, NewSceneMode.Single); // discard the partial build } AssetDatabase.SaveAssets(); // ---------------------------------------------------------------- open it if nothing unsaved would be lost, then render previews bool anyDirty = false; for (int i = 0; i < SceneManager.sceneCount; i++) anyDirty |= SceneManager.GetSceneAt(i).isDirty; if (openIfClean && !anyDirty && !EditorApplication.isPlayingOrWillChangePlaymode) { EditorSceneManager.OpenScene(ScenePath, OpenSceneMode.Single); rep.sceneOpened = true; RenderPreviews(man, rep); } else rep.previewsSkippedReason = anyDirty ? "an open scene has unsaved changes; venue scene saved but not opened" : "not requested"; } static void RenderPreviews(Manifest man, Report rep) { var dir = Path.Combine(ReportDir, "previews"); Directory.CreateDirectory(dir); bool async = ShaderUtil.allowAsyncCompilation; ShaderUtil.allowAsyncCompilation = false; try { foreach (var cam in UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.None)) { if (cam.transform.parent == null || cam.transform.parent.name != "Venue Cameras") continue; const int w = 1280, h = 720; var rt = new RenderTexture(w, h, 24, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB); rt.Create(); bool was = cam.enabled; cam.enabled = true; try { var req = new RenderPipeline.StandardRequest { destination = rt }; if (RenderPipeline.SupportsRenderRequest(cam, req)) RenderPipeline.SubmitRenderRequest(cam, req); else { cam.targetTexture = rt; cam.Render(); cam.targetTexture = null; } } finally { cam.enabled = was; } var prev = RenderTexture.active; RenderTexture.active = rt; var tex = new Texture2D(w, h, TextureFormat.RGB24, false); tex.ReadPixels(new Rect(0, 0, w, h), 0, 0); tex.Apply(); RenderTexture.active = prev; var file = Path.Combine(dir, cam.name + ".png"); File.WriteAllBytes(file, tex.EncodeToPNG()); UnityEngine.Object.DestroyImmediate(tex); rt.Release(); UnityEngine.Object.DestroyImmediate(rt); rep.previews.Add(file); } } catch (Exception e) { rep.warnings.Add("preview render failed: " + e.Message); } finally { ShaderUtil.allowAsyncCompilation = async; } var s = SceneManager.GetActiveScene(); if (s.path == ScenePath && s.isDirty) EditorSceneManager.SaveScene(s); } } } #endif