Version: 2019.4
Использование текстур глубины
Особенности рендеринга различных платформ

Текстура глубины камеры

В Unity камера может генерировать текстуры глубины или текстуры глубины и нормалей. Это минималистичная текстура G-буфера, которую можно использовать для эффектов пост-обработки или для создания пользовательских моделей освещения (например, light pre-pass). На деле камера строит текстуру глубины используя функцию подмены шейдера, таким образом, это вполне можно сделать вручную, в случае необходимости иной настройки G-буфера.

Текстура глубины камеры может быть включена путём использования в скрипте переменной Camera.depthTextureMode.

Есть 2 режима текстуры глубины:

  • DepthTextureMode.Depth: текстура глубины.
  • DepthTextureMode.DepthNormals: depth and view space normals packed into one texture.*
  • DepthTextureMode.MotionVectors: per-pixel screen space motion of each screen texel for the current frame. Packed into a RG16 texture.

These are flags, so it is possible to specify any combination of the above textures.

Текстура DepthTextureMode.Depth

Строит текстуру глубины размера экрана.

Depth texture is rendered using the same shader passes as used for shadow caster rendering (ShadowCaster pass type). So by extension, if a shader does not support shadow casting (i.e. there’s no shadow caster pass in the shader or any of the fallbacks), then objects using that shader will not show up in the depth texture.

  • Make your shader fallback to some other shader that has a shadow casting pass, or
  • If you’re using surface shaders, adding an addshadow directive will make them generate a shadow pass too.

Note that only “opaque” objects (that which have their materials and shaders setup to use render queue <= 2500) are rendered into the depth texture.

Текстура DepthTextureMode.DepthNormals

Строит 32-битную (8 бит/канал) текстуру размера экрана, в которой нормали пространства вида закодированы в R&G каналы, а глубина закодирована в B&A каналы. Нормали закодированы используя стереографическую проекцию, а глубина - 16-битное значение упакованное в 2 канала по 8 бит.

Присоединяемый файл UnityCG.cginc имеет вспомогательную функцию DecodeDepthNormal, предназначенную для декодирования глубины и нормали из закодированного значения пикселя. Возвращает глубину в диапазоне 0..1.

For examples on how to use the depth and normals texture, please refer to the EdgeDetection image effect in the Shader Replacement example project or Screen Space Ambient Occlusion Image Effect.

Текстура DepthTextureMode.DepthNormals

This builds a screen-sized RG16 (16-bit float/channel) texture, where screen space pixel motion is encoded into the R&G channels. The pixel motion is encoded in screen UV space.

When sampling from this texture motion from the encoded pixel is returned in a rance of –1..1. This will be the UV offset from the last frame to the current frame.

Советы и трюки

Camera inspector indicates when a camera is rendering a depth or a depth+normals texture.

The way that depth textures are requested from the Camera (Camera.depthTextureMode) might mean that after you disable an effect that needed them, the Camera might still continue rendering them. If there are multiple effects present on a Camera, where each of them needs the depth texture, there’s no good way to automatically disable depth texture rendering if you disable the individual effects.

При осуществлении комплексных шейдеров или эффектов пост-обработки не забывайте об отличиях рендеринга между платформами. В частности, использование текстуры глубины в эффекте пост-обработки часто требует особого обращения с Direct3D и сглаживанием.

В некоторых случаях текстура глубины может идти прямо из местного Z-буфера. Если вы видите артефакты в своей текстуре глубины, убедитесь, что шейдеры, которые используют её, не пишут в Z-буфер (используйте ZWrite Off).

Shader variables

Depth textures are available for sampling in shaders as global shader properties. By declaring a sampler called _CameraDepthTexture you will be able to sample the main depth texture for the camera.

_CameraDepthTexture always refers to the camera’s primary depth texture. By contrast, you can use _LastCameraDepthTexture to refer to the last depth texture rendered by any camera. This could be useful for example if you render a half-resolution depth texture in script using a secondary camera and want to make it available to a post-process shader.

The motion vectors texture (when enabled) is available in Shaders as a global Shader property. By declaring a sampler called ‘_CameraMotionVectorsTexture’ you can sample the Texture for the curently rendering Camera.

Под капотом

Depth textures can come directly from the actual depth buffer, or be rendered in a separate pass, depending on the rendering path used and the hardware. Typically when using Deferred Shading or Legacy Deferred Lighting rendering paths, the depth textures come “for free” since they are a product of the G-buffer rendering anyway.

Текстура глубины может исходить напрямую из действующего буфера глубины или рендериться в отдельном порядке, в зависимости от используемого способа рендеринга и железа. Когда текстура глубины рендерится в отдельном порядке, это делается через шейдер замещения. Следовательно, важно, чтобы в шейдерах тег “RenderType” был правильным.

When enabled, the MotionVectors texture always comes from a extra render pass. Unity will render moving GameObjects into this buffer, and construct their motion from the last frame to the current frame.

Смотрите так же

Использование текстур глубины
Особенности рендеринга различных платформ