using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Profiling;

/// <summary>
/// 相机渲染管理类
/// </summary>
partial class CameraRenderer
{
    partial void DrawGizmos();
    partial void DrawUnsupportedShaders();
#if UNITY_EDITOR
    // SRP不支持的着色器标签类型
    static ShaderTagId[] legacyShaderTagIds = {
        new ShaderTagId("Always"),
        new ShaderTagId("ForwardBase"),
        new ShaderTagId("PrepassBase"),
        new ShaderTagId("Vertex"),
        new ShaderTagId("VertexLMRGBM"),
        new ShaderTagId("VertexLM"),
    };
    // 绘制成使用错误材质的粉红色颜色
    static Material errorMaterial;

    partial void PrepareForSceneWindow();

    partial void PrepareBuffer();

    string sampleName { get; set; }

    /// <summary>
    /// 绘制SRP不支持的内置着色器
    /// </summary>
    partial void DrawUnsupportedShaders()
    {
        if (errorMaterial == null)
        {
            errorMaterial = new Material(Shader.Find("Hidden/InternalErrorShader"));
        }
        var drawingSettings = new DrawingSettings(legacyShaderTagIds[0], new SortingSettings(camera))
        {
            overrideMaterial = errorMaterial
        };
        for (int i = 1; i < legacyShaderTagIds.Length; i++)
        {
            drawingSettings.SetShaderPassName(i, legacyShaderTagIds[i]);
        }
        var fliteringSettings = FilteringSettings.defaultValue;
        // 可以通过 FilteringSettings.defaultValue 属性获得默认的过滤设置
        context.DrawRenderers(cullingResults, ref drawingSettings, ref fliteringSettings);
    }

    /// <summary>
    /// 绘制Gizmos
    /// </summary>
    /// <returns></returns>
    partial void DrawGizmos()
    {
        if (Handles.ShouldRenderGizmos())
        {
            context.DrawGizmos(camera, GizmoSubset.PreImageEffects);
            context.DrawGizmos(camera, GizmoSubset.PostImageEffects);
        }
    }

    /// <summary>
    /// 在Game视图绘制的几何体也绘制到Scene视图中
    /// </summary>
    /// <returns></returns>
    partial void PrepareForSceneWindow()
    {
        if (camera.cameraType == CameraType.SceneView)
        {
            // 如果切换到了Scene视图，调用次方法完成绘制
            ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
        }
    }

    /// <summary>
    /// 设置buffer缓冲区的名字
    /// </summary>
    /// <returns></returns>
    partial void PrepareBuffer()
    {
        // 设置只有在编辑器模式下才分配内存
        Profiler.BeginSample("Editor Only");
        buffer.name = camera.name;
        Profiler.EndSample();
    }
#else
    const string sampleName = bufferName;
#endif
}
