ScriptableRenderContext.BeginRenderPass
Declaration
public void BeginRenderPass(int width, int height, int samples, NativeArray<AttachmentDescriptor> attachments, int depthAttachmentIndex);public void BeginRenderPass(int width, int height, int samples, NativeArray<AttachmentDescriptor> attachments, int depthAttachmentIndex, int shadingRateImageAttachmentIndex);public void BeginRenderPass(int width, int height, int volumeDepth, int samples, NativeArray<AttachmentDescriptor> attachments, int depthAttachmentIndex);public void BeginRenderPass(int width, int height, int volumeDepth, int samples, NativeArray<AttachmentDescriptor> attachments, int depthAttachmentIndex, int shadingRateImageAttachmentIndex);Параметры
| Параметр | Описание |
|---|---|
| ширина | Ширина поверхности прохода рендеринга в пикселях. |
| высота | Высота поверхности прохода рендеринга в пикселях. |
| volumeDepth | Число слоев поверхностей, проходящих через рендеринг. Значение по умолчанию — 1. |
| образцы | MSAA sample count; установить на 1 для отключения сглаживания. |
| Приложения | Массив цветовых вложений для использования в этом проходе рендеринга. Значения в массиве немедленно копируются. |
| depthAttachmentIndex | Индекс вложения, которое будет использоваться в качестве буфера глубины/шаблона для этого прохода рендеринга, или -1 для отключения глубины/шаблона. |
| shadingRateImageAttachmentIndex | Индекс вложения, который будет использоваться в качестве ShadingRateImage для этого прохода рендеринга, или -1 для отключения затенения с переменной скоростью. |
Описание
Расписывает начало нового прохода рендеринга. В любой момент времени может быть активен только один проход рендеринга.
Процесс рендеринга обеспечивает новый способ переключения целей рендеринга в контексте Скриптового Конвейера Рендирования. В отличие от функции SetRenderTargets, процесс рендеринга определяет четкое начало и конец рендеринга, наряду с явными действиями загрузки/сохранения на поверхностях рендеринга.
Процесс рендеринга также позволяет запускать несколько подпроцессов в рамках одного и того же процесса рендеринга, где пиксельные шейдеры имеют доступ для чтения текущего значения пикселя в пределах процесса рендеринга. Это позволяет эффективно реализовать различные методы рендеринга на основанном на плитках GPUs, такие как отсроченное рендеринг.
Процессы рендеринга реализованы на Metal (iOS) и Vulkan, но API полностью функционален на всех рендеринг-бэкэндах через эмуляцию (используя старые вызовы SetRenderTargets и чтение текущих значений пикселей с помощью тэксел-феч).
Механизм прохождения рендеринга имеет следующие ограничения:
— Все вложения (за исключением вложений изображений с частотой затенения) должны иметь одно и то же разрешение и MSAA количество выборок
— Результаты рендеринга предыдущих подпроходов доступны только в пределах одного и того же пикселя экранного пространства
координаты через макрос UNITY_READ_FRAMEBUFFER_INPUT(x) в шейдере; вложения не могут быть связаны как текстуры или иным образом доступны до тех пор, пока прохождение рендеринга не закончится
— iOS Metal не позволяет чтение из Z-буфера, поэтому для обхода этого требуется дополнительная цель рендеринга
— Максимальное количество вложений, разрешенных на прохождение рендеринга, в настоящее время составляет 8 + глубина, но обратите внимание, что различные GPUs могут иметь более строгие ограничения.
Дополнительные ресурсы: BeginSubPass, EndRenderPassBeginScopedRenderPass, BeginScopedSubPass, SystemInfo.supportsMultisampledShaderResolve.
Быстрый пример того, как использовать проход рендеринга API в Scriptable Render Pipeline для реализации отложенного рендеринга:
using UnityEngine; using UnityEngine.Rendering; using Unity.Collections;
public static class DeferredRenderer { public static void ExecuteRenderLoop(Camera camera, CullingResults cullResults, ScriptableRenderContext context) { // Create the attachment descriptors. If these attachments are not specifically bound to any RenderTexture using the ConfigureTarget calls, // these are treated as temporary surfaces that are discarded at the end of the renderpass var albedo = new AttachmentDescriptor(RenderTextureFormat.ARGB32); var specRough = new AttachmentDescriptor(RenderTextureFormat.ARGB32); var normal = new AttachmentDescriptor(RenderTextureFormat.ARGB2101010); var emission = new AttachmentDescriptor(RenderTextureFormat.ARGBHalf); var depth = new AttachmentDescriptor(RenderTextureFormat.Depth);
// At the beginning of the render pass, clear the emission buffer to all black, and the depth buffer to 1.0f emission.ConfigureClear(new Color(0.0f, 0.0f, 0.0f, 0.0f), 1.0f, 0); depth.ConfigureClear(new Color(), 1.0f, 0);
// Bind the albedo surface to the current camera target, so the final pass will render the Scene to the screen backbuffer // The second argument specifies whether the existing contents of the surface need to be loaded as the initial values; // in our case we do not need that because we'll be clearing the attachment anyway. This saves a lot of memory // bandwidth on tiled GPUs. // The third argument specifies whether the rendering results need to be written out to memory at the end of // the renderpass. We need this as we'll be generating the final image there. // We could do this in the constructor already, but the camera target may change on the fly, esp. in the editor albedo.ConfigureTarget(BuiltinRenderTextureType.CameraTarget, false, true);
// All other attachments are transient surfaces that are not stored anywhere. If the renderer allows, // those surfaces do not even have a memory allocated for the pixel values, saving RAM usage.
// Start the renderpass using the given scriptable rendercontext, resolution, samplecount, array of attachments that will be used within the renderpass and the depth surface var attachments = new NativeArray<AttachmentDescriptor>(5, Allocator.Temp); const int depthIndex = 0, albedoIndex = 1, specRoughIndex = 2, normalIndex = 3, emissionIndex = 4; attachments[depthIndex] = depth; attachments[albedoIndex] = albedo; attachments[specRoughIndex] = specRough; attachments[normalIndex] = normal; attachments[emissionIndex] = emission; context.BeginRenderPass(camera.pixelWidth, camera.pixelHeight, 1, 1, attachments, depthIndex); attachments.Dispose();
// Start the first subpass, GBuffer creation: render to albedo, specRough, normal and emission, no need to read any input attachments var gbufferColors = new NativeArray<int>(4, Allocator.Temp); gbufferColors[0] = albedoIndex; gbufferColors[1] = specRoughIndex; gbufferColors[2] = normalIndex; gbufferColors[3] = emissionIndex; context.BeginSubPass(gbufferColors); gbufferColors.Dispose();
// Render the deferred G-Buffer // RenderGBuffer(cullResults, camera, context);
context.EndSubPass();
// Second subpass, lighting: Render to the emission buffer, read from albedo, specRough, normal and depth. // The last parameter indicates whether the depth buffer can be bound as read-only. // Note that some renderers (notably iOS Metal) won't allow reading from the depth buffer while it's bound as Z-buffer, // so those renderers should write the Z into an additional FP32 render target manually in the pixel shader and read from it instead var lightingColors = new NativeArray<int>(1, Allocator.Temp); lightingColors[0] = emissionIndex; var lightingInputs = new NativeArray<int>(4, Allocator.Temp); lightingInputs[0] = albedoIndex; lightingInputs[1] = specRoughIndex; lightingInputs[2] = normalIndex; lightingInputs[3] = depthIndex; context.BeginSubPass(lightingColors, lightingInputs, true); lightingColors.Dispose(); lightingInputs.Dispose();
// PushGlobalShadowParams(context); // RenderLighting(camera, cullResults, context);
context.EndSubPass();
// Third subpass, tonemapping: Render to albedo (which is bound to the camera target), read from emission. var tonemappingColors = new NativeArray<int>(1, Allocator.Temp); tonemappingColors[0] = albedoIndex; var tonemappingInputs = new NativeArray<int>(1, Allocator.Temp); tonemappingInputs[0] = emissionIndex; context.BeginSubPass(tonemappingColors, tonemappingInputs, true); tonemappingColors.Dispose(); tonemappingInputs.Dispose();
// present frame buffer. // FinalPass(context);
context.EndSubPass();
context.EndRenderPass(); } }