using System;
using UnityEngine;
using UnityEngine.Rendering.LookDev;
using IDataProvider = UnityEngine.Rendering.LookDev.IDataProvider;
namespace UnityEditor.Rendering.LookDev
{
/// Data container to be used with Renderer class
class RenderingData : IDisposable
{
///
/// Internally set to true when the given RenderTexture was not the good size regarding and needed to be recreated
///
public bool sizeMissmatched;
/// The stage that possess every object in your view
public Stage stage;
/// Callback to update the Camera position. Only done in First phase.
public ICameraUpdater updater;
/// Viewport size
public Rect viewPort;
/// Render texture handling captured image
public RenderTexture output;
private bool disposed = false;
/// Dispose pattern
public void Dispose()
{
if (disposed)
return;
disposed = true;
stage = null;
updater = null;
output?.Release();
output = null;
}
}
/// Basic renderer to draw scene in texture
class Renderer
{
/// Use pixel perfect
public bool pixelPerfect { get; set; }
/// Constructor
/// [Optional] Use pixel perfect
public Renderer(bool pixelPerfect = false)
=> this.pixelPerfect = pixelPerfect;
/// Init for rendering
/// The data to use
public void BeginRendering(RenderingData data, IDataProvider dataProvider)
{
data.stage.OnBeginRendering(dataProvider);
data.updater?.UpdateCamera(data.stage.camera);
data.stage.camera.enabled = true;
}
/// Finish to render
/// The data to use
public void EndRendering(RenderingData data, IDataProvider dataProvider)
{
data.stage.camera.enabled = false;
data.stage.OnEndRendering(dataProvider);
}
bool CheckWrongSizeOutput(RenderingData data)
{
if (data.viewPort.IsNullOrInverted()
|| data.viewPort.width != data.output.width
|| data.viewPort.height != data.viewPort.height)
{
data.output = null;
data.sizeMissmatched = true;
return true;
}
data.sizeMissmatched = false;
return false;
}
///
/// Capture image of the scene.
///
/// Datas required to compute the capture
/// [Optional] When drawing several time the scene, you can remove First and/or Last to not initialize objects.
/// Be careful though to always start your frame with a First and always end with a Last.
///
public void Acquire(RenderingData data)
{
if (CheckWrongSizeOutput(data))
return;
data.stage.camera.targetTexture = data.output;
data.stage.camera.Render();
}
internal static void DrawFullScreenQuad(Rect rect)
{
GL.PushMatrix();
GL.LoadOrtho();
GL.Viewport(rect);
GL.Begin(GL.QUADS);
GL.TexCoord2(0, 0);
GL.Vertex3(0f, 0f, 0);
GL.TexCoord2(0, 1);
GL.Vertex3(0f, 1f, 0);
GL.TexCoord2(1, 1);
GL.Vertex3(1f, 1f, 0);
GL.TexCoord2(1, 0);
GL.Vertex3(1f, 0f, 0);
GL.End();
GL.PopMatrix();
}
}
/// Rect extension
public static partial class RectExtension
{
/// Return true if the is null sized or inverted.
/// The rect
/// True: null or inverted area
public static bool IsNullOrInverted(this Rect r)
=> r.width <= 0f || r.height <= 0f
|| float.IsNaN(r.width) || float.IsNaN(r.height);
}
}