Example #1
0
        /// <summary>
        /// Construct a new stage to let your object live.
        /// A stage is a scene with visibility isolation.
        /// </summary>
        /// <param name="sceneName">Name of the scene used.</param>
        public Stage(string sceneName)
        {
            if (string.IsNullOrEmpty(sceneName))
            {
                throw new System.ArgumentNullException("sceneName");
            }

            m_PreviewScene      = EditorSceneManager.NewPreviewScene();
            m_PreviewScene.name = sceneName;

            var camGO = EditorUtility.CreateGameObjectWithHideFlags("Look Dev Camera", HideFlags.HideAndDontSave, typeof(Camera));

            MoveIntoStage(camGO, true); //position will be updated right before rendering
            camGO.layer = k_PreviewCullingLayerIndex;

            m_Camera                     = camGO.GetComponent <Camera>();
            m_Camera.cameraType          = CameraType.Game; //cannot be preview in HDRP: too many things skiped
            m_Camera.enabled             = false;
            m_Camera.clearFlags          = CameraClearFlags.Depth;
            m_Camera.cullingMask         = 1 << k_PreviewCullingLayerIndex;
            m_Camera.renderingPath       = RenderingPath.DeferredShading;
            m_Camera.useOcclusionCulling = false;
            m_Camera.scene               = m_PreviewScene;

            var lightGO = EditorUtility.CreateGameObjectWithHideFlags("Look Dev Sun", HideFlags.HideAndDontSave, typeof(Light));

            MoveIntoStage(lightGO, true); //position will be updated right before rendering
            m_SunLight           = lightGO.GetComponent <Light>();
            m_SunLight.type      = LightType.Directional;
            m_SunLight.shadows   = LightShadows.Soft;
            m_SunLight.intensity = 0f;
        }
Example #2
0
        /// <summary>
        /// Construct a new stage to let your object live.
        /// A stage is a scene with visibility isolation.
        /// </summary>
        /// <param name="sceneName">Name of the scene used.</param>
        public Stage(string sceneName)
        {
            if (string.IsNullOrEmpty(sceneName))
            {
                throw new System.ArgumentNullException("sceneName");
            }

            m_PreviewScene      = EditorSceneManager.NewPreviewScene();
            m_PreviewScene.name = sceneName;

            var camGO = EditorUtility.CreateGameObjectWithHideFlags("Look Dev Camera", HideFlags.HideAndDontSave, typeof(Camera));

            MoveIntoStage(camGO, new Vector3(0, 0, -6), Quaternion.identity, true);
            camGO.layer = k_PreviewCullingLayerIndex;

            m_Camera                     = camGO.GetComponent <Camera>();
            m_Camera.cameraType          = CameraType.Game; //cannot be preview in HDRP: too many things skiped
            m_Camera.enabled             = false;
            m_Camera.clearFlags          = CameraClearFlags.Depth;
            m_Camera.fieldOfView         = 90;
            m_Camera.farClipPlane        = 10.0f;
            m_Camera.nearClipPlane       = 2.0f;
            m_Camera.cullingMask         = 1 << k_PreviewCullingLayerIndex;
            m_Camera.renderingPath       = RenderingPath.DeferredShading;
            m_Camera.useOcclusionCulling = false;
            m_Camera.scene               = m_PreviewScene;
        }
Example #3
0
    private void Initialize(BlockType type)
    {
        if (previewRenderUtility != null)
        {
            return;
        }

        previewScene         = EditorSceneManager.NewPreviewScene();
        previewRenderUtility = new PreviewRenderUtility(false);

        previewRenderUtility.camera.transform.position = new Vector3(5, 5, 5);
        previewRenderUtility.camera.transform.LookAt(Vector3.zero, Vector3.up);
        previewRenderUtility.camera.scene = previewScene;

        previewRendererObject = EditorUtility.CreateGameObjectWithHideFlags(
            "Preview Object",
            HideFlags.HideAndDontSave,
            components
            );
        SceneManager.MoveGameObjectToScene(previewRendererObject, previewScene);
        targetMeshFilter   = previewRendererObject.GetComponent <MeshFilter>();
        targetMeshRenderer = previewRendererObject.GetComponent <MeshRenderer>();
        previewRendererObject.transform.position = -Voxel.Center;

        InitializeLighting(previewRenderUtility);

        ReloadMesh(previewRendererObject, type);
    }
        public PreviewScene(string sceneName)
        {
            m_Scene = EditorSceneManager.NewPreviewScene();
            if (!m_Scene.IsValid())
            {
                throw new InvalidOperationException("Preview scene could not be created");
            }

            m_Scene.name = sceneName;

            var camGO = EditorUtility.CreateGameObjectWithHideFlags("Preview Scene Camera", HideFlags.HideAndDontSave, typeof(Camera));

            AddGameObject(camGO);
            m_Camera             = camGO.GetComponent <Camera>();
            camera.cameraType    = CameraType.Preview;
            camera.enabled       = false;
            camera.clearFlags    = CameraClearFlags.Depth;
            camera.fieldOfView   = 15;
            camera.farClipPlane  = 10.0f;
            camera.nearClipPlane = 2.0f;

            // Explicitly use forward rendering for all previews
            // (deferred fails when generating some static previews at editor launch; and we never want
            // vertex lit previews if that is chosen in the player settings)
            camera.renderingPath       = RenderingPath.Forward;
            camera.useOcclusionCulling = false;
            camera.scene = m_Scene;
        }
Example #5
0
    protected override void OnUpdate()
    {
        Entities.WithNone <EditorCompanionInPreviewSceneTag>().ForEach((EditorRenderData renderData, CompanionLink link) =>
        {
            foreach (var sceneAndMask in m_CompanionScenes)
            {
                if (sceneAndMask.mask == renderData.SceneCullingMask)
                {
                    EditorSceneManager.MoveGameObjectToScene(link.Companion, sceneAndMask.scene);
                    return;
                }
            }

            var scene = EditorSceneManager.NewPreviewScene();

            m_CompanionScenes.Add(new SceneAndMask
            {
                scene = scene,
                mask  = renderData.SceneCullingMask
            });

            EditorSceneManager.SetSceneCullingMask(scene, renderData.SceneCullingMask);
            EditorSceneManager.MoveGameObjectToScene(link.Companion, scene);
        });

        EntityManager.AddComponent <EditorCompanionInPreviewSceneTag>(m_WithoutTag);
    }
Example #6
0
        static void EditUI()
        {
            var preview_scene = EditorSceneManager.NewPreviewScene();

            //EditorSceneManager.SetActiveScene(preview_scene);
            PrefabUtility.LoadPrefabContentsIntoPreviewScene(AssetDatabase.GetAssetPath(Selection.activeInstanceID), preview_scene);
            //EditorSceneManager.NewScene( NewSceneSetup.EmptyScene, NewSceneMode.Single);
            //PrefabUtility.InstantiatePrefab(Selection.activeGameObject);
        }
Example #7
0
    public static RenderTexture Render(GameObject gameObject, int resolution)
    {
        if (threePointLight == null)
        {
            threePointLight = Resources.Load <GameObject>("Prefabs/ThreePointLights");
        }

        //calculate object bounds
        Bounds bounds = new Bounds();

        foreach (MeshRenderer renderer in gameObject.GetComponentsInChildren <MeshRenderer>())
        {
            bounds.Encapsulate(renderer.bounds);
        }

        var renderScene = EditorSceneManager.NewPreviewScene();

        GameObject parent = new GameObject("Scene Parent");

        GameObject instance = GameObjectFactory.Instantiate(gameObject, parent: parent.transform);

        GameObject cameraGameObject = GameObjectFactory.Create("Camera", parent: parent.transform);

        var camera = cameraGameObject.AddComponent <Camera>();

        camera.clearFlags             = CameraClearFlags.Nothing;
        camera.forceIntoRenderTexture = true;

        cameraGameObject.transform.position  = bounds.center + Vector3.right + Vector3.forward + Vector3.up;
        cameraGameObject.transform.position *= Mathf.Max(bounds.extents.x, bounds.extents.y, bounds.extents.z) * 1.2f;
        cameraGameObject.transform.rotation  = Quaternion.Euler(0, 225, 0) * Quaternion.Euler(45f, 0, 0);

        RenderTexture texture = new RenderTexture(resolution, resolution, 16);

        texture.Create();

        camera.targetTexture = texture;
        camera.scene         = renderScene;

        GameObject lightGameObject = GameObjectFactory.Instantiate(threePointLight, parent: parent.transform);
        var        light           = lightGameObject.AddComponent <Light>();

        light.type = LightType.Directional;
        light.transform.rotation = Quaternion.Euler(50f, -30f, 0f);

        EditorSceneManager.MoveGameObjectToScene(parent, renderScene);

        camera.Render();
        camera.targetTexture = null;

        GameObject.DestroyImmediate(parent);

        EditorSceneManager.UnloadSceneAsync(renderScene);

        return(texture);
    }
Example #8
0
 private Scene GetTempScene()
 {
     if (_tempScene == null)
     {
         _tempScene = EditorSceneManager.NewPreviewScene();
         var root = new GameObject("VideoPlayer");
         EditorSceneManager.MoveGameObjectToScene(root, _tempScene);
     }
     return(_tempScene);
 }
Example #9
0
            internal SimulationScene()
            {
                // When not in play mode, use a preview scene for simulation
                var isPlaying = EditorApplication.isPlayingOrWillChangePlaymode;

                if (isPlaying)
                {
                    contentScene = SceneManager.CreateScene(k_SimulatedContentSceneName);
                }
                else
                {
                    var previewScene = EditorSceneManager.NewPreviewScene();
                    previewScene.name = k_SimulatedContentSceneName;
                    contentScene      = previewScene;
                }

                if (!contentScene.IsValid())
                {
                    throw new InvalidOperationException("Content scene could not be created");
                }

                contentRoot = new GameObject("Simulated Content Root");
                SceneManager.MoveGameObjectToScene(contentRoot, contentScene);

                if (isPlaying)
                {
                    environmentScene = SceneManager.CreateScene(k_SimulatedEnvironmentSceneName, k_EnvironmentSceneParameters);
                }
                else if (useFallbackRendering)
                {
                    environmentScene = contentScene;
                }
                else
                {
                    var previewScene = EditorSceneManager.NewPreviewScene();
                    previewScene.name = k_SimulatedEnvironmentSceneName;
                    environmentScene  = previewScene;
                }

                if (!environmentScene.IsValid())
                {
                    throw new InvalidOperationException("Environment scene could not be created");
                }

                environmentRoot = new GameObject("Simulated Environment Root");
                SceneManager.MoveGameObjectToScene(environmentRoot, environmentScene);

                EditorOnlyDelegates.GetAllSimulationSceneCameras = GetAllSimulationSceneCameras;
            }
        static Scene CreateDefaultPreviewScene()
        {
            Scene previewScene = EditorSceneManager.NewPreviewScene();

            Unsupported.SetOverrideRenderSettings(previewScene);

            // Setup default render settings for this preview scene
            UnityEngine.RenderSettings.defaultReflectionMode = UnityEngine.Rendering.DefaultReflectionMode.Custom;
            UnityEngine.RenderSettings.customReflection      = GetDefaultReflection(); // ensure chrome materials do not render balck
            UnityEngine.RenderSettings.skybox      = null;                             // do not use skybox for the default previewscene, we want the flat Prefab Mode background color to let it stand out from normal scenes
            UnityEngine.RenderSettings.ambientMode = AmbientMode.Trilight;             // do not use skybox ambient but simple trilight ambient for simplicity
            Unsupported.RestoreOverrideRenderSettings();

            return(previewScene);
        }
        static Scene CreateDefaultPreviewScene()
        {
            Scene previewScene = EditorSceneManager.NewPreviewScene();

            // Setup default render settings for this preview scene
            Unsupported.SetOverrideLightingSettings(previewScene);
            UnityEngine.RenderSettings.defaultReflectionMode = UnityEngine.Rendering.DefaultReflectionMode.Custom;
            UnityEngine.RenderSettings.customReflection      = GetDefaultReflection(); // ensure chrome materials do not render black
            UnityEngine.RenderSettings.skybox      = AssetDatabase.GetBuiltinExtraResource <Material>("Default-Skybox.mat") as Material;
            UnityEngine.RenderSettings.ambientMode = AmbientMode.Skybox;
            UnityEditorInternal.InternalEditorUtility.CalculateAmbientProbeFromSkybox();
            Unsupported.RestoreOverrideLightingSettings();

            return(previewScene);
        }
Example #12
0
    private void OnEnable()
    {
        line_style = new GUIStyle();
        line_style.normal.background = EditorGUIUtility.Load("icons/d_AvatarBlendBackground.png") as Texture2D;

        if (!scene_loaded)
        {
            sound_scene = EditorSceneManager.NewPreviewScene();

            sound_object = new GameObject("Sound Test Object", typeof(AudioSource)).GetComponent <AudioSource>();

            SceneManager.MoveGameObjectToScene(sound_object.gameObject, sound_scene);

            scene_loaded = true;
        }
    }
Example #13
0
        internal bool LoadStage(string prefabPath)
        {
            if (initialized)
            {
                Cleanup();
            }

            m_PrefabAssetPath = prefabPath;

            // Tempoary scene used while loading the prefab
            m_PreviewScene = EditorSceneManager.NewPreviewScene();

            // The user can have OnEnable and other callbacks called during LoadPrefabIntoPreviewScene (if they use ExecuteInEditMode or ExecuteAlways)
            // where they might request the current the prefabstage, so we ensure m_PreviewScene have been setup so they can check this stage's scene.
            m_PrefabContentsRoot = PrefabStageUtility.LoadPrefabIntoPreviewScene(prefabAssetPath, m_PreviewScene);

            if (m_PrefabContentsRoot != null)
            {
                // Create the environment scene and move the prefab root to this scene to ensure the correct rendersettings (skybox etc) are used in Prefab Mode.
                string environmentEditingScenePath = PrefabStageUtility.GetEnvironmentScenePathForPrefab(m_PrefabContentsRoot);
                Scene  environmentScene            = PrefabStageUtility.CreatePreviewScene(environmentEditingScenePath);
                environmentScene.name = m_PrefabContentsRoot.name;
                SceneManager.MoveGameObjectToScene(m_PrefabContentsRoot, environmentScene);
                if (!PrefabStageUtility.HandleAutoReparenting(m_PrefabContentsRoot, environmentScene))
                {
                    m_PrefabContentsRoot.transform.SetAsFirstSibling();
                }

                // Close the temporary prefab loading scene and set the environment scene as the scene of the stage
                EditorSceneManager.ClosePreviewScene(m_PreviewScene);
                m_PreviewScene = environmentScene;

                m_PrefabFileIcon      = DeterminePrefabFileIconFromInstanceRootGameObject();
                m_InitialSceneDirtyID = m_PreviewScene.dirtyID;
                UpdateEnvironmentHideFlags();
            }
            else
            {
                // Invalid setup
                Cleanup();
            }

            return(initialized);
        }
Example #14
0
        //Called when MainWindow is opened
        public void CreateScene()
        {
            //Scene
            scene      = EditorSceneManager.NewPreviewScene();
            scene.name = "Noise Perspective";

            //Culling mask
            ulong cullingMask = EditorSceneManager.CalculateAvailableSceneCullingMask();

            EditorSceneManager.SetSceneCullingMask(scene, cullingMask); //Prevents running out of culling masks if editor is reopened several times

            //Light
            GameObject lightGo = new GameObject();

            sceneLight      = lightGo.AddComponent <Light>();
            sceneLight.type = LightType.Directional;
            EditorSceneManager.MoveGameObjectToScene(lightGo, scene);
            lightGo.transform.position = lightGo.transform.up * 10;
            lightGo.transform.rotation = Quaternion.Euler(60, 0, 0);
            sceneLight.shadows         = LightShadows.None;
        }
        static void CreateScene(out Scene scene, out Camera camera)
        {
            scene = SceneManager.GetSceneByName(k_SceneName);
            if (!scene.IsValid())
            {
                scene = EditorSceneManager.NewPreviewScene();
            }

            //Cleanup
            var roots = scene.GetRootGameObjects();

            for (int i = roots.Length - 1; i >= 0; --i)
            {
                Object.DestroyImmediate(roots[i]);
            }

            camera         = EditorUtility.CreateGameObjectWithHideFlags("Camera", HideFlags.HideAndDontSave).AddComponent <Camera>();
            camera.enabled = false;
            SetupCamera(camera, scene);
            SceneManager.MoveGameObjectToScene(camera.gameObject, scene);
        }
Example #16
0
        public PreviewScene(string sceneName)
        {
            this.m_Scene      = EditorSceneManager.NewPreviewScene();
            this.m_Scene.name = sceneName;
            GameObject gameObject = EditorUtility.CreateGameObjectWithHideFlags("Preview Scene Camera", HideFlags.HideAndDontSave, new Type[]
            {
                typeof(Camera)
            });

            this.AddGameObject(gameObject);
            this.m_Camera                   = gameObject.GetComponent <Camera>();
            this.camera.cameraType          = CameraType.Preview;
            this.camera.enabled             = false;
            this.camera.clearFlags          = CameraClearFlags.Depth;
            this.camera.fieldOfView         = 15f;
            this.camera.farClipPlane        = 10f;
            this.camera.nearClipPlane       = 2f;
            this.camera.renderingPath       = RenderingPath.Forward;
            this.camera.useOcclusionCulling = false;
            this.camera.scene               = this.m_Scene;
        }
Example #17
0
        public AvatarMonitorField()
        {
            this.monitorSize = 0;
            this.textureMat  = CreateGammaMaterial();

            this.mainOrthographicSize = defaultOrthographicSize;
            this.subOrthographicSize  = 0f;

            scene = EditorSceneManager.NewPreviewScene();

            cameraObj = CreateCameraObj();
            AddGameObject(cameraObj);
            SetAvatarCamBgColor(Color.black);

            lightObj = CreateLightObj();
            AddGameObject(lightObj);

            viewPositionObj      = GameObject.CreatePrimitive(PrimitiveType.Sphere);
            viewPositionObj.name = "ViewPosition";
            viewPositionObj.transform.localScale = Vector3.one * 0.03f;
            AddGameObject(viewPositionObj);
            viewPositionObj.SetActive(false);
        }
Example #18
0
        static RuntimePreviewGenerator()
        {
            m_Scene = EditorSceneManager.NewPreviewScene();

            var Light0 = CreateLight();

            Light0.transform.rotation = Quaternion.Euler(70, 180, 0);
            Light0.color     = new Color(1.0f, 0.95f, 0.9f);
            Light0.intensity = 1.15f;

            var Light1 = CreateLight();

            Light1.transform.rotation = Quaternion.Euler(340, 218, 177);
            Light1.color     = new Color(.4f, .4f, .45f, 0f) * .7f;
            Light1.intensity = 1;

            PreviewRenderCamera   = null;
            PreviewDirection      = new Vector3(-1f, -1f, -1f);
            Padding               = 0f;
            BackgroundColor       = new Color(0.3f, 0.3f, 0.3f, 1f);
            OrthographicMode      = false;
            TransparentBackground = false;
        }
Example #19
0
        internal bool LoadStage(string prefabPath)
        {
            if (initialized)
            {
                Cleanup();
            }

            m_PrefabAssetPath = prefabPath;

            // Tempoary scene used while loading the prefab
            m_PreviewScene = EditorSceneManager.NewPreviewScene();

            // The user can have OnEnable and other callbacks called during LoadPrefabIntoPreviewScene (if they use ExecuteInEditMode or ExecuteAlways)
            // where they might request the current the prefabstage, so we ensure m_PreviewScene have been setup so they can check this stage's scene.
            m_PrefabContentsRoot = PrefabStageUtility.LoadPrefabIntoPreviewScene(prefabAssetPath, m_PreviewScene);

            if (m_PrefabContentsRoot != null)
            {
                Scene environmentScene = PrefabStageUtility.MovePrefabRootToEnvironmentScene(m_PrefabContentsRoot);

                // Close the temporary prefab loading scene and set the environment scene as the scene of the stage
                EditorSceneManager.ClosePreviewScene(m_PreviewScene);
                m_PreviewScene = environmentScene;

                m_PrefabFileIcon      = DeterminePrefabFileIconFromInstanceRootGameObject();
                m_InitialSceneDirtyID = m_PreviewScene.dirtyID;
                UpdateEnvironmentHideFlags();
            }
            else
            {
                // Invalid setup
                Cleanup();
            }

            return(initialized);
        }
        public PreviewSceneResources()
        {
            m_Scene = EditorSceneManager.NewPreviewScene();
            var camGO = EditorUtility.CreateGameObjectWithHideFlags("Preview Scene Camera", HideFlags.HideAndDontSave, typeof(Camera));

            SceneManager.MoveGameObjectToScene(camGO, m_Scene);

            m_Camera = camGO.GetComponent <Camera>();
            EditorUtility.SetCameraAnimateMaterials(camera, true);

            camera.cameraType      = CameraType.Preview;
            camera.enabled         = false;
            camera.clearFlags      = CameraClearFlags.Depth;
            camera.fieldOfView     = 15;
            camera.farClipPlane    = 10.0f;
            camera.nearClipPlane   = 2.0f;
            camera.backgroundColor = new Color(49.0f / 255.0f, 49.0f / 255.0f, 49.0f / 255.0f, 1.0f);

            // Explicitly use forward rendering for all previews
            // (deferred fails when generating some static previews at editor launch; and we never want
            // vertex lit previews if that is chosen in the player settings)
            camera.renderingPath       = RenderingPath.Forward;
            camera.useOcclusionCulling = false;
            camera.scene = m_Scene;

            var l0 = CreateLight();

            SceneManager.MoveGameObjectToScene(l0, m_Scene);

            //previewScene.AddGameObject(l0);
            light0 = l0.GetComponent <Light>();

            var l1 = CreateLight();

            SceneManager.MoveGameObjectToScene(l1, m_Scene);

            //previewScene.AddGameObject(l1);
            light1 = l1.GetComponent <Light>();

            light0.color = new Color(0.769f, 0.769f, 0.769f, 1); // SceneView.kSceneViewFrontLight
            light1.transform.rotation = Quaternion.Euler(340, 218, 177);
            light1.color = new Color(.4f, .4f, .45f, 0f) * .7f;

            m_CheckerboardMaterial         = new Material(Shader.Find("Hidden/Checkerboard"));
            checkerboardMaterial.hideFlags = HideFlags.HideAndDontSave;

            if (s_Meshes[0] == null)
            {
                var handleGo = (GameObject)EditorGUIUtility.LoadRequired("Previews/PreviewMaterials.fbx");

                // @TODO: temp workaround to make it not render in the scene
                handleGo.SetActive(false);
                foreach (Transform t in handleGo.transform)
                {
                    var meshFilter = t.GetComponent <MeshFilter>();
                    switch (t.name)
                    {
                    case "sphere":
                        s_Meshes[0] = meshFilter.sharedMesh;
                        break;

                    case "cube":
                        s_Meshes[1] = meshFilter.sharedMesh;
                        break;

                    case "cylinder":
                        s_Meshes[2] = meshFilter.sharedMesh;
                        break;

                    case "torus":
                        s_Meshes[3] = meshFilter.sharedMesh;
                        break;

                    default:
                        Debug.LogWarning("Something is wrong, weird object found: " + t.name);
                        break;
                    }
                }

                s_MeshIcons[0] = EditorGUIUtility.IconContent("PreMatSphere");
                s_MeshIcons[1] = EditorGUIUtility.IconContent("PreMatCube");
                s_MeshIcons[2] = EditorGUIUtility.IconContent("PreMatCylinder");
                s_MeshIcons[3] = EditorGUIUtility.IconContent("PreMatTorus");
                s_MeshIcons[4] = EditorGUIUtility.IconContent("PreMatQuad");

                s_LightIcons[0] = EditorGUIUtility.IconContent("PreMatLight0");
                s_LightIcons[1] = EditorGUIUtility.IconContent("PreMatLight1");

                s_TimeIcons[0] = EditorGUIUtility.IconContent("PlayButton");
                s_TimeIcons[1] = EditorGUIUtility.IconContent("PauseButton");

                Mesh quadMesh = Resources.GetBuiltinResource(typeof(Mesh), "Quad.fbx") as Mesh;
                s_Meshes[4] = quadMesh;
            }

            if (s_Quad == null)
            {
                var vertices = new[]
                {
                    new Vector3(-1f, -1f, 0f),
                    new Vector3(1f, 1f, 0f),
                    new Vector3(1f, -1f, 0f),
                    new Vector3(-1f, 1f, 0f)
                };

                var uvs = new[]
                {
                    new Vector2(0f, 0f),
                    new Vector2(1f, 1f),
                    new Vector2(1f, 0f),
                    new Vector2(0f, 1f)
                };

                var indices = new[] { 0, 1, 2, 1, 0, 3 };

                s_Quad = new Mesh
                {
                    vertices  = vertices,
                    uv        = uvs,
                    triangles = indices
                };
                s_Quad.RecalculateNormals();
                s_Quad.RecalculateBounds();
            }
        }
        static void GenerateVoxelGrids(GameObject prefabRoot, PlaneVoxelGenerationParams voxelGenerationParams, VoxelPlaneFindingParams planeFindingParams)
        {
            // Rather than modifying collider properties and risking corrupting the scene, for each object with a mesh
            // we create a game object with a collider that uses that mesh and add that object to a preview scene.
            var tempPreviewScene = EditorSceneManager.NewPreviewScene();
            var tempPhysicsScene = tempPreviewScene.GetPhysicsScene();

            // k_MeshFilters is cleared by GetComponentsInChildren
            prefabRoot.GetComponentsInChildren(k_MeshFilters);
            var meshesRoot = new GameObject("Meshes").transform;

            k_MeshColliders.Clear();
            foreach (var meshFilter in k_MeshFilters)
            {
                // Ignore synth planes
                if (meshFilter.GetComponent <SynthesizedPlane>())
                {
                    continue;
                }

                var meshCopyTrans    = new GameObject(string.Format("{0} (Mesh)", meshFilter.gameObject.name)).transform;
                var meshCopyCollider = meshCopyTrans.gameObject.AddComponent <MeshCollider>();
                k_MeshColliders.Add(meshCopyCollider);
                meshCopyCollider.sharedMesh = meshFilter.sharedMesh;
                meshCopyTrans.SetParent(meshesRoot);
                var meshFilterTrans = meshFilter.transform;
                meshCopyTrans.position   = meshFilterTrans.position;
                meshCopyTrans.rotation   = meshFilterTrans.rotation;
                meshCopyTrans.localScale = meshFilterTrans.lossyScale;
            }

            SceneManager.MoveGameObjectToScene(meshesRoot.gameObject, tempPreviewScene);

            var sceneBounds    = BoundsUtils.GetBounds(k_MeshColliders);
            var sceneBoundsMin = sceneBounds.min;
            var sceneBoundsMax = sceneBounds.max;

            // Make mesh colliders convex so that we can use CheckSphere to make sure our
            // raycasts don't originate within meshes.
            foreach (var meshCollider in k_MeshColliders)
            {
                meshCollider.convex = true;
            }

            // Seed the random number generator so that results are deterministic
            Random.InitState(voxelGenerationParams.raycastSeed);

            // Setup all ray origins before raycasting since we need mesh colliders to be convex for this step
            // but concave for the raycasting.
            var raycastCount = voxelGenerationParams.raycastCount;

            k_RayOrigins.Clear();
            k_RayOrigins.Capacity = raycastCount;
            for (var i = 0; i < raycastCount; i++)
            {
                var     rayGenerationAttempts = 0;
                Vector3 origin;
                while (true)
                {
                    origin = new Vector3(
                        Random.Range(sceneBoundsMin.x, sceneBoundsMax.x),
                        Random.Range(sceneBoundsMin.y, sceneBoundsMax.y),
                        Random.Range(sceneBoundsMin.z, sceneBoundsMax.z));

                    // If the randomly generated ray origin lies inside a mesh, try again
                    if (tempPhysicsScene.OverlapSphere(origin, k_CheckSphereRadius, k_Colliders,
                                                       Physics.DefaultRaycastLayers, QueryTriggerInteraction.Collide) == 0)
                    {
                        break;
                    }

                    rayGenerationAttempts++;
                    if (rayGenerationAttempts >= k_MaxRayGenerationRetries)
                    {
                        break;
                    }
                }

                k_RayOrigins.Add(origin);
            }

            foreach (var meshCollider in k_MeshColliders)
            {
                // Make mesh colliders concave for more useful raycast results
                meshCollider.convex = false;
            }

            k_UpGridPoints.Clear();
            k_DownGridPoints.Clear();
            k_ForwardGridPoints.Clear();
            k_BackGridPoints.Clear();
            k_RightGridPoints.Clear();
            k_LeftGridPoints.Clear();

            var outerPointsThreshold = voxelGenerationParams.outerPointsThreshold;
            var upGridBounds         = sceneBounds;
            var upGridMax            = upGridBounds.max;

            upGridMax.y     -= Mathf.Min(outerPointsThreshold, upGridBounds.size.y);
            upGridBounds.max = upGridMax;

            var downGridBounds = sceneBounds;
            var downGridMin    = downGridBounds.min;

            downGridMin.y     += Mathf.Min(outerPointsThreshold, downGridBounds.size.y);
            downGridBounds.min = downGridMin;

            var forwardGridBounds = sceneBounds;
            var forwardGridMax    = forwardGridBounds.max;

            forwardGridMax.z     -= Mathf.Min(outerPointsThreshold, forwardGridBounds.size.z);
            forwardGridBounds.max = forwardGridMax;

            var backGridBounds = sceneBounds;
            var backGridMin    = backGridBounds.min;

            backGridMin.z     += Mathf.Min(outerPointsThreshold, backGridBounds.size.z);
            backGridBounds.min = backGridMin;

            var rightGridBounds = sceneBounds;
            var rightGridMax    = rightGridBounds.max;

            rightGridMax.x     -= Mathf.Min(outerPointsThreshold, rightGridBounds.size.x);
            rightGridBounds.max = rightGridMax;

            var leftGridBounds = sceneBounds;
            var leftGridMin    = leftGridBounds.min;

            leftGridMin.x     += Mathf.Min(outerPointsThreshold, leftGridBounds.size.x);
            leftGridBounds.min = leftGridMin;

            // Start raycasting. We run raycasts synchronously so the user can't switch scenes or make scene changes while they are running.
            var maxHitDistance       = voxelGenerationParams.maxHitDistance;
            var normalToleranceAngle = voxelGenerationParams.normalToleranceAngle;
            var rayIndex             = 0;
            var up    = Vector3.up;
            var down  = Vector3.down;
            var back  = Vector3.back;
            var right = Vector3.right;
            var left  = Vector3.left;

            while (rayIndex < raycastCount)
            {
                if (EditorUtility.DisplayCancelableProgressBar(
                        "Generating Point Cloud",
                        string.Format("{0}/{1} raycasts completed", rayIndex, raycastCount),
                        (float)rayIndex / raycastCount))
                {
                    EditorUtility.ClearProgressBar();
                    GUIUtility.ExitGUI();
                    break;
                }

                for (var i = 0; i < k_RaycastProgressBatchSize && rayIndex < raycastCount; i++, rayIndex++)
                {
                    var        origin    = k_RayOrigins[rayIndex];
                    var        direction = RandomRayDirection();
                    RaycastHit raycastHit;
                    if (!tempPhysicsScene.Raycast(origin, direction, out raycastHit, maxHitDistance))
                    {
                        continue;
                    }

                    var point  = raycastHit.point;
                    var normal = raycastHit.normal;

                    if (Vector3.Angle(normal, up) <= normalToleranceAngle && upGridBounds.Contains(point))
                    {
                        k_UpGridPoints.Add(point);
                    }

                    if (Vector3.Angle(normal, down) <= normalToleranceAngle && downGridBounds.Contains(point))
                    {
                        k_DownGridPoints.Add(point);
                    }

                    if (Vector3.Angle(normal, k_Forward) <= normalToleranceAngle && forwardGridBounds.Contains(point))
                    {
                        k_ForwardGridPoints.Add(point);
                    }

                    if (Vector3.Angle(normal, back) <= normalToleranceAngle && backGridBounds.Contains(point))
                    {
                        k_BackGridPoints.Add(point);
                    }

                    if (Vector3.Angle(normal, right) <= normalToleranceAngle && rightGridBounds.Contains(point))
                    {
                        k_RightGridPoints.Add(point);
                    }

                    if (Vector3.Angle(normal, left) <= normalToleranceAngle && leftGridBounds.Contains(point))
                    {
                        k_LeftGridPoints.Add(point);
                    }
                }
            }

            EditorUtility.ClearProgressBar();
            EditorSceneManager.ClosePreviewScene(tempPreviewScene);

            // Reset the seed so other uses of Random are not deterministic
            Random.InitState((int)DateTime.Now.Ticks);

            // Generate voxel grids from point cloud
            var voxelSize = voxelGenerationParams.voxelSize;

            s_UpVoxelGrid      = new PlaneExtractionVoxelGrid(VoxelGridOrientation.Up, upGridBounds, voxelSize, planeFindingParams);
            s_DownVoxelGrid    = new PlaneExtractionVoxelGrid(VoxelGridOrientation.Down, downGridBounds, voxelSize, planeFindingParams);
            s_ForwardVoxelGrid = new PlaneExtractionVoxelGrid(VoxelGridOrientation.Forward, forwardGridBounds, voxelSize, planeFindingParams);
            s_BackVoxelGrid    = new PlaneExtractionVoxelGrid(VoxelGridOrientation.Back, backGridBounds, voxelSize, planeFindingParams);
            s_RightVoxelGrid   = new PlaneExtractionVoxelGrid(VoxelGridOrientation.Right, rightGridBounds, voxelSize, planeFindingParams);
            s_LeftVoxelGrid    = new PlaneExtractionVoxelGrid(VoxelGridOrientation.Left, leftGridBounds, voxelSize, planeFindingParams);
            s_UpVoxelGrid.AddPoints(k_UpGridPoints);
            s_DownVoxelGrid.AddPoints(k_DownGridPoints);
            s_ForwardVoxelGrid.AddPoints(k_ForwardGridPoints);
            s_BackVoxelGrid.AddPoints(k_BackGridPoints);
            s_RightVoxelGrid.AddPoints(k_RightGridPoints);
            s_LeftVoxelGrid.AddPoints(k_LeftGridPoints);
        }