This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,9 @@
# Camera Switcher
The **CameraSwitcher** component allows you to define a List of Cameras in the Scene and then use the Debug Window to switch between them in Play Mode. This is useful when you want a set of different fixed views for profiling purposes where you need to guarantee that the Camera view is in the same position between sessions.
## Properties
| **Property** | **Description** |
| ------------ | ------------------------------------------------------------ |
| **Cameras** | Drag and drop GameObjects that have a Camera component attached to add them to this List of Cameras. The Debug Window can switch between the Cameras in this List. |
@@ -0,0 +1,258 @@
[comment]: # (If you modify this file make sure you modify the copy/paste file: com.unity.render-pipelines.universal and com.unity.render-pipelines.high-definition\Documentation~\lens-flare-data-driven-asset.md)
# Lens Flare (SRP) Asset
Unity’s [Scriptable Render Pipeline (SRP)](https://docs.unity3d.com/Manual/ScriptableRenderPipeline.html) includes the **Lens Flare Data** asset. You can use this asset to control the appearance of [Lens Flares](lens-flare-component.md) in your scene. This is the SRP equivalent of the Built-in Render Pipeline's [Flare](https://docs.unity3d.com/Manual/class-Flare.html) asset, which is incompatible with SRPs.
To create a Lens Flare Data asset, select **Assets > Create > Lens Flare (SRP)**. To use this asset, assign it to the **Lens Flare Data** property of a [Lens Flare (SRP) component](lens-flare-component.md).
## Properties
The Lens Flare Element asset has the following properties:
- [Type](#Type)
- [Image](#Image)
- [Circle](#Circle)
- [Polygon](#Polygon)
- [Ring](#Ring)
- [Lens Flare Data SRP](#LensFlareDataSRP)
- [Common](#Common)
- [Cutoff](#Cutoff)
- [Transform](#Transform)
- [AxisTransform](#AxisTransform)
- [Distortion](#Distortion)
- [Multiple Elements](#Multiple-Elements)
- [Uniform](#Uniform)
- [Curve](#Curve)
- [Random](#Random)
<a name="Image"></a>
### Type
| **Property** | **Description** |
| ------------ | ------------------------------------------------------------ |
| Type | Select the type of Lens Flare Element this asset creates: <br />&#8226; [Image](#Image) <br />&#8226; [Circle](#Circle) <br />&#8226; [Polygon](#Polygon) |
<a name="Image"></a>
#### Image
![](images/LensFlareShapeImage.png)
| **Property** | **Description** |
| --------------------- | ------------------------------------------------------------ |
| Flare Texture | The Texture this lens flare element uses. |
| Preserve Aspect Ratio | Fixes the width and height (aspect ratio) of the **Flare Texture**. You can use [Distortion](#Distortion) to change this property. |
<a name="Circle"></a>
#### Circle
![](images/LensFlareShapeCircle.png)
| **Property** | **Description** |
| ------------ | ------------------------------------------------------------ |
| Gradient | Controls the offset of the circular flare's gradient. This value ranges from 0 to 1. |
| Falloff | Controls the falloff of the circular flare's gradient. This value ranges from 0 to 1, where 0 has no falloff between the tones and 1 creates a falloff that is spread evenly across the circle. |
| Inverse | Enable this property to reverse the direction of the gradient. |
<a name="Polygon"></a>
#### Polygon
![](images/LensFlareShapePolygon.png)
| **Property** | **Description** |
| ------------ | ------------------------------------------------------------ |
| Gradient | Controls the offset of the polygon flare's gradient. This value ranges from 0 to 1. |
| Falloff | Controls the falloff of the polygon flare's gradient. This value ranges from 0 to 1, where 0 has no falloff between the tones and 1 creates a falloff that is spread evenly across the polygon. |
| Side Count | Determines how many sides the polygon flare has. |
| Roundness | Defines how smooth the edges of the polygon flare are. This value ranges from 0 to 1, where 0 is a sharp polygon and 1 is a circle. |
| Inverse | Enable this property to reverse the direction of the gradient |
<a name="Ring"></a>
#### Ring
![](images/LensFlareShapeRing.png)
| **Property** | **Description** |
| --------------- | -------------------------------------------------------------- |
| Gradient | Controls the offset of the circular flare's gradient. This value ranges from 0 to 1. |
| Falloff | Controls the falloff of the circular flare's gradient. This value ranges from 0 to 1, where 0 has no falloff between the tones and 1 creates a falloff that is spread evenly across the circle. |
| Inverse | Enable this property to reverse the direction of the gradient. |
| Amplitude | Amplitude of the sampling of the noise. |
| Repeat | Frequency of the sampling for the noise. |
| Speed | Scale the speed of the animation. |
| Ring Thickness | Ring Thickness. |
<a name="LensFlareDataSRP"></a>
#### Lens Flare Data Driven SRP
![](images/LensFlareShapeLensFlareDataSRP.png)
| **Property** | **Description** |
| --------------- | ------------------------------------------------------------ |
| Asset | Lens Flare Data SRP asset as an element. |
Unity support an Lens Flare Data SRP recursive, but with a hard cutoff after 16 recursions call.
For instance asset A constains asset B which constains asset A (infinite recursion).
That will trigger a warning and execution 16 recursions:
~~~~~~
"LensFlareSRPAsset contains too deep recursive asset (> 16). Be careful to not have recursive aggregation, A contains B, B contains A, ... which will produce an infinite loop."
~~~~~~
<a name="Color"></a>
## Color
![](images/LensFlareColor.png)
| **Property** | **Description** |
| ----------------------- | ------------------------------------------------------------ |
| Color Type | Select the color type of Lens Flare Element this asset creates: <br />&#8226; [Constant](#ColorConstant) <br />&#8226; [Radial](#ColorRadial) <br />&#8226; [Angular](#ColorAngular) |
| Tint | Changes the tint of the lens flare. If this asset is attached to the light, this property is based on the light tint. |
| Modulate By Light Color | Allows light color to affect this Lens Flare Element. This only applies when the asset is used in a [SRP Lens Flare Override Component](srp-lens-flare-component.md) that is attached to a point, spot, or area light. |
| Intensity | Controls the intensity of this element. |
| Blend Mode | Select the blend mode of the Lens Flare Element this asset creates:<br />&#8226; Additive <br />&#8226; Screen <br />&#8226; Premultiplied <br />&#8226; Lerp |
<a name="ColorConstant"></a>
### Constant Color
![](images/LensFlareColorConstant.png)
| **Property** | **Description** |
| ----------------------- | ------------------------------------------------------------ |
| Tint | Changes the tint of the lens flare. If this asset is attached to the light, this property is based on the light tint. |
<a name="ColorRadial"></a>
### Constant Color
![](images/LensFlareColorRadialGradient.png)
| **Property** | **Description** |
| ----------------------- | ------------------------------------------------------------ |
| Tint Radial | Specifies the radial gradient tint of the element. If the element type is set to Image, the Flare Texture is multiplied by this color. |
<a name="ColorAngular"></a>
### Constant Color
![](images/LensFlareColorAngularGradient.png)
| **Property** | **Description** |
| ----------------------- | ------------------------------------------------------------ |
| Tint Angular | Specifies the angular gradient tint of the element. If the element type is set to Image, the Flare Texture is multiplied by this color. |
<a name="Common"></a>
## Common
<a name="Cutoff"></a>
### Cutoff
![](images/LensFlareCutoff.png)
| **Property** | **Description** |
| ----------------------- | ------------------------------------------------------------ |
| Cutoff Speed | Sets the speed at which the radius occludes the element.
A value of zero (with a large radius) does not occlude anything. The higher this value, the faster the element is occluded on the side of the screen.
The effect of this value is more noticeable with multiple elements.
. |
| Cutoff Radius | Sets the normalized radius of the lens shape used to occlude the lens flare element.
A radius of one is equivalent to the scale of the element.. |
<a name="Transform"></a>
### Transform
![](images/LensFlareTransform.png)
| **Property** | **Description** |
| ----------------------- | ------------------------------------------------------------ |
| Position Offset | Defines the offset of the lens flare's position in screen space, relative to its source. |
| Auto Rotate | Enable this property to automatically rotate the Lens Flare Texture relative to its angle on the screen. Unity uses the **Auto Rotate** angle to override the **Rotation** parameter. <br/><br/> To ensure the Lens Flare can rotate, assign a value greater than 0 to the [**Starting Position**](#AxisTransform) property. |
| Rotation | Rotates the lens flare. This value operates in degrees of rotation. |
| Size | Use this to adjust the scale of this lens flare element. <br/><br/> This property is not available when the [Type](#Type) is set to [Image](#Image) and **Preserve Aspect Ratio** is enabled. |
| Scale | The size of this lens flare element in world space. |
<a name="AxisTransform"></a>
### Axis Transform
![](images/LensFlareAxisTransform.png)
| **Property** | **Description** |
| ----------------- | ------------------------------------------------------------ |
| Starting Position | Defines the starting position of the lens flare relative to its source. This value operates in screen space. |
| Angular Offset | Controls the angular offset of the lens flare, relative to its current position. This value operates in degrees of rotation. |
| Translation Scale | Limits the size of the lens flare offset. For example, values of (1, 0) create a horizontal lens flare, and (0, 1) create a vertical lens flare. <br/><br/>You can also use this property to control how quickly the lens flare appears to move. For example, values of (0.5, 0.5) make the lens flare element appear to move at half the speed. |
<a name="Distortion"></a>
### Distortion
![](images/LensFlareRadialDistortion.png)
| **Property** | **Description** |
| --------------- | ------------------------------------------------------------ |
| Enable | Set this property to True to enable distortion. |
| Radial Edge Size | Controls the size of the distortion effect from the edge of the screen. |
| Radial Edge Curve | Blends the distortion effect along a curve from the center of the screen to the edges of the screen. |
| Relative To Center | Set this value to True to make distortion relative to the center of the screen. Otherwise, distortion is relative to the screen position of the lens flare. |
<a name="Multiple-Elements"></a>
### Multiple Elements
| **Property** | **Description** |
| --------------- | ------------------------------------------------------------ |
| Enable | Enable this to allow multiple lens flare elements in your scene. |
| Count | Determines the number of identical lens flare elements Unity generates.<br/>A value of **1** appears the same as a single lens flare element. |
| Distribution | Select the method that Unity uses to generate multiple lens flare elements:<br/>&#8226;[Uniform](#Uniform)<br/>&#8226;[Curve](#Curve)<br/>&#8226;[Random](#Random) |
| Length Spread | Controls how spread out multiple lens flare elements appear. |
| Relative To Center | If true the distortion is relative to center of the screen otherwise relative to lensFlare source screen position. |
#### Uniform
![](images/LensFlareMultileElementUniform.png)
| **Property** | **Description** |
| --------------- | ------------------------------------------------------------ |
| Colors | The range of colors that this asset applies to the lens flares. |
| Rotation | The angle of rotation (in degrees) applied to each element incrementally. |
<a name="Curve"></a>
#### Curve
![](images/LensFlareMultileElementCurve.png)
| **Property** | **Description** |
| ---------------- | ------------------------------------------------------------ |
| Colors | The range of colors that this asset applies to the lens flares. You can use the **Position Spacing** curve to determine how this range affects each lens flare. |
| Position Variation | Adjust this curve to change the placement of the lens flare elements in the **Lens Spread**. |
| Rotation | The uniform angle of rotation (in degrees) applied to each element distributed along the curve. This value ranges from -180° to 180°. |
| Scale | Adjust this curve to control the size range of the lens flare elements. |
<a name="Random"></a>
#### Random
![](images/LensFlareMultileElementRandom.png)
| **Property** | **Description** |
| ------------------- | ------------------------------------------------------------ |
| Seed | The base value that this asset uses to generate randomness. |
| Intensity Variation | Controls the variation of brightness across the lens flare elements. A high value can make some elements might invisible. |
| Colors | The range of colors that this asset applies to the lens flares. This property is based on the **Seed** value. |
| Position Variation | Controls the position of the lens flares. The **X** value is spread along the same axis as **Length Spread**. A value of 0 means there is no change in the lens flare position. The **Y** value is spread along the vertical screen space axis based on the **Seed** value. |
| Rotation Variation | Controls the rotation variation of the lens flares, based on the **Seed** value. The **Rotation** and **Auto Rotate** parameters inherit from this property. |
| Scale Variation | Controls the scale of the lens flares based on the **Seed** value. |
@@ -0,0 +1,38 @@
[comment]: # (If you modify this file make sure you modify the copy/paste file: com.unity.render-pipelines.universal and com.unity.render-pipelines.high-definition\Documentation~\lens-flare-data-driven-component.md)
# Lens Flare (SRP) Component
![](images/LensFlareHeader.png)
Unity’s Scriptable Render Pipeline (SRP) includes the SRP Lens Flare Override component to control a [Lens Flare (SRP) Data](lens-flare-data-driven-asset.md) asset. You can attach an Lens Flare (SRP) Component to any GameObject.
Some properties only appear when you attach this component to a light.
![](images/LensFlareComp.png)
## Properties
### General
| **Property** | **Description** |
| --------------- | ------------------------------------------------------------ |
| Lens Flare Data | Select the [Lens Flare (SRP) Asset](lens-flare-data-driven-asset.md) asset this component controls. |
| Intensity | Multiplies the intensity of the lens flare. |
| Scale | Multiplies the scale of the lens flare. |
| Light Override | Specifies the light component where the color and shape values are fetched from when using "Modulate By Light Color" or "Attenuation By Light Shape" properties on a Lens Flare Element. If nothing is specified, the light component from this gameobject is used. |
| Attenuation by Light Shape | Enable this property to automatically change the appearance of the lens flare based on the type of light you attached this component to.<br/>For example, if this component is attached to a spot light and the camera is looking at this light from behind, the lens flare will not be visible. <br/>This property is only available when this component is attached to a light. |
| Attenuation Distance |The distance between the start and the end of the Attenuation Distance Curve.<br/>This value operates between 0 and 1 in world space. |
| Attenuation Distance Curve | Fades out the appearance of the lens flare over the distance between the GameObject this asset is attached to, and the Camera. |
| Scale Distance | The distance between the start and the end of the **Scale Distance Curve**.<br/>This value operates between 0 and 1 in world space. |
| Scale Distance Curve | Changes the size of the lens flare over the distance between the GameObject this asset is attached to, and the Camera. |
| Screen Attenuation Curve | Reduces the effect of the lens flare based on its distance from the edge of the screen. You can use this to display a lens flare at the edge of your screen |
### Occlusion
| **Property** | **Description** |
| --------------- | ------------------------------------------------------------ |
| Enable | Enable this property to partially obscure the lens flare based on the depth buffer |
| Occlusion Radius | Defines how far from the light source Unity occludes the lens flare. This value is in world space. |
| Sample Count | The number of random samples the CPU uses to generate the **Occlusion Radius.** |
| Occlusion Offset | Offsets the plane that the occlusion operates on. A higher value moves this plane closer to Camera. This value is in world space. <br/>For example, if a lens flare is inside the light bulb, you can use this to sample occlusion outside the light bulb. |
| Occlusion Remap Curve | Specifies the curve used to remap the occlusion of the flare. By default, the occlusion is linear, between 0 and 1. This can be specifically useful to occlude flare more drastically when behind clouds. |
| Allow Off Screen | Enable this property to allow lens flares outside the Camera's view to affect the current field of view. |
@@ -0,0 +1,16 @@
# Light Anchor
![](Images/LightAnchor0.png)
You can use a Light Anchor to light a scene in Rendered Camera Space. To use a Light Anchor, you must connect it to a Light.
## Properties
| **Property** | **Description** |
| --------------- | ------------------------------------------------------------ |
| Orbit | Use the left icon to control the Orbit of the light. This tool becomes green when you move the icon. |
| Elevation | Use the middle icon to control the Elevation of the light. This tool becomes blue when you move the icon. |
| Roll | Use the right icon to control the Rollof the light. This tool becomes gray when you move the icon. This is especially useful if the light has an IES or a Cookie. |
| Distance | Controls the distance between the light and its anchor in world space. |
| Up Direction | Defines the space of the up direction of the anchor. When this value is set to Local, the Up Direction is relative to the camera. |
| Common | Assigns a preset to the light component based on the behaviour of studio lights. |
@@ -0,0 +1,364 @@
Shader "Hidden/Universal/CoreBlit"
{
HLSLINCLUDE
#pragma target 2.0
#pragma editor_sync_compilation
// Core.hlsl for XR dependencies
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blit.hlsl"
// DebuggingFullscreen.hlsl for URP debug draw
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/DebuggingFullscreen.hlsl"
// Color.hlsl for color space conversion
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
// Specialized blit with URP debug draw support and color space conversion support
half4 FragmentURPBlit(Varyings input, SamplerState blitsampler)
{
half4 color = FragBlit(input, blitsampler);
#ifdef _LINEAR_TO_SRGB_CONVERSION
color = LinearToSRGB(color);
#endif
#if defined(DEBUG_DISPLAY)
half4 debugColor = 0;
float2 uv = input.texcoord;
if (CanDebugOverrideOutputColor(color, uv, debugColor))
{
return debugColor;
}
#endif
return color;
}
ENDHLSL
SubShader
{
Tags{ "RenderPipeline" = "UniversalPipeline" }
// 0: Nearest
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "Nearest"
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment FragNearest
ENDHLSL
}
// 1: Bilinear
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "Bilinear"
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment FragBilinear
ENDHLSL
}
// 2: Nearest quad
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "NearestQuad"
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragNearest
ENDHLSL
}
// 3: Bilinear quad
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "BilinearQuad"
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragBilinear
ENDHLSL
}
// 4: Nearest quad with padding
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "NearestQuadPadding"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragNearest
ENDHLSL
}
// 5: Bilinear quad with padding
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "BilinearQuadPadding"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragBilinear
ENDHLSL
}
// 6: Nearest quad with padding and repeat
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "NearestQuadPaddingRepeat"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragNearestRepeat
ENDHLSL
}
// 7: Bilinear quad with padding and repeat
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "BilinearQuadPaddingRepeat"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragBilinearRepeat
ENDHLSL
}
// 8: Bilinear quad with padding (for OctahedralTexture)
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "BilinearQuadPaddingOctahedral"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragOctahedralBilinearRepeat
ENDHLSL
}
/// Version 4, 5, 6, 7 with Alpha Blending 0.5
// 9: Nearest quad with padding alpha blend (4 with alpha blend)
Pass
{
ZWrite Off ZTest Always Blend DstColor Zero Cull Off
Name "NearestQuadPaddingAlphaBlend"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragNearest
#define WITH_ALPHA_BLEND
ENDHLSL
}
// 10: Bilinear quad with padding alpha blend (5 with alpha blend)
Pass
{
ZWrite Off ZTest Always Blend DstColor Zero Cull Off
Name "BilinearQuadPaddingAlphaBlend"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragBilinear
#define WITH_ALPHA_BLEND
ENDHLSL
}
// 11: Nearest quad with padding alpha blend repeat (6 with alpha blend)
Pass
{
ZWrite Off ZTest Always Blend DstColor Zero Cull Off
Name "NearestQuadPaddingAlphaBlendRepeat"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragNearestRepeat
#define WITH_ALPHA_BLEND
ENDHLSL
}
// 12: Bilinear quad with padding alpha blend repeat (7 with alpha blend)
Pass
{
ZWrite Off ZTest Always Blend DstColor Zero Cull Off
Name "BilinearQuadPaddingAlphaBlendRepeat"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragBilinearRepeat
#define WITH_ALPHA_BLEND
ENDHLSL
}
// 13: Bilinear quad with padding alpha blend (for OctahedralTexture) (8 with alpha blend)
Pass
{
ZWrite Off ZTest Always Blend DstColor Zero Cull Off
Name "BilinearQuadPaddingAlphaBlendOctahedral"
HLSLPROGRAM
#pragma vertex VertQuadPadding
#pragma fragment FragOctahedralBilinearRepeat
#define WITH_ALPHA_BLEND
ENDHLSL
}
// 14. Project Cube to Octahedral 2d quad
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "CubeToOctahedral"
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragOctahedralProject
ENDHLSL
}
// 15. Project Cube to Octahedral 2d quad with luminance (grayscale), RGBA to YYYY
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "CubeToOctahedralLuminance"
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragOctahedralProjectLuminance
ENDHLSL
}
// 16. Project Cube to Octahedral 2d quad with with A to RGBA (AAAA)
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "CubeToOctahedralAlpha"
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragOctahedralProjectAlphaToRGBA
ENDHLSL
}
// 17. Project Cube to Octahedral 2d quad with with R to RGBA (RRRR)
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "CubeToOctahedralRed"
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragOctahedralProjectRedToRGBA
ENDHLSL
}
// 18. Bilinear quad with luminance (grayscale), RGBA to YYYY
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "BilinearQuadLuminance"
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragBilinearLuminance
ENDHLSL
}
// 19. Bilinear quad with A to RGBA (AAAA)
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "BilinearQuadAlpha"
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragBilinearAlphaToRGBA
ENDHLSL
}
// 20. Bilinear quad with R to RGBA (RRRR)
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "BilinearQuadRed"
HLSLPROGRAM
#pragma vertex VertQuad
#pragma fragment FragBilinearRedToRGBA
ENDHLSL
}
// 21. Nearest project cube to octahedral 2d quad with padding
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "NearestCubeToOctahedralPadding"
HLSLPROGRAM
#pragma multi_compile_local _ BLIT_DECODE_HDR
#pragma vertex VertQuadPadding
#pragma fragment FragOctahedralProjectNearestRepeat
ENDHLSL
}
// 22. Bilinear project cube to octahedral 2d quad with padding
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "BilinearCubeToOctahedralPadding"
HLSLPROGRAM
#pragma multi_compile_local _ BLIT_DECODE_HDR
#pragma vertex VertQuadPadding
#pragma fragment FragOctahedralProjectBilinearRepeat
ENDHLSL
}
// 23: Bilinear blit with debug draw and color space conversion support
Pass
{
Name "BilinearDebugDraw"
ZWrite Off ZTest Always Blend Off Cull Off
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment FragmentURPBlitBilinearSampler
#pragma multi_compile_fragment _ _LINEAR_TO_SRGB_CONVERSION
#pragma multi_compile_fragment _ DEBUG_DISPLAY
half4 FragmentURPBlitBilinearSampler(Varyings input) : SV_Target
{
return FragmentURPBlit(input, sampler_LinearClamp);
}
ENDHLSL
}
// 24: Nearest blit with debug draw and color space conversion support
Pass
{
Name "NearestDebugDraw"
ZWrite Off ZTest Always Blend Off Cull Off
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment FragmentURPBlitPointSampler
#pragma multi_compile_fragment _ _LINEAR_TO_SRGB_CONVERSION
#pragma multi_compile_fragment _ DEBUG_DISPLAY
half4 FragmentURPBlitPointSampler(Varyings input) : SV_Target
{
return FragmentURPBlit(input, sampler_PointClamp);
}
ENDHLSL
}
}
Fallback Off
}
@@ -0,0 +1,41 @@
Shader "Hidden/Universal/CoreBlitColorAndDepth"
{
HLSLINCLUDE
#pragma target 2.0
#pragma editor_sync_compilation
// Core.hlsl for XR dependencies
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
#include_with_pragmas "Packages/com.unity.render-pipelines.core/Runtime/Utilities/BlitColorAndDepth.hlsl"
ENDHLSL
SubShader
{
Tags{ "RenderPipeline" = "UniversalPipeline" }
// 0: Color Only
Pass
{
ZWrite Off ZTest Always Blend Off Cull Off
Name "ColorOnly"
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment FragColorOnly
ENDHLSL
}
// 1: Color Only and Depth
Pass
{
ZWrite On ZTest Always Blend Off Cull Off
Name "ColorAndDepth"
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment FragColorAndDepth
ENDHLSL
}
}
Fallback Off
}
@@ -0,0 +1,13 @@
# Free Camera
The **FreeCamera** component provides you with an implementation for a simple free camera. When you add this component to a Camera, you can use the keyboard and mouse, or a controller, to control the Camera's position and rotation in Play Mode.
## Properties
| **Property** | **Description** |
| ------------------------- | ------------------------------------------------------------ |
| **Look Speed Controller** | Set the look speed of the Camera when using a controller. |
| **Look Speed Mouse** | Set the look speed of the Camera when using a mouse. |
| **Move Speed** | Set the speed at which the Camera moves. |
| **Move Speed Increment** | Set the value of the increment that you can increase or decrease the **Move Speed** by. This is useful if you have a large Scene and the current **Move Speed** is not enough to easily traverse it. |
| **Turbo** | Set the value that this component multiplies the **Move Speed** by when you press the key or button assigned to "Fire1". |
File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 64 KiB

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 62 KiB

@@ -0,0 +1,221 @@
# Rendering Debugger
The **Rendering Debugger** is a window you can customize with your own controls and scripts to visualize your project's lighting, rendering, or Material properties.
If your project uses a custom Scriptable Render Pipeline (SRP), you can add controls to the default empty window.
If your project uses the Universal Render Pipeline (URP) or the High-Definition Render Pipeline (HDRP), refer to the following pages:
- [Add controls to the Rendering Debugger in URP](https://docs.unity3d.com/Manual/urp/features/rendering-debugger-add-controls.html)
- [Add controls to the Rendering Debugger in HDRP](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@15.0/manual/Rendering-Debugger-Add-Controls.html)
## How to access the Rendering Debugger
The Rendering Debugger window is available in the following modes:
| Mode | Platform | Availability | How to Open the Rendering Debugger |
|------------|----------------|--------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Editor | All | Yes (window in the Editor) | Select **Window > Analysis > Rendering Debugger** |
| Play mode | All | Yes (overlay in the Game view) | On a desktop or laptop computer, press **LeftCtrl+Backspace** (**LeftCtrl+Delete** on macOS)<br>On a console controller, press L3 and R3 (Left Stick and Right Stick) |
| Runtime | Desktop/Laptop | Yes (only in Development builds) | Press **LeftCtrl+Backspace** (**LeftCtrl+Delete** on macOS) |
| Runtime | Console | Yes (only in Development builds) | Press L3 and R3 (Left Stick and Right Stick) |
| Runtime | Mobile | Yes (only in Development builds) | Use a three-finger double tap |
To disable the runtime UI, use the [enableRuntimeUI](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.0/api/UnityEngine.Rendering.DebugManager.html#UnityEngine_Rendering_DebugManager_enableRuntimeUI) property.
## Navigation at runtime
### Keyboard
| Action | Control |
|----------------------------------------------------|-------------------------------------------------------------------------------------------|
| **Change the current active item** | Use the arrow keys |
| **Change the current tab** | Use the Page up and Page down keys (Fn + Up and Fn + Down keys respectively for MacOS) |
| **Display the current active item independently of the debug window** | Press the right Shift key |
### Xbox Controller
| Action | Control |
|----------------------------------------------------|-------------------------------------------------------------------------------------------|
| **Change the current active item** | Use the Directional pad (D-Pad) |
| **Change the current tab** | Use the Left Bumper and Right Bumper |
| **Display the current active item independently of the debug window** | Press the X button |
### PlayStation Controller
| Action | Control |
|----------------------------------------------------|-------------------------------------------------------------------------------------------|
| **Change the current active item** | Use the Directional buttons |
| **Change the current tab** | Use the L1 button and R1 button |
| **Display the current active item independently of the debug window** | Press the Square button |
## Add a control
The **Rendering Debugger** window can contain multiple tabs ('panels'). When you select a panel, the window displays one or more controls ('widgets').
To create a widget and add it to a new panel, do the following:
1. Create a script that uses `using UnityEngine.Rendering;` to include the `UnityEngine.Rendering` namespace.
2. Create a widget by creating an instance of a child class of [DebugUI.Widget](../api/UnityEngine.Rendering.DebugUI.Widget.html), for example `DebugUI.Button`.
3. In the widget, implement the `onValueChanged` callback, which Unity calls when you change the value in the widget.
4. Create a panel using [DebugUI.instance.GetPanel](../api/UnityEngine.Rendering.DebugManager.html#UnityEngine_Rendering_DebugManager_GetPanel_System_String_System_Boolean_System_Int32_System_Boolean_).
5. Add the widget to an array.
6. Add the widget array to the list of children in the panel.
If you add 2 or more widgets to the array, the panel displays the widgets in the same order as the array.
The following code sample creates and adds a widget that enables or disables the main directional light:
```
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
using System.Linq;
[ExecuteInEditMode]
public class CustomDebugPanel : MonoBehaviour
{
static bool lightEnabled = true;
void OnEnable()
{
// Create a list of widgets
var widgetList = new List<DebugUI.Widget>();
// Add a checkbox widget to the list of widgets
widgetList.AddRange(new DebugUI.Widget[]
{
new DebugUI.BoolField
{
displayName = "Enable main directional light",
tooltip = "Enable or disable the main directional light",
getter = () => lightEnabled,
// When the widget value is changed, change the value of lightEnabled
setter = value => lightEnabled = value,
// Run a custom function to enable or disable the main directional light based on the widget value
onValueChanged = DisplaySunChanged
},
});
// Create a new panel (tab) in the Rendering Debugger
var panel = DebugManager.instance.GetPanel("My Custom Panel", createIfNull: true);
// Add the widgets to the panel
panel.children.Add(widgetList.ToArray());
}
// Remove the custom panel if the GameObject is disabled
void OnDisable()
{
DebugManager.instance.RemovePanel("My Custom Panel");
}
// Enable or disable the main directional light based on the widget value
void DisplaySunChanged(DebugUI.Field<bool> field, bool displaySun)
{
Light sun = FindObjectsOfType<Light>().Where(x => x.type == LightType.Directional).FirstOrDefault();
if (sun)
sun.enabled = displaySun;
}
}
```
Add the script to a GameObject. You should see a new **My Custom Panel** panel in the **Rendering Debugger** window.
![Screenshot of the Rendering Debugger window showing a new custom panel.](Images/rendering-debugger.png)
### Add a control to an existing panel
You can only add properties to existing panels if you're using a custom SRP. You shouldn't add widgets to URP or HDRP's built-in Rendering Debugger panels.
To fetch an existing panel, use `DebugManager.instance.GetPanel` with the panel name. Set `createIfNull` to `false`, so you don't accidentally create a new panel if the name doesn't match an existing panel.
The following code sample fetches the panel from the code sample above:
```
var panel = DebugManager.instance.GetPanel("My Custom Panel", createIfNull: false);
```
## Add a container
You can use containers to display groups of widgets together.
1. Create a container using one of the child classes of [DebugUI.Container](../api/UnityEngine.Rendering.DebugUI.Container.html), for example `DebugUI.Foldout`.
2. Add a widget array using the container's `Add` method.
The following example creates a collapsible container that contains 2 checkboxes:
```
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
[ExecuteInEditMode]
public class CustomDebugPanelWithContainer : MonoBehaviour
{
void OnEnable()
{
// Create a list of widgets
var widgetList = new List<DebugUI.Widget>();
// Add 2 checkbox widgets to the list of widgets
widgetList.AddRange(new DebugUI.Widget[]
{
new DebugUI.BoolField
{
displayName = "Visualisation 1",
},
new DebugUI.BoolField
{
displayName = "Visualisation 2",
},
});
// Create a container
var container = new DebugUI.Foldout
{
displayName = "My Container"
};
// Add the widgets to the container
container.children.Add(widgetList.ToArray());
// Create a new panel (tab) in the Rendering Debugger
var panel = DebugManager.instance.GetPanel("My Custom Panel With Container", createIfNull: true);
// Add the container to the panel
panel.children.Add(container);
}
}
```
## Control the Rendering Debugger overlay
To change the value of the currently active widget:
- On a keyboard, press the Left and Right arrow keys.
- On a touch screen, tap the arrows next to the properties.
- On an Xbox controller, use the Directional pad (D-Pad).
- On a PlayStation controller, use the Directional buttons.
To change the current panel:
- On a Windows keyboard, use the Page up and Page down keys (macOS: fn + Up arrow key, and fn + Down arrow key).
- On a touch screen, tap the arrows next to the tab title.
- On an Xbox controller, use the Left Bumper and Right Bumper.
- On a PlayStation controller, use L1 and R1.
To display the currently active widget independently of the debug window:
- On a keyboard, press Right Shift.
- On an Xbox controller, press X.
- On a PlayStation controller, press Square.
## Disable the Rendering Debugger
To disable the Rendering Debugger in your built application, set [DebugManager.enableRuntimeUI](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@15.0/api/UnityEngine.Rendering.DebugManager.html#UnityEngine_Rendering_DebugManager_enableRuntimeUI) to `false`.
@@ -0,0 +1,56 @@
* [SRP Core](index.md)
* [What's new](whats-new.md)
* [12](whats-new-12.md)
* [13](whats-new-13.md)
* [17](whats-new-17.md)
* [Creating a custom render pipeline](srp-custom.md)
* [Create a custom Scriptable Render Pipeline](srp-custom-getting-started.md)
* [Create a Render Pipeline Asset and Render Pipeline Instance in a custom render pipeline](srp-creating-render-pipeline-asset-and-render-pipeline-instance.md)
* [Create a simple render loop in a custom render pipeline](srp-creating-simple-render-loop.md)
* [Execute rendering commands in a custom render pipeline](srp-using-scriptable-render-context.md)
* [Scriptable Render Pipeline callbacks reference](srp-callbacks-reference.md)
* [Creating a custom render pipeline using the render graph system](render-graph-system-landing.md)
* [Render graph system](render-graph-system.md)
* [Write a render pipeline with render graph](render-graph-writing-a-render-pipeline.md)
* [Write a render pass using the render graph system](render-graph-write-render-pass.md)
* [Resources in the render graph system](render-graph-resources-landing.md)
* [Introduction to resources in the render graph system](render-graph-resources.md)
* [Blit using the render graph system](render-graph-blit.md)
* [Create a texture in the render graph system](render-graph-create-a-texture.md)
* [Import a texture into the render graph system](render-graph-import-a-texture.md)
* [Access a texture in a render pass](render-graph-read-write-texture.md)
* [Use the CommandBuffer interface in a render graph](render-graph-unsafe-pass.md)
* Camera components
* [Free Camera](Free-Camera.md)
* [Camera Switcher](Camera-Switcher.md)
* [Render Requests](User-Render-Requests.md)
* [Render from another camera inside a camera's rendering loop](in-loop-render-requests.md)
* [RTHandle system](rthandle-system.md)
* [RTHandle fundamentals](rthandle-system-fundamentals.md)
* [Using the RTHandle system](rthandle-system-using.md)
* [Custom Material Inspector](custom-material-inspector.md)
* [Custom graphics settings](settings.md)
* [Adding properties in the menu](adding-properties.md)
* [Add a settings group](add-custom-graphics-settings.md)
* [Add a setting](add-custom-graphics-setting.md)
* [Customize the UI of a setting](customize-ui-for-a-setting.md)
* [Get custom graphics settings](get-custom-graphics-settings.md)
* [Include or exclude a setting in your build](choose-whether-unity-includes-a-graphics-setting-in-your-build.md)
* [Advanced Properties](advanced-properties.md)
* [Shaders](shaders.md)
* [Use shader methods from the SRP Core shader library](built-in-shader-methods.md)
* [Synchronizing shader code and C#](generating-shader-includes.md)
* [Look Dev](Look-Dev.md)
* [Environment Library](Look-Dev-Environment-Library.md)
* [Rendering Debugger](Rendering-Debugger.md)
* [Light Anchor](view-lighting-tool.md)
* [Unified Raytracing API](UnifiedRayTracing/unified-ray-tracing-api.md)
* [Get started with ray tracing](UnifiedRayTracing/get-started.md)
* [Ray tracing workflow](UnifiedRayTracing/workflow.md)
* [Create the ray tracing context](UnifiedRayTracing/create-ray-tracing-context.md)
* [Create an acceleration structure](UnifiedRayTracing/create-acceleration-structure.md)
* [Create a unified ray tracing shader](UnifiedRayTracing/create-shader.md)
* [Write your ray tracing code](UnifiedRayTracing/write-shader.md)
* [Execute your ray tracing code](UnifiedRayTracing/execute-shader.md)
* [Sample code: Tracing camera rays](UnifiedRayTracing/trace-camera-rays-full-sample.md)
* [Unified ray tracing shader code reference](UnifiedRayTracing/shader-code-reference.md)
@@ -0,0 +1,51 @@
# Create an acceleration structure
[`IRayTracingAccelStruct`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct) is the data structure used to represent a collection of instances and geometries that are used for GPU ray tracing.
Create an acceleration structure with the following code:
```C#
var options = new AccelerationStructureOptions();
IRayTracingAccelStruct rtAccelStruct = rtContext.CreateAccelerationStructure(options);
```
## Build options
[`AccelerationStructureOptions`](xref:UnityEngine.Rendering.UnifiedRayTracing.AccelerationStructureOptions) allows you to configure the build algorithm. The trade-off is as follows: A faster build results in worse ray tracing performance, and conversely, a slower build can improve ray tracing performance.
The following fields can be configured:
|Field|Description|
|-|-|
|`buildFlags`|Adjust the buildFlags to prioritize either faster construction of the acceleration structure or faster ray tracing.|
|`useCPUBuild` (Compute backend)|When set to true, Unity builds the acceleration structure on the CPU instead of the GPU. This option has no effect when using the `Hardware` backend. CPU-based builds use a more advanced algorithm, resulting in a higher-quality acceleration structure, which enhances overall ray tracing performance.|
The following example demonstrates how to get the best ray tracing performance. These options make the acceleration structure longer to build, however.
```HLSL
var options = new AccelerationStructureOptions() {
buildFlags = BuildFlags.PreferFastTrace,
useCPUBuild = true
}
```
## Populate the acceleration structure
Unlike [`RayTracingAccelerationStructure`](xref:UnityEngine.Rendering.RayTracingAccelerationStructure), there is no support for automatic synchronization between the acceleration structure's instances and the scene instances. You need to add them manually, for example:
```C#
var instanceDesc = new MeshInstanceDesc(mesh, 0 /*subMeshIndex*/);
instanceDesc.localToWorldMatrix = /* desired transform */;
rtAccelStruct.AddInstance(instanceDesc);
```
To trace rays against all the Mesh-based GameObjects in your scene, add them to the [`IRayTracingAccelStruct`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct). For example:
```C#
var meshRenderers = UnityEngine.Object.FindObjectsByType<MeshRenderer>(FindObjectsSortMode.None);
foreach (var renderer in meshRenderers)
{
var mesh = renderer.GetComponent<MeshFilter>().sharedMesh;
int subMeshCount = mesh.subMeshCount;
for (int i = 0; i < subMeshCount; ++i)
{
var instanceDesc = new MeshInstanceDesc(mesh, i);
instanceDesc.localToWorldMatrix = renderer.transform.localToWorldMatrix;
rtAccelStruct.AddInstance(instanceDesc);
}
}
```
@@ -0,0 +1,73 @@
# Create the ray tracing context
The [`RayTracingContext`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext) serves as the initial API entry point, allowing the creation of all essential objects required to execute ray tracing code.
Follow these steps:
1. Load the ray tracing resources.
2. Create the context.
## Load the ray tracing resources
The [`RayTracingContext`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext) needs a few utility shaders that the [`RayTracingResources`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingResources) object supplies. You can load these resources in several different ways.
If your project uses SRP (Scriptable Render Pipeline), load the resources via [`RayTracingResources.LoadFromRenderPipelineResources`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingResources.LoadFromRenderPipelineResources()). This always works in the Editor.
```C#
var rtResources = new RayTracingResources();
bool result = rtResources.LoadFromRenderPipelineResources();
```
You can instruct Unity to also include the resources in Player builds:
```C#
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
#if UNITY_EDITOR
class MyURTStripping: IRenderPipelineGraphicsSettingsStripper<RayTracingRenderPipelineResources>
{
public bool active => true;
public bool CanRemoveSettings(RayTracingRenderPipelineResources settings) => false;
}
#endif
```
You can also load the resources via the Asset Database:
```C#
var rtResources = new RayTracingResources();
rtResources.Load();
```
**Note:** Since the Player doesn't give access to the Asset Database, this method only works in the Editor.
To load the [`RayTracingResources`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingResources) in the Player, you can also build an AssetBundle that includes the following SRP Core files:
- `Runtime/UnifiedRayTracing/Common/GeometryPool/GeometryPoolKernels.compute`
- `Runtime/UnifiedRayTracing/Common/Utilities/CopyBuffer.compute`
- `Runtime/UnifiedRayTracing/Compute/RadeonRays/kernels/copyPositions.compute`
- `Runtime/UnifiedRayTracing/Compute/RadeonRays/kernels/bit_histogram.compute`
- `Runtime/UnifiedRayTracing/Compute/RadeonRays/kernels/block_reduce_part.compute`
- `Runtime/UnifiedRayTracing/Compute/RadeonRays/kernels/block_scan.compute`
- `Runtime/UnifiedRayTracing/Compute/RadeonRays/kernels/build_hlbvh.compute`
- `Runtime/UnifiedRayTracing/Compute/RadeonRays/kernels/restructure_bvh.compute`
- `Runtime/UnifiedRayTracing/Compute/RadeonRays/kernels/scatter.compute`
For more information about building and loading AssetBundles, refer to [AssetBundles](xref:AssetBundlesIntro).
After you build the AssetBundle, use the following code to load it:
```C#
var rtResources = new RayTracingResources();
// Load the AssetBundle
var asssetBundle = AssetBundle.LoadFromFile("Assets/pathToYourBuiltAssetBundles/unifiedraytracing");
// Load the RayTracingResources
rtResources.LoadFromAssetBundle(asssetBundle);
```
## Create the context
Once the [`RayTracingResources`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingResources) are loaded, use them to create the [`RayTracingContext`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext).
```C#
var context = new RayTracingContext(rtResources);
```
By default, Unity checks if the device supports hardware ray tracing, and selects either hardware ray tracing or compute shaders. To manually select the backend, pass in a `RayTracingBackend`. For example:
```C#
var backend = RayTracingBackend.Compute;
var context = new RayTracingContext(backend, rtResources);
```
@@ -0,0 +1,53 @@
# Create a unified ray tracing shader
Depending on the backend you choose in the [`RayTracingContext`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext), write your ray tracing code in either a `.raytrace` or a `.compute` shader.
To create both a `.raytrace` shader and a `.compute` shader, write your shader code in a unified ray tracing shader (`.urtshader`).
To create a shader, follow these steps:
1. Create the shader asset file.
2. Load the shader.
## Create the shader asset file
To create a unified ray tracing shader:
1. Launch the Unity Editor.
1. In the **Project** window, open the **Assets** folder.
1. Open or create the folder in which you want to create your shader.
1. Open the context menu (right-click) and select **Create** &gt; **Shader** &gt; **Unified Ray Tracing Shader**.
1. Enter a name for the shader.
Ray tracing occurs in the `RayGenExecute` function. You can edit the example code snippet.
For more information about writing a ray tracing shader, refer to [Write your shader code](write-shader.md).
## Load the shader
To load the `.urtshader` file in the Editor, use the following code snippet:
```C#
IRayTracingShader shader = rtContext.LoadRayTracingShader("Assets/yourShader.urtshader");
```
To load the shader in the Player, add the `.urtshader` shader to an <xref:UnityEngine.AssetBundle> then load it with the following:
```C#
// Load the AssetBundle
var asssetBundle = AssetBundle.LoadFromFile("Assets/pathToYourBuiltAssetBundles/yourAssetBundle");
// Load the shader
IRayTracingShader shader = rtContext.LoadRayTracingShaderFromAssetBundle(asssetBundle, "Assets/yourShader.urtshader");
```
To have more control, load the underlying Compute or Ray Tracing shader asset yourself and pass it to [`RayTracingContext.CreateRayTracingShader`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext.CreateRayTracingShader(UnityEngine.Object)).
[`RayTracingContext.LoadRayTracingShaderFromAssetBundle`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext.LoadRayTracingShaderFromAssetBundle(UnityEngine.AssetBundle,System.String)) is a convenience function that performs the following operations:
```C#
public IRayTracingShader LoadRayTracingShaderFromAssetBundle(AssetBundle assetBundle, string name)
{
Object asset = assetBundle.LoadAsset(name, BackendHelpers.GetTypeOfShader(BackendType));
return CreateRayTracingShader(asset);
}
```
@@ -0,0 +1,55 @@
# Execute your ray tracing code
This section assumes you have [a shader](create-shader.md) containing your ray tracing logic and an [acceleration structure](create-acceleration-structure.md) representing the geometry that the rays will intersect.
To execute your ray tracing shader on the GPU:
1. Build the acceleration structure.
2. Bind resources to the shader.
3. Dispatch the shader.
## Build the acceleration structure
You must build the acceleration structure after you create it and every time you modify it. For example:
```C#
IRayTracingAccelStruct rtAccelStruct = /* your acceleration structure */;
var cmd = new CommandBuffer();
// A scratch buffer is required to build the acceleration structure, this helper function allocates one with the required size.
GraphicsBuffer buildScratchBuffer = RayTracingHelper.CreateScratchBufferForBuild(rtAccelStruct);
// Build the ray tracing acceleration structure
rtAccelStruct.Build(cmd, buildScratchBuffer);
```
## Bind resources to the shader
You must bind the acceleration structure and any additional GPU resources declared in your shader, such as constants, buffers, and textures. For example:
```C#
IRayTracingShader rtShader = /* your shader */;
// Bind the acceleration structure. It is declared in the shader as: UNIFIED_RT_DECLARE_ACCEL_STRUCT(_YourAccelStruct);
rtShader.SetAccelerationStructure(cmd, "_YourAccelStruct", rtAccelStruct);
// Bind the other GPU resources (constants/uniforms, buffers and textures)
rtShader.SetIntParam(cmd, Shader.PropertyToID("_YourInteger"), 5);
```
## Dispatch the shader
To make the GPU run your ray tracing shader, call the [`Dispatch`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingShader.Dispatch(UnityEngine.Rendering.CommandBuffer,UnityEngine.GraphicsBuffer,System.UInt32,System.UInt32,System.UInt32)) method. For example:
```C#
const int threadCountX = 256, threadCountY = 256, threadCountZ = 1;
// A scratch buffer is required to trace rays, this helper function allocates one with the required size.
GraphicsBuffer traceScratchBuffer = RayTracingHelper.CreateScratchBufferForTrace(rtShader, threadCountX, threadCountY, threadCountZ);
// Dispatch rays. Workgrid dimensions are supplied in threads, not workgroups
rtShader.Dispatch(cmd, traceScratchBuffer, threadCountX, threadCountY, threadCountZ);
// Execute the command buffer to effectively run all the previously registered commands.
Graphics.ExecuteCommandBuffer(cmd);
```
**Note:** If its size satisfies the requirements for both operations, you can use the same scratch buffer for both the build and trace steps.
@@ -0,0 +1,28 @@
# Get started with ray tracing
The `UnifiedRayTracing` API enables you to write ray tracing code that executes on a wide range of GPUs. Unlike the [`RayTracingAccelerationStructure`](xref:UnityEngine.Rendering.RayTracingAccelerationStructure) API,
its key advantage is that it is able to operate without requiring hardware ray tracing support. It achieves this by offering multiple backends that can be dynamically selected based on the GPU’s capabilities.
## Backends
The following backends are available:
- `Hardware`: Requires a GPU that supports hardware-accelerated ray tracing. This backend uses the [`RayTracingAccelerationStructure`](xref:UnityEngine.Rendering.RayTracingAccelerationStructure) API.
- `Compute` : Software implementation of ray tracing that works only on GPUs that support compute shaders.
By abstracting these different implementations behind a unified interface, the API allows you to write your ray tracing code once, and have it automatically adapt to the appropriate backend.
## Main concepts
The API entry point is the [`RayTracingContext`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext) which is initialized for a specific backend.
The [`RayTracingContext`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext) enables you to create the 2 essential objects you need to perform ray tracing:
- an acceleration structure ([`IRayTracingAccelStruct`]((xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct))) which represents the geometry to trace rays against.
- a shader ([`IRayTracingShader`]((xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingShader))) which contains your ray tracing code that will run on the GPU.
![RayTracingContext class features](../Images/RayTracingContext.jpg)
For more information, refer to [Using the API workflow](workflow.md).
## Limitations
In order to accomodate both hardware-accelerated and non-accelerated GPUs, the API is more constrained than Unity's [`RayTracingAccelerationStructure` API](xref:UnityEngine.Rendering.RayTracingAccelerationStructure).
- The API doesn't support any automatic scene updates. You must explicitly call [`IRayTracingAccelStruct.AddInstance`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct.AddInstance(UnityEngine.Rendering.UnifiedRayTracing.MeshInstanceDesc)) or
[`IRayTracingAccelStruct.RemoveInstance`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct.RemoveInstance(System.Int32)) to update the acceleration structure.
- The API supports only ray tracing with mesh geometries.
- Once a hit is found, the `TraceRay` function returns immediately with the hit information. You need to write the shading code in the ray generation shader (`.urtshader`).
@@ -0,0 +1,26 @@
# Release your ray tracing objects
You must free up the memory your ray tracing objects use after you finish with them.
Dispose of the following:
- Scratch buffers. Use [`GraphicsBuffer.Dispose`](xref:UnityEngine.GraphicsBuffer.Dispose()) after you've executed the final command buffer.
- Ray tracing acceleration structures. Use [`IRayTracingAccelStruct.Dispose`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct.Dispose()) after you've executed the final command buffer.
- Ray tracing context. Use [`RayTracingContext.Dispose`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext.Dispose()) after you dispose of all its acceleration structures.
**Note**: Unity automatically disposes of [`RayTracingResources`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingResources) and [`IRayTracingShader`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingShader).
For example:
```C#
RayTracingContext rtContext = new RayTracingContext(rtResources);
IRayTracingShader rtShader = rtContext.LoadRayTracingShader("Assets/yourShader.urtshader");
IRayTracingAccelStruct rtAccelStruct = rtContext.CreateAccelerationStructure(new AccelerationStructureOptions());
GraphicsBuffer rtScratchBuffer = RayTracingHelper.CreateScratchBufferForBuild(rtAccelStruct);
// ... create and dispatch your ray tracing command buffers ...
rtScratchBuffer.Dispose();
rtAccelStruct.Dispose();
rtContext.Dispose();
```
@@ -0,0 +1,74 @@
# Unified ray tracing shader code reference
This section presents the different functions and structs provided by the API for tracing rays in a shader.
All types are defined inside the `UnifiedRT` namespace. In your code, you need to prefix them with ```UnifiedRT::```. Alternatively, you can add ```using namespace UnifiedRT;``` after your `TraceRayAndQueryHit.hlsl` include statement.
## function TraceRayClosestHit
```HLSL
Hit TraceRayClosestHit(DispatchInfo dispatchInfo, RayTracingAccelStruct accelStruct, uint instanceMask, Ray ray, uint rayFlags)
```
Searches for intersections between a ray and an acceleration structure. It returns hit information about the closest triangle encountered along the ray.
### Parameters
|Type|Name|Description|
|-|-|-|
|[`DispatchInfo`](#struct-dispatchinfo)|*dispatchInfo*|The dispatch info. Must be the value that is passed by `RayGenExecute`.|
|`RayTracingAccelStruct`|*accelStruct*|The acceleration structure to test the ray against.|
|`uint`|*instanceMask*|The lower 8 bits of this mask are used to include geometry instances based on the instance mask that was set in `MeshInstanceDesc` for each instance.|
|[`Ray`](#struct-ray)|*ray*|Describes the ray segment that is intersected against the acceleration structure.|
|`uint`|*rayFlags*|Flags that filter out the triangles that participate in the intersection test. Can be one of the following: <ul><li>kRayFlagNone</li><li>kRayFlagCullBackFacingTriangles</li><li>kRayFlagCullFrontFacingTriangles</li> </ul>|
### Returns
[`Hit`](#struct-hit) containing geometry information about the hit triangle. When no primitive has intersected with the ray, `hit.IsValid()` returns false.
## function TraceRayAnyHit
```HLSL
bool TraceRayAnyHit(DispatchInfo dispatchInfo, RayTracingAccelStruct accelStruct, uint instanceMask, Ray ray, uint rayFlags)
```
Searches for any intersection between a ray and an acceleration structure. The search ends as soon as a valid triangle hit is found. This function can typically be used to trace shadow rays or perform occlusion queries.
### Parameters
|Type|Name|Description|
|-|-|-|
|[`DispatchInfo`](#struct-dispatchinfo)|*dispatchInfo*|The dispatch info. Must be the value that is passed by `RayGenExecute`.|
|`RayTracingAccelStruct`|*accelStruct*|The acceleration structure to test the ray against.|
|`uint`|*instanceMask*|The lower 8 bits of this mask are used to include geometry instances based on the instance mask that was set in `MeshInstanceDesc` for each instance.|
|[`Ray`](#struct-ray)|*ray*|Describes the ray segment that is intersected against the acceleration structure.|
|`uint`|*rayFlags*|Flags that filter out the triangles that participate in the intersection test. Can be one of the following: <ul><li>kRayFlagNone</li><li>kRayFlagCullBackFacingTriangles</li><li>kRayFlagCullFrontFacingTriangles</li> </ul>|
### Returns
A boolean that is true if any primitive was hit by the ray.
## struct Ray
Describes a ray.
The `tMin` and `tMax` fields define the segment of the ray to be tested against the acceleration structures's primitives.
Mathematically, the ray consists of all the points defined as `P = ray.origin + t * ray.direction`, where `ray.tMin ≤ t ≤ ray.tMax`.
### Fields
|Type|Name|Description|
|-|-|-|
|`float3`|*origin*|The ray's origin.|
|`float3`|*direction*|The ray's direction.|
|`float`|*tMin*|The ray's starting point.|
|`float`|*tMax*|The ray's endpoint.|
## struct DispatchInfo
Provides information about the current thread that is invoked.
### Fields
|Type|Name|Description|
|-|-|-|
|`uint3`|*dispatchThreadID*|Same semantic as `SV_DispatchThreadID`.|
|`uint`|*localThreadIndex*|Same semantic as `SV_GroupIndex`.|
|`uint3`|*dispatchDimensionsInThreads*|Total numbers of threads dispatched in the X, Y, and Z workgrid directions.|
|`uint`|*globalThreadIndex*|Global thread index that is unique within the workgrid.|
## struct Hit
Describes a Hit.
### Fields
|Type|Name|Description|
|-|-|-|
|`uint`|*instanceID*|Matches the `instanceID` supplied from C# in `MeshInstanceDesc.instanceID`.|
|`uint`|*primitiveIndex*|Index of the hit triangle in its source Mesh.|
|`float2`|*uvBarycentrics*|Barycentric coordinates of the hit triangle.|
|`float`|*hitDistance*|Defines the hit position: `hitPos = ray.origin + ray.direction * hit.hitDistance`.|
|`bool`|*isFrontFace*|Indicates whether the hit triangle is front-facing or back-facing.|
### Methods
```HLSL
bool IsValid();
```
Returns true when a hit has been found. When a hit is invalid `hit.instanceID` is equal to `~0` and the other fields are undefined.
@@ -0,0 +1,161 @@
# Sample code: Tracing camera rays
This section demonstrates how to use the API to cast rays from the scene's Main camera and output the results into a `RenderTexture`, providing the complete code for implementation.
![Example of output texture for a scene with a simple cube](../Images/ExampleOutputTexture.png)
Save the following code in your **Assets** folder as a file named `shootCameraRays.urtshader`:
```HLSL
// Include file for the UnifiedRayTracing API functions
#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/TraceRayAndQueryHit.hlsl"
// Use this macro to declare the acceleration structure binding
UNIFIED_RT_DECLARE_ACCEL_STRUCT(_AccelStruct);
uint _RenderWidth;
uint _RenderHeight;
float4 _CameraFrustum;
float4x4 _CameraToWorldMatrix;
RWTexture2D<float4> _OutputTexture;
UnifiedRT::Ray GenerateFrustumRay(float2 frameCoord, uint2 resolution)
{
float2 ndcCoords01 = (frameCoord + 0.5) / float2(resolution);
float3 viewDirection = float3(
lerp(_CameraFrustum.x, _CameraFrustum.y, ndcCoords01.x),
lerp(_CameraFrustum.z, _CameraFrustum.w, ndcCoords01.y),
-1.0);
UnifiedRT::Ray ray;
ray.origin = transpose(_CameraToWorldMatrix)[3].xyz;
ray.direction = mul((float3x3) _CameraToWorldMatrix, normalize(viewDirection));
ray.tMin = 0.0f;
ray.tMax = 100000.0f;
return ray;
}
// Entry point of the shader. DispatchInfo provides the current thread index in the dispatch
void RayGenExecute(UnifiedRT::DispatchInfo dispatchInfo)
{
UnifiedRT::Ray ray = GenerateFrustumRay(dispatchInfo.dispatchThreadID.xy, uint2(_RenderWidth, _RenderHeight));
// Retrieve the acceleration structure
UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(_AccelStruct);
// Trace a ray in the acceleration structure
UnifiedRT::Hit hitResult = UnifiedRT::TraceRayClosestHit(dispatchInfo, accelStruct, 0xFFFFFFFF, ray, UnifiedRT::kRayFlagNone);
float2 uv = hitResult.uvBarycentrics;
// display the hit triangle barycentrics coordinates as an RGB color
float3 color = hitResult.IsValid() ? float3(uv.x, uv.y, 1.0 - uv.x - uv.y) : 0.0;
_OutputTexture[dispatchInfo.dispatchThreadID.xy] = float4(color, 1.0);
}
```
The following C# MonoBehaviour is responsible for creating the acceleration structure, loading the ray tracing shader and dispatching it to the GPU.
Save it as a script file in your **Assets** folder and attach it to one of your scene GameObjects.
```C#
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
public class ShootCameraRays : MonoBehaviour
{
RayTracingResources m_RtResources;
RayTracingContext m_RtContext;
IRayTracingShader m_RtShader;
IRayTracingAccelStruct m_RtAccelStruct;
// Ray tracing results are written to this texture
const int width = 1024;
const int height = 576;
public RenderTexture OutputTexture;
void Start()
{
var renderTexDesc = new RenderTextureDescriptor(width, height);
renderTexDesc.graphicsFormat = UnityEngine.Experimental.Rendering.GraphicsFormat.R8G8B8A8_SRGB;
renderTexDesc.enableRandomWrite = true;
OutputTexture = new RenderTexture(renderTexDesc);
m_RtResources = new RayTracingResources();
m_RtResources.Load();
// Create the RayTracingContext
var backend = RayTracingContext.IsBackendSupported(RayTracingBackend.Hardware) ? RayTracingBackend.Hardware : RayTracingBackend.Compute;
m_RtContext = new RayTracingContext(backend, m_RtResources);
// Load the unified ray tracing shader
m_RtShader = m_RtContext.LoadRayTracingShader("Assets/shootCameraRays.urtshader");
// Create the ray tracing acceleration structure
m_RtAccelStruct = m_RtContext.CreateAccelerationStructure(new AccelerationStructureOptions());
// Add an instance to the acceleration structure for each MeshRenderer in the current scene
uint instanceID = 0;
var meshRenderers = UnityEngine.Object.FindObjectsByType<MeshRenderer>(FindObjectsSortMode.None);
foreach (var renderer in meshRenderers)
{
var mesh = renderer.GetComponent<MeshFilter>().sharedMesh;
int subMeshCount = mesh.subMeshCount;
for (int i = 0; i < subMeshCount; ++i)
{
var instanceDesc = new MeshInstanceDesc(mesh, i);
instanceDesc.localToWorldMatrix = renderer.transform.localToWorldMatrix;
instanceDesc.instanceID = instanceID++;
m_RtAccelStruct.AddInstance(instanceDesc);
}
}
}
void OnDestroy()
{
m_RtAccelStruct.Dispose();
m_RtContext.Dispose();
OutputTexture?.Release();
}
void Update()
{
// A scratch buffer is required to build the acceleration structure and for the ray traversal, this helper function allocates one with the required size.
GraphicsBuffer scratchBuffer = RayTracingHelper.CreateScratchBufferForBuildAndDispatch(m_RtAccelStruct, m_RtShader, width, height, 1);
var cmd = new CommandBuffer();
// build the ray tracing acceleration structure
m_RtAccelStruct.Build(cmd, scratchBuffer);
// bind the shader gpu resources
m_RtShader.SetAccelerationStructure(cmd, "_AccelStruct", m_RtAccelStruct);
m_RtShader.SetIntParam(cmd, Shader.PropertyToID("_RenderWidth"), width);
m_RtShader.SetIntParam(cmd, Shader.PropertyToID("_RenderHeight"), height);
m_RtShader.SetVectorParam(cmd, Shader.PropertyToID("_CameraFrustum"), GetCameraFrustum(Camera.main));
m_RtShader.SetMatrixParam(cmd, Shader.PropertyToID("_CameraToWorldMatrix"), Camera.main.cameraToWorldMatrix);
m_RtShader.SetTextureParam(cmd, Shader.PropertyToID("_OutputTexture"), OutputTexture);
// dispatch rays. Workgrid dimensions are supplied in threads, not workgroups
m_RtShader.Dispatch(cmd, scratchBuffer, width, height, 1);
Graphics.ExecuteCommandBuffer(cmd);
scratchBuffer?.Dispose();
}
// utility function to extract a frustum from a camera
Vector4 GetCameraFrustum(Camera camera)
{
Vector3[] frustumCorners = new Vector3[4];
camera.CalculateFrustumCorners(new Rect(0, 0, 1, 1), 1.0f, Camera.MonoOrStereoscopicEye.Mono, frustumCorners);
float left = frustumCorners[0].x;
float right = frustumCorners[2].x;
float bottom = frustumCorners[0].y;
float top = frustumCorners[2].y;
return new Vector4(left, right, bottom, top);
}
}
```
You can now enter Play mode and visualize the ray tracing results. Follow these steps:
1. Select the GameObject you attached the `ShootCameraRays` MonoBehaviour to.
2. In the **Inspector** window, go to the **ShootCameraRays** component and double-click **Output Texture**.
3. The Inspector now displays a preview of the render texture containing the ray tracing results.
@@ -0,0 +1,15 @@
# Ray tracing with the UnifiedRayTracing API
The `UnifiedRayTracing` API enables you to write ray tracing code that can execute on a wide range of GPUs. It leverages hardware ray tracing acceleration on supported GPUs, while providing a compute shader-based software fallback for those that do not.
|Section|Description|
|-|-|
|[Get started with ray tracing](get-started.md)|Learn the essential information about the API.|
|[Ray tracing workflow](workflow.md)|Create a ray tracing context, and create and execute a ray tracing shader.|
|[Create the ray tracing context](create-ray-tracing-context.md)|How to create the API entry point.|
|[Create an acceleration structure](create-acceleration-structure.md)|Create and initialize an acceleration structure describing your geometry.|
|[Create a unified ray tracing shader](create-shader.md)|Create a unified ray tracing shader file.|
|[Write your shader code](write-shader.md)|Write the ray tracing logic in your a unified ray tracing shader file.|
|[Execute your ray tracing code](execute-shader.md)|How to execute your ray tracing shader.|
|[Sample code](trace-camera-rays-full-sample.md)|Complete code example showcasing tracing rays from the scene's camera.|
|[Unified ray tracing shader code reference](shader-code-reference.md)|API reference for the unified ray tracing shader code.|
|[Release your ray tracing objects](release-resources.md)|Learn how to release your ray tracing resources.|
@@ -0,0 +1,58 @@
# Ray tracing workflow
To use the API to trace rays in Unity, follow these steps:
1. Create the ray tracing context.
2. Create an acceleration structure.
3. Create a shader.
4. Build your acceleration structure.
5. Execute your shader.
6. Dispose of your objects.
## Create the ray tracing context
The context serves as the API entry point. Create it using the following parameters:
1. `backend`: The chosen backend, which can be either `Hardware` or `Compute`.
2. `resources`: A collection of assets required by the context to function.
```C#
var rtContext = new RayTracingContext(backend, rtResources);
```
For more information, refer to [Create the ray tracing Context](create-ray-tracing-context.md).
## Create an acceleration structure
The acceleration structure is the data structure used to represent a collection of instances and geometries that are used for GPU ray tracing.
```C#
IRayTracingAccelStruct rtAccelStruct = rtContext.CreateAccelerationStructure(options);
```
After creating the structure, populate it with mesh instances using the [`AddInstance`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct.AddInstance(UnityEngine.Rendering.UnifiedRayTracing.MeshInstanceDesc)) method.
For more information, refer to [Create an acceleration structure](create-acceleration-structure.md).
## Create a unified ray tracing shader
Depending on the chosen backend, the `RayTracingContext` runs either a `ComputeShader` or a `RayTracingShader`. The API introduces the unified ray tracing shader (`.urtshader`), which is a shader type that generates both variants for you.
```C#
IRayTracingShader rtShader = rtContext.LoadRayTracingShader("Assets/yourShader.urtshader");
```
For more information, refer to [Create a unified ray tracing shader](create-shader.md).
## Build your acceleration structure
Whenever it is modified or used for the first time, the acceleration structure needs to be built or rebuilt. This can be achieved with the following code:
```C#
rtAccelStruct.Build(cmd, buildScratchBuffer);
```
For more information, refer to [Execute your ray tracing code](execute-shader.md).
## Execute your shader
To execute your shader, call the [`Dispatch`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingShader.Dispatch(UnityEngine.Rendering.CommandBuffer,UnityEngine.GraphicsBuffer,System.UInt32,System.UInt32,System.UInt32))
method of `IRayTracingShader`.
```C#
rtShader.Dispatch(cmd, traceScratchBuffer, threadCountX, threadCountY, threadCountZ);
```
For more information, refer to [Execute your ray tracing code](execute-shader.md).
## Dispose of your objects
For more information, refer to [Release your ray tracing objects](release-resources.md).
@@ -0,0 +1,95 @@
# Write your ray tracing code
This section guides you through the process of implementing ray tracing logic in a unified ray tracing shader (`.urtshader`).
Follow these steps:
1. Include the UnifiedRayTracing API.
2. Declare the acceleration structure.
3. Define the ray generation function.
4. Define a ray.
5. Retrieve the acceleration structure.
6. Trace the ray.
## Include the UnifiedRayTracing API
At the top of your `.urtshader` add the following statement:
```HLSL
#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/TraceRayAndQueryHit.hlsl"
```
## Declare the acceleration structure
Declare the acceleration structure binding with the following macro:
```HLSL
UNIFIED_RT_DECLARE_ACCEL_STRUCT(_YourAccelStruct);
```
Ensure that the name you declare here matches the one specified in your C# code when calling [`IRayTracingShader.SetAccelerationStructure`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingShader.SetAccelerationStructure(UnityEngine.Rendering.CommandBuffer,System.String,UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct)).
**Note**: You can declare and use multiple acceleration structures within the same shader.
## Define the ray generation function
This is your kernel function that will be invoked by the GPU for each thread of your dispatch workgrid. It must be defined as follows:
```HLSL
void RayGenExecute(UnifiedRT::DispatchInfo dispatchInfo)
{
}
```
The [`DispatchInfo`](shader-code-reference.md#struct-dispatchinfo) struct provides information about the currently invoked thread. For instance, you can query its location within the workgrid using:
```HLSL
uint3 threadID = dispatchInfo.dispatchThreadID;
```
At this point, you have a valid `.urtshader` file. The next steps involve implementing the ray tracing logic.
## Define a ray
Use the `Ray` struct to define a ray. For example, here is a ray starting at the origin and pointing towards the positive Z-axis:
```HLSL
UnifiedRT::Ray ray;
ray.origin = 0;
ray.direction = float3(0, 0, 1);
ray.tMin = 0;
ray.tMax = 1000.0f;
```
The `tMin` and `tMax` fields define the segment of the ray to be tested against the acceleration structure's primitives.
In mathematical terms, the ray consists of all the points defined as `P = ray.origin + t * ray.direction` where `ray.tMin ≤ t ≤ ray.tMax`.
## Retrieve the acceleration structure
This is achieved with the following macro:
```HLSL
UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(_YourAccelStruct);
```
## Trace the ray
Invoke one of the following functions that perform ray tracing: [`TraceRayClosestHit`](shader-code-reference.md#function-tracerayclosesthit) or [`TraceRayAnyHit`](shader-code-reference.md#function-tracerayanyhit).
```HLSL
UnifiedRT::Hit hitResult = UnifiedRT::TraceRayClosestHit(dispatchInfo, accelStruct, 0xFFFFFFFF, ray, 0);
```
The returned [`Hit`](shader-code-reference.md#struct-hit) structure provides geometry information about the found intersection such as the instance ID or the triangle index.
Use `hitResult.IsValid()` to check whether a hit has been found.
## Full shader code example
Here is a complete example of a unified ray tracing shader:
```HLSL
// Include file for the UnifiedRayTracing API functions
#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/TraceRayAndQueryHit.hlsl"
// Use this macro to declare the acceleration structure binding
UNIFIED_RT_DECLARE_ACCEL_STRUCT(_AccelStruct);
void RayGenExecute(UnifiedRT::DispatchInfo dispatchInfo)
{
UnifiedRT::Ray ray;
ray.origin = 0;
ray.direction = float3(0, 0, 1);
ray.tMin = 0;
ray.tMax = 1000.0f;
UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(_AccelStruct);
UnifiedRT::Hit hitResult = UnifiedRT::TraceRayClosestHit(dispatchInfo, accelStruct, 0xFFFFFFFF, ray, 0);
if (hitResult.IsValid())
{
// Handle found intersection
}
}
```
When you create a unified ray tracing shader, Unity prefills the shader with a similar code template.
## Additional resources
- [Create a unified ray tracing shader](create-shader.md)
- [Ray tracing shader code reference](shader-code-reference.md)
@@ -0,0 +1,94 @@
# Render Requests
You can use a render request in a C# script to trigger a Camera to render to a render texture, outside the Unity rendering loop.
The request is processed sequentially in your script, so there's no callback involved.
## Use RenderPipeline.StandardRequest
`RenderPipeline.StandardRequest` renders the following:
* A full stack of cameras in the [Universal Render Pipeline](https://docs.unity3d.com/Manual/urp/urp-introduction.html) (URP).
* A single camera in the [High Definition Render Pipeline](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@latest/index.html) (HDRP).
The following code sample gets the output of the scriptable render pipeline when you select a GUI button. Attach the script to a camera and select **Enter Play Mode**.
```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
[RequireComponent(typeof(Camera))]
public class StandardRenderRequest : MonoBehaviour
{
[SerializeField]
RenderTexture texture2D, texture2DArray, cubeMap, texture3D;
// Render requests are sent when GUI button is selected
private void OnGUI()
{
GUILayout.BeginVertical();
if (GUILayout.Button("Render Request"))
{
SendRenderRequests();
}
GUILayout.EndVertical();
}
void SendRenderRequests()
{
Camera cam = GetComponent<Camera>();
// Create a standard request
RenderPipeline.StandardRequest request = new RenderPipeline.StandardRequest();
// Check if the request is supported by the active render pipeline
if (RenderPipeline.SupportsRenderRequest(cam, request))
{
// Submit the render request to the active render pipeline with different destination textures
// 2D Texture
request.destination = texture2D;
// Render camera and fill texture2D with its view
RenderPipeline.SubmitRenderRequest(cam, request);
// 2D Array Texture
request.destination = texture2DArray;
for (int i = 0; i < texture2DArray.volumeDepth; i++)
{
request.slice = i;
// Render camera and fill slice i of texture2DArray with its view
RenderPipeline.SubmitRenderRequest(cam, request);
}
// Cubemap
var faces = new[] {
CubemapFace.NegativeX, CubemapFace.PositiveX,
CubemapFace.NegativeY, CubemapFace.PositiveY,
CubemapFace.NegativeZ, CubemapFace.PositiveZ
};
request.destination = cubeMap;
foreach (var face in faces)
{
request.face = face;
// Render camera and fill face of cubeMap with its view
RenderPipeline.SubmitRenderRequest(cam, request);
}
// 3D Texture
request.destination = texture3D;
for (int i = 0; i < texture3D.volumeDepth; i++)
{
request.slice = i;
// Render camera and fill slice i of texture3D with its view
RenderPipeline.SubmitRenderRequest(cam, request);
}
}
}
}
```
## Other useful information
* On [Universal Render Pipeline (URP)](https://docs.unity3d.com/Manual/urp/User-Render-Requests.html).
@@ -0,0 +1,41 @@
## Light Anchor
The Light Anchor can help to place light sources around subjects, in relation to a Camera and an anchor point. It's particularly effective for cinematic lighting, which often requires multiple light sources orbiting a subject.
## Using the Light Anchor Component
To add a Light Anchor component to a GameObject in your Scene:
1. Select a Light GameObject in the hierarchy to open its Inspector window.
2. Go to **Add Component** > **Rendering** > **Light Anchor**
By default, the Anchor's position is the same as the position of the GameObject the Light Anchor Component is attached to.
**Note**: To use the Light Anchor, you must set the Tag of at least one Camera to "MainCamera".
Use the **Orbit** and **Elevation** to control the orientation of the light, in degrees, relative to the main Camera's and Anchor's positions. If the Light has a Cookie or an IES Profile, use the **Roll** to change their orientation. Use the **Distance** to control how far from the anchor, in meters, you want to place the Light.
You can use the **Anchor Position Override** to provide a GameObject’s [Transform](https://docs.unity3d.com/ScriptReference/Transform.html) as an anchor point for the Light. This is useful if you want the Light to follow a specific GameObject in the Scene.
<video title="A light uses the main camera as the reference GamObject that controls the rotation of the light. The light rotates synchronously with the camera." src="Images/videos/light-anchor-animation.mp4" width="100%" height="auto" autoplay="true" loop="true" controls></video>
**Note**: The above example uses the Main Camera as the reference Camera that adjusts the light rotation. The Common presets might create a different result in the Scene View if your view isn't aligned with the Main Camera.
You can set a **Position Offset** for this custom Anchor. This is useful if the Transform position of the custom Anchor isn't centered appropriately for the light to orbit correctly around the custom Anchor.
![Light Anchor component screenshot. Orbit and Elevation properties display example values that change the orientation of a light.](Images/LightAnchor0.png)
The Light Anchor component also includes a list of **Presets** that you can use to set the Light's orientation relative to the main Camera.
## Properties
| **Property** | **Description** |
| --------------- | ------------------------------------------------------------ |
| **Orbit** | Use the left icon to control the Orbit of the light. This tool becomes green when you move the icon. |
| **Elevation** | Use the middle icon to control the Elevation of the light. This tool becomes blue when you move the icon. |
| **Roll** | Use the right icon to control the Roll of the light. This tool becomes gray when you move the icon. This is useful if the light has an IES or a Cookie. |
| **Distance** | Controls the distance between the light and its anchor in world space. |
| **Up Direction** | Defines the space of the up direction of the anchor. When you set this value to Local, the Up Direction is relative to the Camera. |
| **Anchor Position Override** | Allows you to use a GameObject's [Transform](https://docs.unity3d.com/ScriptReference/Transform.html) as anchor position instead of the LightAnchor's Transform. When the Transform of the GameObject you assigned to this property changes, the Light Anchor's Transform also changes. |
| **Common** | Assigns a preset to the light component based on the behavior of studio lights. |
@@ -0,0 +1,60 @@
# Add a setting
Add a simple property or a reference property to a [custom graphics settings group](add-custom-graphics-settings.md). You can change the values of the setting in the Unity Editor while you're editing your project.
Unity serializes the graphics settings you add. For more information, refer to [Script serialization](xref:um-script-serialization).
**Note:** The value of a custom setting is static in a built project. You can't change the setting at runtime.
## Add a simple property
To add a simple property, add a field to your `IRenderPipelineGraphicsSettings` class using the `[SerializeField]` attribute. For example:
```c#
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
[Serializable]
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
// Create a new settings group by implementing the IRenderPipelineGraphicsSettings interface
public class MySettings : IRenderPipelineGraphicsSettings
{
// Add a private field for the version property
int internalVersion = 1;
// Implement the public version property
public int version => internalVersion;
// Add a float setting
[SerializeField]
private float mySetting = 1.0f;
// Add a Material reference property
[SerializeField]
public Material myMaterial;
}
```
![Screenshot of the Project Settings window. The Graphics section contains the new custom settings from the example script.](Images/customsettings-addsetting.png)<br/>
The **Edit** > **Project Settings** > **Graphics** window with the new custom setting from the example script.
## Set the default asset for a reference property
To set a default asset for a [reference property](xref:um-editing-value-properties#references), for example a material, add a [`[ResourcePath]`](https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rendering.ResourcePathAttribute.html) attribute. For example:
```c#
public class MySettings: IRenderPipelineGraphicsSettings
{
...
[SerializeField]
[ResourcePath('path-to-default-file')]
public Material myMaterial;
}
```
## Additional resources
- [SerializeField](xref:UnityEngine.SerializeField)
- [Reference properties](xref:EditingValueProperties#references)
@@ -0,0 +1,57 @@
# Add a settings group
To add a custom graphics settings group to a Scriptable Render Pipeline, implement the `IRenderPipelineGraphicsSettings` interface.
Follow these steps:
1. Create a class that implements the `IRenderPipelineGraphicsSettings` interface, then add a `[Serializable]` attribute.
2. To set which render pipeline the setting applies to, add a `[SupportedOnRenderPipeline]` attribute and pass in a `RenderPipelineAsset` type.
**Note:** If you don't add a `[SupportedOnRenderPipeline]` attribute, the setting applies to any Scriptable Render Pipeline. However each Scriptable Render Pipeline stores its own value for the setting.
3. Implement the `version` property. Unity doesn't currently use the `version` property, but you must implement it.
Unity adds the new settings group to the **Edit** > **Project Settings** > **Graphics** window.
For example, the following script adds a settings group called **My Settings** in the **Graphics** settings window of the Universal Render Pipeline (URP).
```c#
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
[Serializable]
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
// Create a new settings group by implementing the IRenderPipelineGraphicsSettings interface
public class MySettings : IRenderPipelineGraphicsSettings
{
// Add a private field for the version property
int internalVersion = 1;
// Implement the public version property
public int version => internalVersion;
}
```
![Screenshot of the Project Settings window. The Graphics section contains the new custom settings group from the example script.](Images/customsettings-settingsgroup.png)<br/>
The **Edit** > **Project Settings** > **Graphics** window with the new custom settings group from the example script.
## Change the display order of settings groups
To change where a settings group appears, use the `[UnityEngine.Categorization.CategoryInfo]` attribute. For example, the following code gives the settings group the name **My Settings** and moves the group to the top of the graphics settings window.
```c#
[UnityEngine.Categorization.CategoryInfo(Name = "My Settings", Order = 0)]
public class MySettings : IRenderPipelineGraphicsSettings
{
...
}
```
## Additional resources
- [Add a setting](add-custom-graphics-setting.md)
@@ -0,0 +1,33 @@
# Adding properties to the Core Render Pipeline settings section
To add properties in the **Core Render Pipeline** settings section (**Edit > Preferences > Core Render Pipeline**), create a class that implements the interface `ICoreRenderPipelinePreferencesProvider`.
For example:
```
class MyPreference : ICoreRenderPipelinePreferencesProvider
{
class Styles
{
public static readonly GUIContent myBoolLabel = EditorGUIUtility.TrTextContent("My check box", "The description of the property.");
}
public List<string> keywords => new List<string>() {Styles.myBoolLabel.text};
public GUIContent header => EditorGUIUtility.TrTextContent("My property section", "The description of my property section.");
public static bool s_MyBoolPreference;
public void PreferenceGUI()
{
EditorGUI.BeginChangeCheck();
var newValue = EditorGUILayout.Toggle(Styles.myBoolLabel, s_MyBoolPreference);
if (EditorGUI.EndChangeCheck())
{
s_MyBoolPreference = newValue;
}
}
}
```
Unity shows the new properties in the **Core Render Pipeline** settings section:
![Screenshot of the Preferences window showing the new properties in the Core Render Pipeline settings section.](Images/core_render_pipeline_preference_provider.png)
@@ -0,0 +1,40 @@
---
uid: um-srp-advanced-properties
---
# Advanced Properties
Unity Render Pipelines components expose standard properties by default that are suitable for most use-cases.
However, there are components and Volume Overrides that include **advanced properties** which you can use to fine-tune the behavior of the component.
There is a global state per user that stores if Unity displays **advanced properties** or not.
## Exposing advanced properties within the inspector
Not every component or Volume Override includes advanced properties.
If one does, it has a contextual menu to the right of each property section header that includes additional properties. To expose advanced properties for that section, open the contextual menu and click **Show All Advanced Properties**.
For an example, refer to the **Water Surface** component in [High Definition Render Pipeline (HDRP)](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@latest?subfolder=/manual/settings-and-properties-related-to-the-water-system.html).
By default only standard properties are shown.
![](Images/Preferences/HDRP_WaterSurface_General.png)
When you select **Show All Advanced Properties**:
![](Images/Preferences/PopUpAdvanced.png)
**Advanced Properties** become visible:
![](Images/Preferences/HDRP_WaterSurface_General_Visible.png)
For Volume Overrides, the already existing contextual menu has a **Show All Advanced Properties** toggle as well.
## Exposing advanced properties on preferences
You can also access to this global preference by:
1. Open the **Graphics** tab in the **Preferences** window (menu: **Edit > Preferences**, macOS: **Unity > Settings**).
2. Under **Graphics**, select **Properties**. Set **Advanced Properties** to **All Visible**.
![](Images/Preferences/AdvancedProperties_Settings.png)
@@ -0,0 +1,12 @@
---
uid: srp-core-api-index
---
# Scriptable Render Pipeline Core scripting API
This is the documentation for the scripting APIs of the Scriptable Render Pipeline (SRP) Core package.
**Note**: URP and HDRP are built on the Scriptable Render Pipeline (SRP) Core package, but have their own class types. For more information, refer to the following:
- [Universal Render Pipeline (URP) Scripting API](https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.3/api/index.html)
- [High Definition Render Pipeline (HDRP) Scripting API](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@17.3/api/index.html)
@@ -0,0 +1,60 @@
# Use shader methods from the SRP Core shader library
SRP Core has a library of High-Level Shader Language (HLSL) shader files that contain helper methods. You can import these files into your custom shader files and use the helper methods.
To use the following methods, add `#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl"` inside the `HLSLPROGRAM` in your shader file.
### Get matrices
| **Method** | **Syntax** | **Description** |
|-|-|-|
| `CreateTangentToWorld` | `real3x3 CreateTangentToWorld(real3 normal, real3 tangent, real flipSign)` | Returns the matrix that converts tangents to world space. |
| `GetObjectToWorldMatrix()` | `float4x4 GetObjectToWorldMatrix()` | Returns the matrix that converts positions in object space to world space. |
| `GetViewToHClipMatrix()` | `float4x4 GetViewToHClipMatrix()` | Returns the matrix that converts positions in view space to clip space. |
| `GetViewToWorldMatrix()` | `float4x4 GetViewToWorldMatrix()` | Returns the matrix that converts positions in view space to world space. |
| `GetWorldToHClipMatrix()` | `float4x4 GetWorldToHClipMatrix()` | Returns the matrix that converts positions in world space to clip space. |
| `GetWorldToObjectMatrix()` | `float4x4 GetWorldToObjectMatrix()` | Returns the matrix that converts positions in world space to object space. |
| `GetWorldToViewMatrix()` | `float4x4 GetWorldToViewMatrix()` | Returns the matrix that converts positions in world space to view space. |
### Transform positions
| **Method** | **Syntax** | **Description** |
|-|-|-|
| `TransformObjectToHClip` | `float4 TransformObjectToHClip(float3 positionInObjectSpace)` | Converts a position in object space to clip space. |
| `TransformObjectToWorld` | `float3 TransformObjectToWorld(float3 positionInObjectSpace)` | Converts a position in object space to world space. |
| `TransformViewToWorld` | `float3 TransformViewToWorld(float3 positionInViewSpace)` | Converts a position in view space to world space. |
| `TransformWorldToHClip` | `float4 TransformWorldToHClip(float3 positionInWorldSpace)` | Converts a position in world space to clip space. |
| `TransformWorldToObject` | `float3 TransformWorldToObject(float3 positionInWorldSpace)` | Converts a position in world space to object space. |
| `TransformWorldToView` | `float3 TransformWorldToView(float3 positionInWorldSpace)` | Converts a position in world space to view space. |
| `TransformWViewToHClip` | `float4 TransformWViewToHClip(float3 positionInViewSpace)` | Converts a position in view space to clip space. |
### Transform directions
| **Method** | **Syntax** | **Description** |
|-|-|-|
| `TransformObjectToTangent` | `real3 TransformObjectToTangent(real3 directionInObjectSpace, real3x3 tangentToWorldMatrix)` | Converts a direction in object space to tangent space, using a tangent-to-world matrix. |
| `TransformObjectToWorldDir` | `float3 TransformObjectToWorldDir(float3 directionInObjectSpace, bool normalize = true)` | Converts a direction in object space to world space. |
| `TransformTangentToObject` | `real3 TransformTangentToObject(real3 dirTS, real3x3 tangentToWorldMatrix)` | Converts a direction in tangent space to object space, using a tangent-to-world matrix. |
| `TransformTangentToWorldDir` | `real3 TransformTangentToWorldDir(real3 directionInWorldSpace, real3x3 tangentToWorldMatrix, bool normalize = false)` | Converts a direction in tangent space to world space, using a tangent-to-world matrix. |
| `TransformViewToWorldDir` | `real3 TransformViewToWorldDir(real3 directionInViewSpace, bool normalize = false)` | Converts a direction in view space to world space. |
| `TransformWorldToHClipDir` | `real3 TransformWorldToHClipDir(real3 directionInWorldSpace, bool normalize = false)` | Converts a direction in world space to clip space. |
| `TransformWorldToObjectDir` | `float3 TransformWorldToObjectDir(float3 directionInWorldSpace, bool normalize = true)` | Converts a direction in world space to object space. |
| `TransformWorldToTangentDir` | `real3 TransformWorldToTangentDir(real3 directionInWorldSpace, real3x3 tangentToWorldMatrix, bool normalize = false)` | Converts a direction in world space to tangent space, using a tangent-to-world matrix. |
| `TransformWorldToViewDir` | `real3 TransformWorldToViewDir(real3 directionInWorldSpace, bool normalize = false)` | Converts a direction in world space to view space. |
### Transform surface normals
| **Method** | **Syntax** | **Description** |
|-|-|-|
| `TransformObjectToWorldNormal` | `float3 TransformObjectToWorldNormal(float3 normalInObjctSpace, bool normalize = true)` | Converts a normal in object space to world space. |
| `TransformTangentToWorld` | `float3 TransformTangentToWorld(float3 normalInTangentSpace, real3x3 tangentToWorldMatrix, bool normalize = false)` | Converts a normal in tangent space to world space, using a tangent-to-world matrix. |
| `TransformViewToWorldNormal` | `real3 TransformViewToWorldNormal(real3 normalInViewSpace, bool normalize = false)` | Converts a normal in view space to world space. |
| `TransformWorldToObjectNormal` | `float3 TransformWorldToObjectNormal(float3 normalInWorldSpace, bool normalize = true)` | Converts a normal in world space to object space. |
| `TransformWorldToTangent` | `float3 TransformWorldToTangent(float3 normalInWorldSpace, real3x3 tangentToWorldMatrix, bool normalize = true)` | Converts a normal in world space to tangent space using a tangent-to-world matrix. |
| `TransformWorldToViewNormal` | `real3 TransformWorldToViewNormal(real3 normalInWorldSpace, bool normalize = false)` | Converts a normal in world space to view space. |
## Additional resources
- [HLSL in Unity](https://docs.unity3d.com/Manual/SL-ShaderPrograms.html)
@@ -0,0 +1,76 @@
# Include or exclude a setting in your build
By default, Unity doesn't include a setting ("strips" the setting) in your built project to optimize performance and reduce build size. For example, if you create a custom reference property that points to a shader asset, by default Unity doesn't include that property in your build.
You can choose to include a setting in your build instead. The value of the property is read-only at runtime.
## Include a setting in your build
To include a setting in your build by default, set the `IsAvailableInPlayerBuild` property of your [settings group class](add-custom-graphics-settings.md) to `true`.
For example:
```c#
public class MySettings: IRenderPipelineGraphicsSettingsStripper
{
...
// Make settings in this class available in your build
public bool IsAvailableInPlayerBuild => true;
}
```
## Create your own stripping code
To conditionally control whether Unity includes or excludes a setting in your build, override the `IsAvailableInPlayerBuild` property by implementing the `IRenderPipelineGraphicsSettingsStripper` interface.
Follow these steps:
1. Create a class that implements the `IRenderPipelineGraphicsSettingsStripper` interface, and pass in your [settings class](add-custom-graphics-settings.md).
2. Implement the `active` property. If you set `active` to `false`, the code in the class doesn't run.
3. Implement the `CanRemoveSettings` method with your own code that decides whether to include the setting. Return `true` to strip the setting, or `false` to include the setting.
For example:
```c#
using UnityEngine;
using UnityEngine.Rendering;
// Implement the IRenderPipelineGraphicsSettingsStripper interface, and pass in our settings class
class SettingsStripper : IRenderPipelineGraphicsSettingsStripper<MySettings>
{
// Make this stripper active
public bool active => true;
// Implement the CanRemoveSettings method with our own code
public bool CanRemoveSettings(MySettings settings)
{
// Strip the setting (return true) if useMyFeature is false
return !settings.useMyFeature;
}
}
```
If you implement `IRenderPipelineGraphicsSettingsStripper` multiple times for one setting, Unity only strips the setting if they all return `true`.
## Check if your build includes a setting
You can check if a setting exists at runtime. A setting might not exist at runtime for one of the following reasons:
- Unity didn't include the setting in your build.
- The current pipeline doesn't support the setting.
- The setting is in an assembly that Unity doesn't include in your build. Refer to [Organizing scripts into assemblies](xref:um-script-compilation-assembly-definition-files) for more information.
To check if the setting exists, use the `TryGetRenderPipelineSettings` API. `TryGetRenderPipelineSettings` puts the setting in an `out` variable if the setting exists. Otherwise it returns `false`.
For example, the following code checks whether a settings group called `MySettings` exists at runtime:
```c#
if (GraphicsSettings.TryGetRenderPipelineSettings<MySettings>(out var mySetting)){
Debug.Log("The setting is in the build and its value is {mySetting.myValue}");
}
```
## Additional resources
- [Organizing scripts into assemblies](xref:um-script-compilation-assembly-definition-files)
@@ -0,0 +1 @@
{ "DefineConstants": "CORE_PACKAGE_DOCTOOLS" }
@@ -0,0 +1,50 @@
# Custom Material Inspector
Custom Material Inspectors enable you to define how Unity displays properties in the Material Inspector for a particular shader. This is useful if a shader includes a lot of properties and you want to organize them in the Inspector. The Universal Render Pipeline (URP) and High Definition Render Pipeline (HDRP) both support custom Material Inspectors, but the method to create them is slightly different.
## Creating a custom Material Inspector
The implementation for custom Material Inspectors differs between URP and HDRP. For example, for compatibility purposes, every custom Material Inspector in HDRP must inherit from `HDShaderGUI` which does not exist in URP. For information on how to create custom Material Inspectors for the respective render pipelines, see:
- **HDRP**: [HDRP custom Material Inspectors](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@latest?subfolder=/manual/custom-material-inspectors.html).
- **URP**: [Unity Custom Shader GUI](https://docs.unity3d.com/Manual/SL-CustomShaderGUI.html).
## Assigning a custom Material Inspector
When you create a shader, either hand-written or using Shader Graph, both URP and HDRP provide a default editor for it to use. To override this default and provide your own custom Material Inspector, the method differs depending on whether you hand-wrote the shader or used Shader Graph.
### Using hand-written shaders
To set a custom Material Inspector for a hand-written shader:
1. Open the shader source file.
2. Assign a string that contains the class name of the custom Material Inspector to the **CustomEditor** shader instruction.
This is the same method as for the Built-in Renderer's [custom shader GUI](<https://docs.unity3d.com/Manual/SL-CustomShaderGUI.html>).
For an example of how to do this, see the following shader code sample. In this example, the name of the custom Material Inspector class is **ExampleCustomMaterialInspector**:
```c#
Shader "Custom/Example"
{
Properties
{
// Shader properties
}
SubShader
{
// Shader code
}
CustomEditor "ExampleCustomMaterialInspector"
}
```
### Using Shader Graph
To set a custom Material Inspector for a Shader Graph shader:
1. Open the Shader Graph.
2. In the [Graph Inspector](<https://docs.unity3d.com/Packages/com.unity.shadergraph@latest?subfolder=/manual/Internal-Inspector.html>), open the Graph Settings tab.
3. If **Active Targets** does not include the render pipeline your project uses, click the **plus** button then, in the drop-down, click the render pipeline.
4. In the render pipeline section (**HDRP** or **URP** depending on the render pipeline your project uses) find the **Custom Editor GUI** property and provide it the name of the custom Material Inspector.
@@ -0,0 +1,78 @@
# Customize the UI of custom settings
To change the look of custom settings in the **Graphics** settings window, use the `PropertyDrawer` API.
Follow these steps:
1. Create a class that inherits from the [`PropertyDrawer`](xref:UnityEditor.PropertyDrawer) class.
2. Add the `[CustomPropertyDrawer]` attribute to the class, with a reference to your settings class.
3. Override the `PropertyDrawer.CreatePropertyGUI` method, and return a `VisualElement` object that contains the UI elements you want to display.
The following example creates a custom UI for a `MySettings` class that contains a Boolean and a float field. The Graphics settings window displays the float only when the Boolean field is enabled.
For more information, refer to [PropertyDrawer](xref:UnityEditor.PropertyDrawer).
```c#
using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;
// Create a custom UI for the properties in the MySettings class
[CustomPropertyDrawer(typeof(MySettings))]
public class MySettingsPropertyDrawer : PropertyDrawer
{
// Override the CreatePropertyGUI method to define the custom UI
public override VisualElement CreatePropertyGUI(SerializedProperty property)
{
// Create a container to hold the UI elements
var container = new VisualElement();
// Find the properties to display
var useProperty = property.FindPropertyRelative("m_UseMyFeature");
var intensityProperty = property.FindPropertyRelative("m_MyFeatureIntensity");
// Create property fields for each property
var usePropertyField = new PropertyField(useProperty);
var intensityPropertyField = new PropertyField(intensityProperty);
// Enable or disable the intensity field based on the value of m_UseMyFeature
usePropertyField.RegisterValueChangeCallback(evt =>
{
intensityPropertyField.SetEnabled(useProperty.boolValue);
});
// Add the property fields to the container
container.Add(usePropertyField);
container.Add(intensityPropertyField);
// Return the container to be displayed in the Graphics settings window
return container;
}
}
```
## Customize the More (⋮) menu of a settings group
To add items to the **More** (⋮) menu of a settings group, follow these steps:
1. Create a class that implements the [`IRenderPipelineGraphicsSettingsContextMenu2<T>`](https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rendering.IRenderPipelineGraphicsSettingsContextMenu2_1.html) interface.
2. Implement the `PopulateContextMenu` method.
3. To add an item, use the `AddItem` API.
For example:
```c#
public class MySettingsContextMenu : IRenderPipelineGraphicsSettingsContextMenu2<MySettings>
{
void IRenderPipelineGraphicsSettingsContextMenu2<MySettings>.PopulateContextMenu(MySettings setting, SerializedProperty _, ref GenericMenu menu)
{
menu.AddItem(new GUIContent("My custom menu item"), false, () => { Debug.Log("Menu item was selected."); });
}
}
```
## Additional resources
- [PropertyDrawer](xref:UnityEditor.PropertyDrawer)
- [IRenderPipelineGraphicsSettingsContextMenu2](https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Rendering.IRenderPipelineGraphicsSettingsContextMenu2.html)
- [IRenderPipelineGraphicsSettingsContextMenu2<T>](https://docs.unity3d.com/6000.2/Documentation/ScriptReference/Rendering.IRenderPipelineGraphicsSettingsContextMenu2_1.html)
@@ -0,0 +1,44 @@
# Synchronizing shader code and C#
Unity can generate HLSL code based on C# structs to synchronize data and constants between shaders and C#. In Unity, the process of generating the HLSL code from C# code is called generating shader includes. When Unity generates shader includes, it parses all the C# files in the project and, for every file that contains a struct with a GenerateHLSL attribute, generates corresponding HLSL code. It places this HLSL code in a file with the same name as the origin, but uses the `.cs.hlsl` file extension.
## Generating shader includes
To generate an HLSL equivalent for a C# struct:
1. Add the GenerateHLSL attribute to the struct. To do this, above the line that declares the struct, add `[GenerateHLSL(PackingRules.Exact, false)]`. For an example on how to do this, see the sample code below. For more information about the GenerateHLSL attribute, see the [API documentation](../api/UnityEngine.Rendering.GenerateHLSL.html).
2. In the Unity Editor, go to **Edit** > **Render Pipeline** > **Generate Shader Includes**.
The following code example is from the High Definition Render Pipeline (HDRP). It shows an extract of the C# representation of a directional light. The original file is `LightDefinition.cs`. When Unity generates the HLSL shader code, it places it in a new file called `LightDefinition.cs.hlsl`.
```
// LightDefinition.cs
[GenerateHLSL(PackingRules.Exact, false)]
struct DirectionalLightData
{
public Vector3 positionRWS;
public uint lightLayers;
public float lightDimmer;
public float volumetricLightDimmer; // Replaces 'lightDimer'
public Vector3 forward;
public Vector4 surfaceTextureScaleOffset;
};
```
```
// LightDefinition.cs.hlsl
// Generated from UnityEngine.Rendering.HighDefinition.DirectionalLightData
// PackingRules = Exact
struct DirectionalLightData
{
float3 positionRWS;
uint lightLayers;
float lightDimmer;
float volumetricLightDimmer;
float3 forward;
float4 surfaceTextureScaleOffset;
};
```
@@ -0,0 +1,102 @@
# Get custom graphics settings
To get a custom setting and read its value, use the `GetRenderPipelineSettings` method.
For example, the following script gets the `MySettings` settings class from the example in the [Add a setting](add-custom-graphics-setting.md) page, then logs the value of the `mySetting` setting:
```c#
using UnityEngine;
using UnityEngine.Rendering;
public class LogMySettingsValue : MonoBehaviour
{
// Unity calls the Update method once per frame
void Update()
{
// Get the MySettings settings
var mySettings = GraphicsSettings.GetRenderPipelineSettings<MySettings>();
// Log the value of the MyValue setting
Debug.Log(mySettings.mySetting);
}
}
```
## Get a notification when a setting changes
To configure a property so it notifies other scripts when its value changes, use the `SetValueAndNotify` method. You can use this to debug, update UI elements, or trigger other actions when a setting changes.
This only works while you're editing your project, not at runtime. If you use `SetValueAndModify` in a built application, Unity throws an exception.
Follow these steps:
1. Create a public getter and setter in your setting class.
2. In the setter, set the value using the `SetValueAndNotify` method, so changing the setting value sends a notification to other scripts.
For example:
```c#
using UnityEngine;
using UnityEngine.Rendering;
using System;
[Serializable]
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
// Create a settings group by implementing the IRenderPipelineGraphicsSettings interface
public class MySettings : IRenderPipelineGraphicsSettings
{
// Implement the version field
public int version => 0;
// Create a MyValue setting and set its default value to 100
[SerializeField] private int MyValue = 100;
public int myValue
{
get => MyValue;
set => this.SetValueAndNotify(ref MyValue, value);
}
}
```
3. Use the `GraphicsSettings.Subscribe` method to subscribe to notifications from the setting, and call an `Action` when the setting changes.
For example:
```c#
using System;
using UnityEngine;
using UnityEngine.Rendering;
public class DetectSettingsChange : MonoBehaviour
{
// Unity calls the Awake method when it loads the script instance.
void Awake()
{
// Log the new value of the setting
Action<MySettings, string> onSettingChanged = (setting, name) =>
{
Debug.Log($"{name} changed to {setting.myValue}");
};
// Subscribe to notifications from the MySettings settings, and call the OnSettingsChanged Action when notified
GraphicsSettings.Subscribe<MySettings>(onSettingChanged);
}
}
```
### Unsubscribe from the notifications from a setting
To stop calling a method when a setting changes, use the `GraphicsSettings.Unsubscribe` method. For example:
```c#
GraphicsSettings.Unsubscribe<MySettings>(onSettingChanged);
```
## Additional resources
- [`IRenderPipelineGraphicsSettings`](https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rendering.IRenderPipelineGraphicsSettings.html)
@@ -0,0 +1,139 @@
# Render from another camera inside a camera's rendering loop
Render from cameras nested inside the render loop of other cameras.
Attach the provided script to a GameObject with a Camera component to nest multiple cameras, that are rendering with [RenderPipeline.SubmitRenderRequest](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rendering.RenderPipeline.SubmitRenderRequest.html), inside the render loop of other cameras.
**Note**: If your project uses the [Universal Render Pipeline](https://docs.unity3d.com/Manual/urp/urp-introduction.html) (URP), the recommended best practice is to use [UniversalRenderPipeline.SingleCameraRequest](https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.2/api/UnityEngine.Rendering.Universal.UniversalRenderPipeline.SingleCameraRequest.html) instead of [StandardRequest](https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rendering.RenderPipeline.StandardRequest.html), to make sure you only render the camera provided to the `RenderRequest` API instead of the full stack of cameras.
## Attach the script to nest
Follow these steps:
1. Create a new C# script.
2. Add the `using` statements shown below and the `RequireComponent` attribute with the `Camera` type.
```c#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
[RequireComponent(typeof(Camera))]
public class InLoopRenderRequest : MonoBehaviour
{
}
```
3. Add a property with the type `Camera` to the `InLoopRenderRequest` class.
4. Add a property with the type `RenderTexture` for each callback the camera uses, as shown below:
```c#
[RequireComponent(typeof(Camera))]
public class InLoopRenderRequest : MonoBehaviour
{
public Camera renderRequestCamera;
public RenderTexture onBeginCameraRendering;
public RenderTexture onBeginContextRendering;
public RenderTexture onEndCameraRendering;
public RenderTexture onEndContextRendering;
}
```
## Full code example
The following is an example of the finalized code which you attach to the secondary camera:
```c#
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
[RequireComponent(typeof(Camera))]
public class InLoopRenderRequest : MonoBehaviour
{
// Add a reference to the secondary camera that will render the textures
// It's recommended to disable the secondary camera.
public Camera renderRequestCamera;
// Add references to the Render Textures that will contain the rendered image from the secondary camera.
public RenderTexture onBeginCameraRendering;
public RenderTexture onBeginContextRendering;
public RenderTexture onEndCameraRendering;
public RenderTexture onEndContextRendering;
void OnEnable()
{
// Subscribe to the RenderPipelineManager callbacks
RenderPipelineManager.beginCameraRendering += OnBeginCameraRender;
RenderPipelineManager.beginContextRendering += OnBeginContextRendering;
RenderPipelineManager.endCameraRendering += OnEndCameraRender;
RenderPipelineManager.endContextRendering += OnEndContextRendering;
}
public void OnDisable()
{
// Unsubscribe to the callbacks from RenderPipelineManager when we disable the component
RenderPipelineManager.beginCameraRendering -= OnBeginCameraRender;
RenderPipelineManager.beginContextRendering -= OnBeginContextRendering;
RenderPipelineManager.endCameraRendering -= OnEndCameraRender;
RenderPipelineManager.endContextRendering -= OnEndContextRendering;
}
void SubmitStandardRenderRequest(RenderTexture rt, Camera cam)
{
RenderPipeline.StandardRequest request = new();
// Check that the Scriptable Render Pipeline (SRP) we're using supports the given render data.
if (RenderPipeline.SupportsRenderRequest(cam, request))
{
// Set the request RenderTexture
request.destination = rt;
// Render the camera output to the RenderTexture synchronously
// When this is complete, the RenderTexture in renderTextures[i] contains the scene rendered from the point of view of the secondary cameras
RenderPipeline.SubmitRenderRequest(cam, request);
}
}
// StandardRequest and UniversalRenderPipeline.SingleCameraRequest also trigger RenderPipelineManager callbacks.
// Check that the callbacks are from the GameObject's Camera component to avoid a recursive rendering of the same camera.
private void OnBeginContextRendering(ScriptableRenderContext ctx, List<Camera> cams)
{
if (cams.Contains(GetComponent<Camera>()))
{
SubmitStandardRenderRequest(onBeginContextRendering, renderRequestCamera);
}
}
private void OnEndContextRendering(ScriptableRenderContext ctx, List<Camera> cams)
{
if (cams.Contains(GetComponent<Camera>()))
{
SubmitStandardRenderRequest(onEndContextRendering, renderRequestCamera);
}
}
private void OnBeginCameraRender(ScriptableRenderContext ctx, Camera cam)
{
if (cam == GetComponent<Camera>())
{
SubmitStandardRenderRequest(onBeginCameraRendering, renderRequestCamera);
}
}
private void OnEndCameraRender(ScriptableRenderContext ctx, Camera cam)
{
if (cam == GetComponent<Camera>())
{
SubmitStandardRenderRequest(onEndCameraRendering, renderRequestCamera);
}
}
}
```
## Additional resources
- [Render Requests](User-Render-Requests.md)
- [Creating a custom render pipeline](srp-custom.md)
@@ -0,0 +1,9 @@
# SRP Core
The Scriptable Render Pipeline (SRP) is a Unity feature that allows you to write C# scripts to control the way Unity renders each frame. SRP Core is a package that makes it easier to create or customize an SRP.
SRP Core contains reusable code, including boilerplate code for working with platform-specific graphics APIs, utility functions for common rendering operations, and the shader libraries used in the High Definition Render Pipeline (HDRP) and Universal Render Pipeline (URP).
If you are creating a custom SRP from scratch or customizing a prebuilt SRP, using SRP Core will save you time.
For more information on SRP, including a guide to getting started with a custom SRP, see the [SRP documentation](https://docs.unity3d.com/Manual/ScriptableRenderPipeline.html). For more information on Unity's prebuilt SRPs, see the [Universal Render Pipeline (URP) documentation](https://docs.unity3d.com/Manual/urp/urp-introduction.html), or the [High Definition Render Pipeline (HDRP) documentation](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@latest).
@@ -0,0 +1,58 @@
# Blit using the render graph system in SRP Core
To blit from one texture to another in the render graph system, use the [`AddBlitPass`](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.3/api/UnityEngine.Rendering.RenderGraphModule.Util.RenderGraphUtils.html#UnityEngine_Rendering_RenderGraphModule_Util_RenderGraphUtils_AddBlitPass_UnityEngine_Rendering_RenderGraphModule_RenderGraph_UnityEngine_Rendering_RenderGraphModule_Util_RenderGraphUtils_BlitMaterialParameters_System_String_System_Boolean_) API. The API generates a render pass automatically, so you don't need to use a method like `AddRasterRenderPass`.
Follow these steps:
1. To create a shader and material that works with a blit render pass, from the main menu select **Assets** > **Create** > **Shader** > **SRP Blit Shader**, then create a material from it.
1. Add `using UnityEngine.Rendering.RenderGraphModule.Util` to your render pass script.
1. In your render pass, create a field for the blit material. For example:
```lang-cs
public class MyBlitPass : ScriptableRenderPass
{
Material blitMaterial;
}
```
1. Set up the texture to blit from and blit to. For example:
```lang-cs
TextureHandle sourceTexture = renderGraph.CreateTexture(sourceTextureProperties);
TextureHandle destinationTexture = renderGraph.CreateTexture(destinationTextureProperties);
```
1. To set up the material, textures, and shader pass for the blit operation, create a [`RenderGraphUtils.BlitMaterialParameters`](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.3/api/UnityEngine.Rendering.RenderGraphModule.Util.RenderGraphUtils.BlitMaterialParameters.html) object. For example:
```lang-cs
// Create a BlitMaterialParameters object with the blit material, source texture, destination texture, and shader pass to use.
var blitParams = new RenderGraphUtils.BlitMaterialParameters(sourceTexture, destinationTexture, blitMaterial, 0);
```
1. To add a blit pass, call the [`AddBlitPass`](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.3/api/UnityEngine.Rendering.RenderGraphModule.Util.RenderGraphUtils.html#UnityEngine_Rendering_RenderGraphModule_Util_RenderGraphUtils_AddBlitPass_UnityEngine_Rendering_RenderGraphModule_RenderGraph_UnityEngine_Rendering_RenderGraphModule_Util_RenderGraphUtils_BlitMaterialParameters_System_String_System_Boolean_) method with the blit parameters. For example:
```lang-cs
renderGraph.AddBlitPass(blitParams, "Pass created with AddBlitPass");
```
If you use `AddBlitPass` with a default material, Unity might use the `AddCopyPass` API instead, to optimize the render pass so it accesses the framebuffer from the on-chip memory of the GPU instead of video memory. This process is sometimes called framebuffer fetch. For more information, refer to [`AddCopyPass`](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.3/api/UnityEngine.Rendering.RenderGraphModule.Util.RenderGraphUtils.html#UnityEngine_Rendering_RenderGraphModule_Util_RenderGraphUtils_AddCopyPass_UnityEngine_Rendering_RenderGraphModule_RenderGraph_UnityEngine_Rendering_RenderGraphModule_TextureHandle_UnityEngine_Rendering_RenderGraphModule_TextureHandle_System_String_System_Boolean_) API.
## Customize the render pass
To customize the render pass that the methods generate, for example to change settings or add more resources, call the APIs with the `returnBuilder` parameter set to `true`. The APIs then return the `IBaseRenderGraphBuilder` object that you usually receive as `var builder` from a method like `AddRasterRenderPass`.
For example:
```lang-cs
using (var builder = renderGraph.AddBlitPass(blitParams, "Pass created with AddBlitPass", returnBuilder: true))
{
// Use the builder variable to customize the render pass here.
}
```
## Additional resources
- [The RTHandle System](rthandle-system.md)
- [Shaders](shaders.md)
@@ -0,0 +1,48 @@
# Create a texture in the render graph system in SRP Core
To create a texture in the render graph system, use the `CreateTexture` method of the render graph instance.
When you create a texture inside a render pass, the render graph system handles the creation and disposal of the texture. This process means the texture might not exist in the next frame, and other cameras might not be able to use it. To make sure a texture is available across frames and cameras, [import a texture](render-graph-import-a-texture.md) instead.
When the render graph system optimizes the render pipeline, it might not create a texture if the final frame doesn't use the texture, to reduce the memory and bandwidth the render passes use.
## Create a texture
To create a texture, in follow these steps:
1. Create a [`TextureDesc`](xref:UnityEngine.Rendering.RenderGraphModule.TextureDesc) object with the texture properties you need.
2. Use the [`CreateTexture`](xref:UnityEngine.Rendering.RenderGraphModule.RenderGraph.CreateTexture(UnityEngine.Rendering.RenderGraphModule.TextureDesc@)) method of the render graph instance to create a texture and return a texture handle.
For example, the following creates a texture the same size as the screen.
``` lang-cs
void RenderCamera(ScriptableRenderContext context, Camera cameraToRender)
{
...
var textureProperties = new TextureDesc(Vector2.one)
{
colorFormat = GraphicsFormat.R8G8B8A8_UNorm,
width = cameraToRender.pixelWidth,
height = cameraToRender.pixelHeight,
clearBuffer = true,
clearColor = Color.blue,
name = "New render graph Texture",
};
TextureHandle tempTexture = renderGraph.CreateTexture(textureProperties);
...
}
```
You can then [use the texture](render-graph-read-write-texture.md) in the same custom render pass.
The render graph system manages the lifetime of textures you create with `CreateTexture`, so you don't need to manually release the memory they use when you're finished with them.
## Additional resources
- [Import a texture into the render graph system](render-graph-import-a-texture.md)
- [Textures](https://docs.unity3d.com/Manual/Textures.html)
@@ -0,0 +1,60 @@
# Import a texture into the render graph system in SRP Core
To use a texture from outside the render graph system, or to make sure a texture is available across frames and cameras, import it into the render graph system using the `ImportTexture` API.
For example, you can import the back buffer, or create a texture that points to a texture in your project, such as a [texture asset](https://docs.unity3d.com/Manual/ImportingTextures.html).
The render graph system doesn't manage the lifetime of imported textures, so it can't optimize the render graph by removing unneeded render passes. Where possible, [Create a texture inside the render graph system](render-graph-create-a-texture) instead, so the render graph system manages its lifetime.
## Import a texture
To import a texture, follow these steps:
1. Create a [RenderTextureDescriptor](https://docs.unity3d.com/ScriptReference/RenderTextureDescriptor.html) object with the texture properties you need.
For example:
``` lang-cs
RenderTextureDescriptor textureProperties = new RenderTextureDescriptor(Screen.width, Screen.height, RenderTextureFormat.Default, 0);
```
2. Use the `RenderTextureDescriptor` to instantiate a new render texture. For example:
```lang-cs
RenderTexture renderTexture = new RenderTexture(textureProperties);
```
3. Create a handle to the render texture. For example:
``` lang-cs
RTHandle renderTextureHandle = RTHandles.Alloc(renderTexture);
```
4. Import the texture, to convert the `RTHandle` object to a `TextureHandle` object the render graph system can use.
For example:
``` lang-cs
TextureHandle texture = renderGraph.ImportTexture(renderTextureHandle);
```
You can then use the `TextureHandle` object to [read from or write to the render texture](render-graph-read-write-texture.md).
<a name="dispose-of-a-render-texture"></a>
### Dispose of the render texture
You must free the memory a render texture uses at the end of a render pass.
For example, you can create the following `Dispose` method:
``` lang-cs
public void Dispose()
{
renderTexture.Release();
}
```
## Additional resources
* [Textures](https://docs.unity3d.com/Manual/Textures.html)
* [The RTHandle system](rthandle-system.md)
@@ -0,0 +1,60 @@
# Use a texture in a render pass in SRP Core
You can use the render graph system API to set a texture as an input or output for a custom render pass, so you can read from or write to it.
## Set a texture as an input
To set a texture as an input for a custom render pass, follow these steps:
1. In your pass data, add a texture handle field to the data your pass uses.
For example:
``` lang-cs
// Create the data your pass uses
public class MyPassData
{
// Add a texture handle
public TextureHandle textureToUse;
}
```
2. Set the texture handle to the texture you want to use. For more information, refer to [Create a texture in the render graph system](render-graph-create-a-texture.md) or [Import a texture into the render graph system](render-graph-import-a-texture.md).
3. Call the [`UseTexture`](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.0/api/UnityEngine.Rendering.RenderGraphModule.IBaseRenderGraphBuilder.html#UnityEngine_Rendering_RenderGraphModule_IBaseRenderGraphBuilder_UseTexture_UnityEngine_Rendering_RenderGraphModule_TextureHandle__UnityEngine_Rendering_RenderGraphModule_AccessFlags_) method to set the texture as an input.
For example:
``` lang-cs
builder.UseTexture(passData.textureToUse, AccessFlags.Read);
```
In your `SetRenderFunc` method, you can now use the `TextureHandle` object in the pass data as an input for APIs.
## Set a texture as the render target
To set a texture as the output for APIs, use the [`SetRenderAttachment`](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.0/api/UnityEngine.Rendering.RenderGraphModule.IRasterRenderGraphBuilder.html#UnityEngine_Rendering_RenderGraphModule_IRasterRenderGraphBuilder_SetRenderAttachment_UnityEngine_Rendering_RenderGraphModule_TextureHandle_System_Int32_UnityEngine_Rendering_RenderGraphModule_AccessFlags_) method. The `SetRenderAttachment` method sets the texture as write-only by default.
For example:
```lang-cs
builder.SetRenderAttachment(textureHandle, 0);
```
You don't need to add the texture to your pass data. The render graph system sets up the texture for you automatically before it executes the render pass.
You can't use `UseTexture` and `SetRenderAttachment` on the same texture in a `AddRasterRenderPass` render pass. Refer to [Change the render target during a render pass](#change-the-render-target-during-a-pass) for more information.
<a name="change-the-render-target-during-a-pass"></a>
## Change the render target during a render pass
You can't change which texture Unity writes to during a render graph system render pass.
You can do either of the following instead:
- Create a second custom render pass, and use `builder.SetRenderAttachment` during the second render pass to change the render target.
- Use the `UnsafePass` API so you can use the `SetRenderTarget` API in the `SetRenderFunc` method. For more information, refer to [Use the CommandBuffer interface in a render graph](render-graph-unsafe-pass.md).
You can use these methods to read from and write to the same texture, by first copying from the texture to a temporary texture you create, then copying back.
If you blit between several textures with different properties, rendering might be slow because Unity can't merge the blits into a single native render pass. Use the `AddUnsafePass` API and the `SetRenderTarget()` method instead.
@@ -0,0 +1,13 @@
# Resources in the render graph system in SRP Core
Access and use textures and other resources in a custom scriptable render pipeline (SRP) that uses the render graph system.
**Note:** This page is about creating a custom render pipeline. To use the render graph system in a prebuilt Unity pipeline, refer to either [Render graph system in URP](https://docs.unity3d.com/Manual/urp/render-graph.html) or [Render graph system in HDRP](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@latest/index.html?subfolder=/manual/render-graph-introduction.html).
|**Topic**|**Description**|
|-|-|
|[Introduction to resources in the render graph system](render-graph-resources.md)|Learn about how to manage resources in the render graph system.|
|[Blit using the render graph system](render-graph-blit.md)|To blit from one texture to another in the render graph system, use the `AddBlitPass` API.|
|[Create a texture in the render graph system](render-graph-create-a-texture.md)|Create a texture in a render graph system render pass.|
|[Import a texture into the render graph system](render-graph-import-a-texture.md)|To create or use a render texture in a render graph system render pass, use the `RTHandle` API.|
|[Use a texture in a render pass](render-graph-read-write-texture.md)|To allow a render pass to read from or write to a texture, use the render graph system API to set the texture as an input or output.|
@@ -0,0 +1,34 @@
# Introduction to resources in the render graph system in SRP Core
To declare a resource and use it in a render pass, for example a texture or a list of objects to render, call render graph APIs that return a handle to the resource. You can't directly allocate or dispose of resources yourself.
The render graph system only allocates the memory for a resource just before the first render pass that writes to it, and releases the memory after the last render pass that reads it. This lets render graph manage memory in the most efficient way possible, and avoid allocating memory for resources that aren't used in a frame.
You can create resources in two ways:
- Create a resource inside a render pass. These are called internal or transient resources. The render graph system handles the lifetime of these resources. You can't access them outside of the render graph instance, or pass them between frames or different render graphs.
For example:
```c#
TextureHandle tempTexture = myRenderGraph.CreateTexture(textureProperties);
```
For more information, refer to [Create a texture in the render graph system](render-graph-create-a-texture.md).
- Import an existing resource from outside a render pass, for example the camera back buffer, or textures you want a render graph to use across multiple frames. These are called imported or external resources. You manage their lifetime yourself.
For example:
```c#
TextureHandle cameraColorBuffer = myRenderGraph.ImportBackbuffer(BuiltinRenderTextureType.CameraTarget, cameraTargetProperties);
```
Imported resources are useful when the resource is used in one of two possible render passes. For example, using the color buffer in either a deferred lighting pass or a forward lighting pass.
For more information, refer to [Import a texture into the render graph system](render-graph-import-a-texture.md).
Each API requires a descriptor structure as a parameter. The properties in these structures are similar to the properties in the resources they represent (respectively [RTHandle](rthandle-system.md), [ComputeBuffer](https://docs.unity3d.com/ScriptReference/ComputeBuffer.html), and [RendererLists](https://docs.unity3d.com/ScriptReference/Rendering.RendererList.html)).
For the complete list of APIs, refer to the [API documentation](../api/UnityEngine.Rendering.RenderGraphModule.RenderGraph.html).
@@ -0,0 +1,18 @@
# Creating a custom render pipeline using the render graph system
The render graph system is a set of APIs you can use to write a custom scriptable render pipeline in a modular, maintainable way.
**Note:** This section is about creating a custom render pipeline. To use the render graph system in a prebuilt Unity pipeline, refer to either [Render graph system in URP](https://docs.unity3d.com/Manual/urp/render-graph.html) or [Render graph system in HDRP](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@latest/index.html?subfolder=/manual/render-graph-introduction.html).
|**Topic**|**Description**|
|-|-|
|[Introduction to the render graph system](render-graph-system.md)|What the render graph system is, and how it optimizes rendering.|
|[Write a render pipeline with render graph](render-graph-writing-a-render-pipeline.md)|Write the outline of a render pipeline that uses the render graph APIs.|
|[Write a render pass using the render graph system](render-graph-write-render-pass.md)|Record and execute a render pass in the render graph system.|
|[Resources in the render graph system](render-graph-resources-landing.md)|Import and use textures and other resources in a render pass.|
|[Use the CommandBuffer interface in a render graph](render-graph-unsafe-pass.md)|Use `CommandBuffer` interface APIs such as `SetRenderTarget` in render graph system render passes.|
## Additional resources
- [Creating a custom render pipeline](srp-custom.md)
- [RTHandle system](rthandle-system.md)
@@ -0,0 +1,37 @@
# Render graph system in SRP Core
The render graph system is a set of APIs you can use to write a custom scriptable render pipeline in a modular, maintainable way. A render graph is a high-level representation of the render passes in the pipeline.
The render graph system automatically optimizes the render pipeline to minimize the number of render passes, and the memory and bandwidth the render passes use.
In each frame, you create a new instance of a render graph and follow these steps:
1. Set up the render passes. For each render pass, you tell the render graph system the textures or render textures to use (the recording stage) and the graphics commands to execute (the execution stage).
2. Compile the graph. The render graph removes render passes that don't contribute to the final frame, and calculates the lifetime of resources and the synchronization points between render passes.
3. Execute the graph.
During execution, the render graph system allocates memory for resources before each render pass that uses them, then releases them if later render passes don't use them.
## Differences from a standard custom render pipeline
The render graph system differs from the standard workflow for [creating a custom render pipeline](srp-custom.md) in the following ways:
- You no longer handle resources directly and instead use handles such as `RTHandle` that are specific to the render graph system. This affects how to write shader code and how to set up render passes.
- Each render pass must state which resources it reads from and writes to.
- Resource references are only accessible within the execution code of a render pass.
- The resources you create inside one frame or render graph can't carry over to the next frame or render graph, unless you import them. For more information, refer to [Resources in the render graph system](render-graph-resources.md).
## How the render graph system optimizes rendering
The render graph system automatically optimizes the graph to minimize the number of render passes, and the memory and bandwidth the render passes use, in the following ways:
- Avoids allocating resources the frame doesn't use.
- Removes render passes if the final frame doesn't use their output.
- Optimizes GPU memory, for example by reusing allocated memory if a texture has the same properties as an earlier texture.
- Automatically synchronizes the compute and graphics GPU command queues, if you use compute shaders.
On mobile platforms that use tile-based deferred rendering (TBDR), render graph can also merge multiple render passes into a single native render pass. A native render pass keeps textures in tile memory, rather than copying textures from the GPU to the CPU. As a result, rendering uses less memory bandwidth and rendering time.
## Additional resources
- [The RTHandle system](rthandle-system.md)
@@ -0,0 +1,63 @@
# Use the CommandBuffer interface in a render graph in SRP Core
You can use the render graph `AddUnsafePass` API to use [CommandBuffer](ScriptRef:Rendering.CommandBuffer) interface APIs such as `SetRenderTarget` in render graph system render passes.
The `AddUnsafePass` API gives access to the [UnsafeCommandBuffer](ScriptRef:Rendering.UnsafeCommandBuffer), which gives access to more `CommandBuffer` functions than the [RasterCommandBuffer](ScriptRef:Rendering.RasterCommandBuffer) API.
**Note**: Both `AddUnsafePass` and `RasterCommandBuffer` restrict access to certain `commandBuffer` functions so that `RenderGraph` can better optimize the frame. The most important function `UnsafeCommandbuffer` gives you access to is `SetRenderTarget`.
If you use the `AddUnsafePass` API, the following applies:
- You can't use the `SetRenderAttachment` method in the `RecordRenderGraph` method. Use `SetRenderTarget` in the `SetRenderFunc` method instead.
- Rendering might be slower because the render graph system can't optimize the render pass. For example, if your render pass writes to the active color buffer, the render graph system can't detect if a later render pass writes to the same buffer. As a result, the render graph system can't merge the two render passes, and the GPU unnecessarily transfers the buffer in and out of memory.
## Create an unsafe render pass
To create an unsafe render pass, follow these steps:
1. In your `RecordRenderGraph` method, use the `AddUnsafePass` method instead of the `AddRasterRenderPass` method.
For example:
``` lang-cs
using (var builder = renderGraph.AddUnsafePass<PassData>("My unsafe render pass", out var passData))
```
2. When you call the `SetRenderFunc` method, use the `UnsafeGraphContext` type instead of `RasterGraphContext`.
For example:
``` lang-cs
builder.SetRenderFunc(
static (PassData passData, UnsafeGraphContext context) => ExecutePass(passData, context)
);
```
3. If your render pass writes to a texture, add the texture as a field in your pass data class.
For example:
``` lang-cs
private class PassData
{
internal TextureHandle textureToWriteTo;
}
```
4. If your render pass writes to a texture, set the texture as writeable using the `UseTexture` method.
For example:
``` lang-cs
builder.UseTexture(passData.textureToWriteTo, AccessFlags.Write);
```
You can now use CommandBuffer interface APIs in your `SetRenderFunc` method. For example:
```lang-cs
static void ExecutePass(PassData passData, UnsafeGraphContext context)
{
// Add a command to set the render target to the active color buffer so render graph draws to it
context.cmd.SetRenderTarget(passData.activeColorBuffer);
}
```
@@ -0,0 +1,149 @@
# Write a render pass using the render graph system in SRP Core
Write a render pass using the render graph system, after you use the `BeginRecording` API to start recording render graph commands.
**Note:** This section is about creating a custom render pipeline. To use the render graph system in a prebuilt Unity pipeline, refer to either [Render graph system in URP](https://docs.unity3d.com/Manual/urp/render-graph.html) or [Render graph system in HDRP](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@latest/index.html?subfolder=/manual/render-graph-introduction.html).
## Prerequisites
To add a render pass, you must first create a render graph instance and start recording. For more information, refer to [Write a render pipeline with render graph](render-graph-writing-a-render-pipeline.md).
## Write a render pass
1. Create a class or struct that declares the resources the render pass uses. For example:
```lang-cs
class PassData
{
public TextureHandle cameraTarget;
public TextureHandle sourceTexture;
}
```
Ensure that you declare only the variables that the render pass uses. Adding unnecessary variables can reduce performance.
2. Declare the render pass, for example using the `AddRasterRenderPass` method.
```lang-cs
using (var builder = myRenderGraph.AddRasterRenderPass<PassData>("Example render pass", out var passData))
{
}
```
The `builder` variable is an instance of the `IRasterRenderGraphBuilder` interface. This variable is the entry point for configuring the information related to the render pass.
2. Set the resources that the render pass uses. For example:
```lang-cs
using (var builder = myRenderGraph.AddRasterRenderPass<PassData>("Example render pass", out var passData))
{
...
// Set the source texture as the camera target.
passData.cameraTarget = myRenderGraph.ImportBackbuffer(BuiltinRenderTextureType.CameraTarget, cameraTargetProperties);
// Set the destination texture as a temporary texture.
passData.sourceTexture = myRenderGraph.CreateTexture(textureProperties);
}
```
For more information, refer to [Resources in the render graph system](render-graph-resources.md).
3. Declare the inputs of the render pass using the `UseTexture` API, but don't add commands to command buffers. This is the recording stage.
```lang-cs
builder.UseTexture(passData.cameraTarget, AccessFlags.Read);
```
4. Declare the output of the render pass using the `SetRenderAttachment` API. For example:
```lang-cs
builder.SetRenderAttachment(passData.sourceTexture, 0, AccessFlags.Write);
```
5. To add commands, declare a rendering function using the `SetRenderFunc` API. Use a static method or a static lambda method. This is the execution stage. For example:
```lang-cs
builder.SetRenderFunc(static (PassData passData, RasterGraphContext context) =>
{
context.cmd.ClearRenderTarget(true, true, Color.blue);
});
```
## Example
The following example sets a temporary texture as the input and the camera target as the output, then clears the camera target to blue. To use the example, add it to a custom render pipeline after the `BeginRecording` API. For more information, refer to [Write a render pipeline with render graph](render-graph-writing-a-render-pipeline.md).
This code example is simplified. It demonstrates the clearest workflow, rather than the most efficient runtime performance.
```c#
using (var builder = myRenderGraph.AddRasterRenderPass<PassData>("Example render pass", out var passData))
{
RenderTargetInfo cameraTargetProperties = new RenderTargetInfo
{
width = cameraToRender.pixelWidth,
height = cameraToRender.pixelHeight,
volumeDepth = 1,
msaaSamples = 1,
format = GraphicsFormat.R8G8B8A8_UNorm
};
passData.cameraTarget = myRenderGraph.ImportBackbuffer(BuiltinRenderTextureType.CameraTarget, cameraTargetProperties);
var textureProperties = new TextureDesc(Vector2.one)
{
colorFormat = GraphicsFormat.R8G8B8A8_UNorm,
width = cameraTargetProperties.width,
height = cameraTargetProperties.height,
clearBuffer = true,
clearColor = Color.red,
name = "My temporary texture"
};
passData.sourceTexture = myRenderGraph.CreateTexture(textureProperties);
passData.material = new Material(Shader.Find("Unlit/Texture"));
builder.UseTexture(passData.sourceTexture, AccessFlags.Read);
builder.SetRenderAttachment(passData.cameraTarget, 0, AccessFlags.Write);
// Make sure the render graph system keeps the render pass, even if it's not used in the final frame.
// Don't use this in production code, because it prevents the render graph system from removing the render pass if it's not needed.
builder.AllowPassCulling(false);
builder.SetRenderFunc(static (PassData passData, RasterGraphContext context) =>
{
// Create a quad mesh
Mesh mesh = new Mesh();
Vector3[] vertices = new Vector3[4]
{
new Vector3(0, 0, 0),
new Vector3(1f, 0, 0),
new Vector3(0, 1f, 0),
new Vector3(1f, 1f, 0)
};
mesh.vertices = vertices;
int[] triangles = new int[6]
{
0, 2, 1,
2, 3, 1
};
mesh.triangles = triangles;
context.cmd.ClearRenderTarget(true, true, Color.blue);
// Pass the source texture to the shader
passData.material.SetTexture("_MainTex", passData.sourceTexture);
// Create a transformation matrix for the quad
Matrix4x4 trs = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, 0), Vector3.one);
// Draw the quad onto the camera target, using the shader and the source texture
context.cmd.DrawMesh(mesh, trs, passData.material, 0);
});
}
```
@@ -0,0 +1,136 @@
# Write a render pipeline with render graph in SRP Core
Create a custom render pipeline using the [render graph system](render-graph-system.md) in SRP Core.
**Note:** This page is about creating a custom render pipeline. To use the render graph system in a prebuilt Unity pipeline, refer to either [Render graph system in URP](https://docs.unity3d.com/Manual/urp/render-graph.html) or [Render graph system in HDRP](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@latest/index.html?subfolder=/manual/render-graph-introduction.html).
1. In your class that inherits `RenderPipeline`, create an instance of a [`RenderGraph`](../api/UnityEngine.Rendering.RenderGraphModule.RenderGraph.html). For example:
```c#
public class MyRenderPipeline : RenderPipeline
{
...
RenderGraph myRenderGraph;
myRenderGraph = new RenderGraph("MyRenderGraph");
}
```
**Note:** To optimize memory usage, use only one instance. You can use more than one instance of a render graph, but Unity doesn't share resources across `RenderGraph` instances.
For more information about creating a render pipeline class, refer to [Creating a custom render pipeline](srp-custom.md).
2. In your render loop, create the parameters to initialize the render graph, using the `RenderGraphParameters` API. For example:
```c#
void RenderMyCamera(ScriptableRenderContext context, Camera cameraToRender)
{
context.SetupCameraProperties(cameraToRender);
var cmd = CommandBufferPool.Get("ExampleCommandBuffer");
RenderGraphParameters rgParams = new RenderGraphParameters
{
commandBuffer = cmd,
scriptableRenderContext = context,
currentFrameIndex = Time.frameCount,
};
}
```
For more information about creating a render loop, refer to [Create a simple render loop in a custom render pipeline](srp-creating-simple-render-loop.md).
3. Initialize the render graph by calling the [`BeginRecording`](../api/UnityEngine.Rendering.RenderGraphModule.RenderGraph.html) method. For example:
```c#
myRenderGraph.BeginRecording(renderGraphParams);
```
4. Run the render passes by calling the [`EndRecordingAndExecute`](../api/UnityEngine.Rendering.RenderGraphModule.RenderGraph.html) method. For example:
```c#
myRenderGraph.BeginRecording(renderGraphParams);
// Add render passes here.
myRenderGraph.EndRecordingAndExecute();
```
For more information about adding render passes, refer to [Write a render pass using the render graph system](render-graph-write-render-pass.md)
5. Execute the rendering commands. For more information, refer to [Execute rendering commands in a custom render pipeline](srp-using-scriptable-render-context.md).
6. In the render pipeline class, call the `Cleanup()` method on the RenderGraph instance to free the resources the render graph allocated. For example:
```c#
myRenderGraph.Cleanup();
myRenderGraph = null;
```
7. After the last camera renders, call the `EndFrame` method to deallocate any resources that the render graph hasn't used since the last frame.
```c#
myRenderGraph.EndFrame();
```
## Example render pipeline template
This code template is simplified. It demonstrates the clearest workflow, rather than the most efficient runtime performance.
```c#
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
public class ExampleRenderPipeline : RenderPipeline
{
private RenderGraph myRenderGraph;
public ExampleRenderPipeline(ExampleRenderPipelineAsset asset)
{
myRenderGraph = new RenderGraph("My render graph");
}
protected override void Render(ScriptableRenderContext context, List<Camera> cameras)
{
foreach (var cam in cameras)
{
if (cam.enabled)
{
RenderCamera(context, cam);
}
}
}
void RenderCamera(ScriptableRenderContext context, Camera cameraToRender)
{
context.SetupCameraProperties(cameraToRender);
var cmd = CommandBufferPool.Get("Example command buffer");
RenderGraphParameters rgParams = new RenderGraphParameters
{
commandBuffer = cmd,
scriptableRenderContext = context,
currentFrameIndex = Time.frameCount,
};
try
{
myRenderGraph.BeginRecording(rgParams);
// Add render passes here.
myRenderGraph.EndRecordingAndExecute();
}
catch (Exception e)
{
if (myRenderGraph.ResetGraphAndLogException(e))
throw;
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
context.Submit();
}
}
```
@@ -0,0 +1,17 @@
## RTHandle system fundamentals
This document describes the main principles of the RTHandle (RTHandle) system.
The RTHandle system is an abstraction on top of Unity's [RenderTexture](https://docs.unity3d.com/ScriptReference/RenderTexture.html) API. It makes it trivial to reuse render textures across Cameras that use various resolutions. The following principles are the foundation of how the RTHandle system works:
- You no longer allocate render textures yourself with a fixed resolution. Instead, you declare a render texture using a scale related to the full screen at a given resolution. The RTHandle system allocates the texture only once for the whole render pipeline so that it can reuse it for different Cameras.
- There is now the concept of reference size. This is the resolution the application uses for rendering. It is your responsibility to declare it before the render pipeline renders every Camera at a particular resolution. For information on how to do this, see the [Updating the RTHandle system](rthandle-system-using.md#updating-the-rthandle-system) section.
- Internally, the RTHandle system tracks the largest reference size you declare. It uses this as the actual size of render textures. The largest reference size is the maximum size.
- Every time you declare a new reference size for rendering, the RTHandle system checks if it is larger than the current recorded largest reference size. If it is, the RTHandle system reallocates all render textures internally to fit the new size and replaces the largest reference size with the new size.
An example of this process is as follows. When you allocate the main color buffer, it uses a scale of **1** because it is a full-screen texture. You want to render it at the resolution of the screen. A downscaled buffer for a quarter-resolution transparency pass would use a scale of **0.5** for both the x-axis and y-axis. Internally the RTHandle system allocates render textures using the largest reference size multiplied by the scale you declare for the render texture. After that and before each Camera renders, you tell the system what the current reference size is. Based on that and the scaling factor for all textures, the RTHandle system determines if it needs to reallocate render textures. As mentioned above, if the new reference size is larger than the current largest reference size, the RTHandle system reallocates all render textures. By doing this, the RTHandle system ends up with a stable maximum resolution for all render textures, which is most likely the resolution of your main Camera.
The key takeaway of this is that the actual resolution of the render textures is not necessarily the same as the current viewport: it can be bigger. This has implications when you write a renderer using RTHandles, which the [Using the RTHandle system](rthandle-system-using.md) documentation explains.
The RTHandleSystem also allows you to allocate textures with a fixed size. In this case, the RTHandle system never reallocates the texture. This allows you to use the RTHandle API consistently for both automatically-resized textures that the RTHandle system manages and regular fixed size textures that you manage.
@@ -0,0 +1,186 @@
## Using the RTHandle system
This page covers how to use the RTHandle system to manage render textures in your render pipeline. For information about the RTHandle system, see [RTHandle system](rthandle-system.md) and [RTHandle system fundamentals](rthandle-system-fundamentals.md).
### Initializing the RTHandle System
All operations related to `RTHandles` require an instance of the `RTHandleSystem` class. This class contains all the APIs necessary to allocate RTHandles, release RTHandles, and set the reference size for the frame. This means that you must create and maintain an instance of `RTHandleSystem` in your render pipeline or make use of the static RTHandles class mentioned later in this section. To create your own instance of `RTHandleSystem`, see the following code sample:
```c#
RTHandleSystem m_RTHandleSystem = new RTHandleSystem();
m_RTHandleSystem.Initialize(Screen.width, Screen.height);
```
When you initialize the system, you must supply the starting resolution. The above code example uses the width and height of the screen. Because the RTHandle system only reallocates render textures when a Camera requires a resolution larger than the current maximum size, the internal `RTHandle` resolution can only increase from the value you pass in here. It is good practice to initialize this resolution to be the resolution of the main display. This means the system does not need to unnecessarily reallocate the render textures (and cause unwanted memory spikes) at the beginning of the application.
You must only call the `Initialize` function once at the beginning of the application. After this, you can use the initialized instance to allocate textures.
Because you allocate the majority of `RTHandles` from the same `RTHandleSystem` instance, the RTHandle system also provides a default global instance through the `RTHandles` static class. Rather than maintain your own instance of `RTHandleSystem`, this allows you to use the same API that you get with an instance, but not worry about the lifetime of the instance. Using the static instance, the initialization becomes this:
```c#
RTHandles.Initialize(Screen.width, Screen.height);
```
The code examples in the rest of this page use the default global instance.
### Updating the RTHandle System
Before rendering with a Camera, you need to set the resolution the RTHandle system uses as a reference size. To do so, call the `SetReferenceSize` function.
```c#
RTHandles.SetReferenceSize(width, height);
```
Calling this function has two effects:
1. If the new reference size you provide is bigger than the current one, the RTHandle system reallocates all the render textures internally to match the new size.
2. After that, the RTHandle system updates internal properties that set viewport and render texture scales for when the system uses RTHandles as active render textures.
### Allocating and releasing RTHandles
After you initialize an instance of `RTHandleSystem`, whether this is your own instance or the static default instance, you can use it to allocate RTHandles.
There are three main ways to allocate an `RTHandle`. They all use the same `Alloc` method on the RTHandleSystem instance. Most of the parameters of these functions are the same as the regular Unity RenderTexture ones, so for more information see the [RenderTexture API documentation](https://docs.unity3d.com/ScriptReference/RenderTexture.html). This section focuses on the parameters that relate to the size of the `RTHandle`:
- `Vector2 scaleFactor`: This variant requires a constant 2D scale for width and height. The RTHandle system uses this to calculate the resolution of the texture against the maximum reference size. For example, a scale of (1.0f, 1.0f) generates a full-screen texture. A scale of (0.5f 0.5f) generates a quarter-resolution texture.
- `ScaleFunc scaleFunc`: For cases when you don't want to use a constant scale to calculate the size of an `RTHandle`, you can provide a functor that calculates the size of the texture. The functor should take a `Vector2Int` as a parameter, which is the maximum reference size, and return a `Vector2In`t, which represents the size you want the texture to be.
- `int width, int height`: This is for fixed-size textures. If you allocate a texture like this, it behaves like any regular RenderTexture.
There are also overrides that create RTHandles from [RenderTargetIdentifier](https://docs.unity3d.com/ScriptReference/Rendering.RenderTargetIdentifier.html). [RenderTextures](https://docs.unity3d.com/ScriptReference/RenderTexture.html), or [Textures](https://docs.unity3d.com/Manual/Textures.html). These are useful when you want to use the RTHandle API to interact with all your textures, even though the texture might not be an actual `RTHandle`.
The following code sample contains example uses of the `Alloc` function:
```c#
// Simple Scale
RTHandle simpleScale = RTHandles.Alloc(Vector2.one, depthBufferBits: DepthBits.Depth32, dimension: TextureDimension.Tex2D, name: "CameraDepthStencil");
// Functor
Vector2Int ComputeRTHandleSize(Vector2Int screenSize)
{
return DoSpecificResolutionComputation(screenSize);
}
RTHandle rtHandleUsingFunctor = RTHandles.Alloc(ComputeRTHandleSize, colorFormat: GraphicsFormat.R32_SFloat, dimension: TextureDimension.Tex2D);
// Fixed size
RTHandle fixedSize = RTHandles.Alloc(256, 256, colorFormat: GraphicsFormat.R8G8B8A8_UNorm, dimension: TextureDimension.Tex2D);
```
When you no longer need a particular RTHandle, you can release it. To do this, call the `Release` method.
```c#
myRTHandle.Release();
```
## Using RTHandles
After you allocate an RTHandle, you can use it exactly like a regular RenderTexture. There are implicit conversions to `RenderTargetIdentifier` and `RenderTexture`, which means you can use them with regular related Unity APIs.
However, when you use the RTHandle system, the actual resolution of the `RTHandle` might be different from the current resolution. For example, if the main Camera renders at 1920x1080 and a secondary Camera renders at 512x512, all RTHandle resolutions are based on the 1920x1080 resolution, even when rendering at lower resolutions. Because of this, take care when you set an RTHandle up as a render target. There are a number of APIs available in the [CoreUtils](../api/UnityEngine.Rendering.CoreUtils.html) class to help you with this. For example:
```c#
public static void SetRenderTarget(CommandBuffer cmd, RTHandle buffer, ClearFlag clearFlag, Color clearColor, int miplevel = 0, CubemapFace cubemapFace = CubemapFace.Unknown, int depthSlice = -1)
```
This function sets the `RTHandle` as the active render target but also sets up the viewport based on the scale of the `RTHandle` and the current reference size, not the maximum size.
For example, when the reference size is 512x512, even if the maximum size is 1920x1080, a texture of scale (1.0f, 1.0f) uses the 512x512 size and therefore sets up a 512x512 viewport. A (0.5f, 0.5f) scaled texture sets up a viewport of 256x256 and so on. This means that, when using these helper functions, the RTHandle system generates the correct viewport based on the `RTHandle` parameters.
This example is one of many different overrides for the `SetRenderTarget` function. For the full list of overrides, see the [documentation](../api/UnityEngine.Rendering.CoreUtils.html#UnityEngine_Rendering_CoreUtils_SetRenderTarget_CommandBuffer_RenderTargetIdentifier_RenderBufferLoadAction_RenderBufferStoreAction_RenderTargetIdentifier_RenderBufferLoadAction_RenderBufferStoreAction_UnityEngine_Rendering_ClearFlag_).
## Using RTHandles in shaders
When you sample from a full-screen render texture in a shader in the usual way, UVs span the whole 0 to 1 range. This is not always the case with `RTHandles`. The current rendering might only occur in a partial viewport. To take this into account, you must apply a scale to UVs when you sample `RTHandles` that use a scale. All the information necessary to handle `RTHandles` specificity inside shaders is in the `RTHandleProperties` structure that the `RTHandleSystem` instance provides. To access it, use:
```c#
RTHandleProperties rtHandleProperties = RTHandles.rtHandleProperties;
```
This structure contains the following properties:
```c#
public struct RTHandleProperties
{
public Vector2Int previousViewportSize;
public Vector2Int previousRenderTargetSize;
public Vector2Int currentViewportSize;
public Vector2Int currentRenderTargetSize;
public Vector4 rtHandleScale;
}
```
This structure provides:
- The current viewport size. This is the reference size you set for rendering.
- The current render target size. This is the actual size of the render texture based on the maximum reference size.
- The `rtHandleScale`. This is the scale to apply to full-screen UVs to sample an RTHandle.
Values for previous frames are also available. For more information, see [Camera specific RTHandles](#camera-specific-rthandles). Generally, the most important property in this structure is `rtHandleScale`. It allows you to scale full-screen UV coordinates and use the result to sample an RTHandle. For example:
```c#
float2 scaledUVs = fullScreenUVs * rtHandleScale.xy;
```
However, because the partial viewport always starts at (0, 0), when you use integer pixel coordinates within the viewport to load content from a texture, there is no need to rescale them.
Another important thing to consider is that, when you render a full-screen quad into a partial viewport, there is no benefit from standard UV addressing mechanisms such as wrap or clamp. This is because the texture might be bigger than the viewport. For this reason, take care when you sample pixels outside of the viewport.
### Custom SRP specific information
There are no shader constants provided by default with SRP. So, when you use RTHandles with your own SRP, you must provide these constants to their shaders themselves.
## Camera specific RTHandles
Most of the render textures that a rendering loop uses can be shared by all Cameras. If their content does not need to carry from one frame to another, this is fine. However, some render textures need persistence. A good example of this is using the main color buffer in subsequent frames for Temporal Anti-aliasing. This means that the Camera cannot share its RTHandle with other Cameras. Most of the time, this also means that these RTHandles must be at least double-buffered (written to during the current frame, read from during the previous frame). To address this problem, the RTHandle system includes `BufferedRTHandleSystems`.
A `BufferedRTHandleSystem` is an `RTHandleSystem` that can multi-buffer RTHandles. The principle is to identify a buffer by a unique ID and provide APIs to allocate a number of instances of the same buffer then retrieve them from previous frames. These are history buffers. Usually, you must allocate one `BufferedRTHandleSystem` for each Camera. Each one owns their Camera-specific RTHandles.
Not every Camera needs history buffers. For example, if a Camera does not need Temporal Anti-aliasing, you do not need to assign a `BufferedRTHandleSystem` to it. History buffers require memory which means you can save memory by not assigning history buffers to Cameras that do not need them. Another consequence is that the system only allocates history buffers at the resolution of the Camera that the buffers are for. If the main Camera is 1920x1080 and another Camera renders in 256x256 and needs a history color buffer, the second Camera only uses a 256x256 buffer and not a 1920x1080 buffer as the non-Camera specific RTHandles would. To create an instance of a `BufferedRTHandleSystem`, see the following code sample:
```c#
BufferedRTHandleSystem m_HistoryRTSystem = new BufferedRTHandleSystem();
```
To allocate an `RTHandle` using a `BufferedRTHandleSystem`, the process is different from a normal `RTHandleSystem`:
```c#
public void AllocBuffer(int bufferId, Func<RTHandleSystem, int, RTHandle> allocator, int bufferCount);
```
The `bufferId` is a unique ID that the system uses to identify the buffer. The allocator is a function you provide to allocate the `RTHandles` when needed (all instances are not allocated upfront), and the `bufferCount` is the number of instances requested.
From there, you can retrieve each `RTHandle` by its ID and instance index like so:
```c#
public RTHandle GetFrameRT(int bufferId, int frameIndex);
```
The frame index is between zero and the number of buffers minus one. Zero always represents the current frame buffer, one the previous frame buffer, two the one before that, and so on.
To release a buffered RTHandle, call the `Release` function on the `BufferedRTHandleSystem`, passing in the ID of the buffer to release:
```c#
public void ReleaseBuffer(int bufferId);
```
In the same way that you provide the reference size for regular `RTHandleSystems`, you must do this for each instance of `BufferedRTHandleSystem`.
```c#
public void SwapAndSetReferenceSize(int width, int height);
```
This works the same way as regular RTHandleSystem but it also swaps the buffers internally so that the 0 index for `GetFrameRT` still references the current frame buffer. This slightly different way of handling Camera-specific buffers also has implications when you write shader code.
With a multi-buffered approach like this, `RTHandles` from a previous frame might have a different size to the one from the current frame. For example, this can happen with dynamic resolution or even when you resize the window in the Editor. This means that when you access a buffered `RTHandle` from a previous frame, you must scale it accordingly. The scale Unity uses to do this is in `RTHandleProperties.rtHandleScale.zw`. Unity uses this in exactly the same way as `xy` for regular RTHandles. This is also the reason why `RTHandleProperties` contains the viewport and resolution of the previous frame. It can be useful when doing computation with history buffers.
## Dynamic Resolution
One of the byproducts of the RTHandle System design is that you can also use it to simulate software dynamic resolution. Because the current resolution of the Camera is not directly correlated to the actual render texture objects, you can provide any resolution you want at the beginning of the frame and all render textures scale accordingly.
## Reset Reference Size
Sometimes, you might need to render to a higher resolution than normal for a short period of time. If your application does not require this resolution anymore, the additional memory allocated is wasted. To avoid that, you can reset the current maximum resolution of an `RTHandleSystem` like so:
```c#
RTHandles.ResetReferenceSize(newWidth, newHeight);
```
This forces the RTHandle system to reallocate all RTHandles to the new provided size. This is the only way to shrink the size of `RTHandles`.
@@ -0,0 +1,12 @@
# The RTHandle system
Render target management is an important part of any render pipeline. In a complicated render pipeline where there are many interdependent render passes that use many different render textures, it is important to have a maintainable and extendable system that allows for easy memory management.
One of the biggest issues occurs when a render pipeline uses many different Cameras, each with their own resolution. For example, off-screen Cameras or real-time reflection probes. In this scenario, if the system allocated render textures independently for each Camera, the total amount of memory would increase to unmanageable levels. This is particularly bad for complex render pipelines that use many intermediate render textures. Unity can use [temporary render textures](https://docs.unity3d.com/ScriptReference/RenderTexture.GetTemporary.html), but unfortunately, they do not suit this kind of use case because temporary render textures can only reuse memory if a new render texture uses the exact same properties and resolution. This means that when rendering with two different resolutions, the total amount of memory Unity uses is the sum of all resolutions.
To solve these issues with render texture memory allocation, Unity's Scriptable Render Pipeline includes the RTHandle system. This system is an abstraction layer on top of Unity's [RenderTexture](https://docs.unity3d.com/ScriptReference/RenderTexture.html) API that handles render texture management automatically.
This section contains the following pages:
- [RTHandle system fundamentals](rthandle-system-fundamentals.md)
- [Using the RTHandle system](rthandle-system-using.md)
@@ -0,0 +1,16 @@
# Custom graphics settings
Add, store, and manage custom settings that control rendering features and behaviours in a Scriptable Render Pipeline. For example, quality or shader settings.
|Page|Description|
|-|-|
|[Adding properties in the menu](adding-properties.md)|Add properties in the **Core Render Pipeline** settings section.|
|[Add a settings group](add-custom-graphics-settings.md)|To add custom graphics settings to a Scriptable Render Pipeline, implement the `IRenderPipelineGraphicsSettings` interface. |
|[Add a setting](add-custom-graphics-setting.md)|Add a simple property or a reference property to a custom graphics settings group.|
|[Customize the UI of a setting](customize-ui-for-a-setting.md)|Customize how a setting displays in the graphics settings window, or add items to the **More** (⋮) menu of a settings group.|
|[Get custom graphics settings](get-custom-graphics-settings.md)|Get a custom graphics setting and read its value, or detect when a setting changes.|
|[Include or exclude a setting in your build](choose-whether-unity-includes-a-graphics-setting-in-your-build.md)|Choose whether Unity includes or strips a graphics setting in your build, and check if a build includes a setting.|
## Additional resources
- [Graphics settings](xref:class-GraphicsSettings) in the Unity manual
@@ -0,0 +1,12 @@
# Shaders
Work with shader code in the Scriptable Render Pipeline (SRP).
|**Page**|**Description**|
|-|-|
|[Use shader methods from the SRP Core shader library](built-in-shader-methods.md)|SRP Core has a library of High-Level Shader Language (HLSL) shader files that contain helper methods. You can import these files into your custom shader files and use the helper methods.|
|[Synchronizing shader code and C#](generating-shader-includes.md)|Generate HLSL code based on C# structs to synchronize data and constants between shaders and C#.|
## Additional resources
- [HLSL in Unity](https://docs.unity3d.com/Manual/SL-ShaderPrograms.html)
@@ -0,0 +1,12 @@
# Use Scriptable Render Pipeline callbacks
To make Unity call your C# code at specific times, use the following APIs.
To write your custom render pipeline code, use the [RenderPipeline.Render](https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rendering.RenderPipeline.Render.html) API. This method is the main entry point to the SRP, and Unity calls it automatically.
To execute custom code at specific points in the render loop, subscribe to the following events in the [RenderPipelineManager](xref:UnityEngine.Rendering.RenderPipelineManager) class:
* [beginContextRendering](https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rendering.RenderPipelineManager-beginContextRendering.html)
* [endContextRendering](https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rendering.RenderPipelineManager-endContextRendering.html)
* [beginCameraRendering](https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rendering.RenderPipelineManager-beginCameraRendering.html)
* [endCameraRendering](https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rendering.RenderPipelineManager-endCameraRendering.html)
@@ -0,0 +1,124 @@
---
uid: um-srp-creating-render-pipeline-asset-and-render-pipeline-instance
---
# Create a Render Pipeline Asset and Render Pipeline Instance in a custom render pipeline
If you are creating your own render pipeline based on the Scriptable Render Pipeline (SRP), your Project must contain:
* A script that inherits from [RenderPipelineAsset](xref:UnityEngine.Rendering.RenderPipelineAsset) and overrides its `CreatePipeline()` method. This script defines your Render Pipeline Asset.
* A script that inherits from [RenderPipeline](xref:UnityEngine.Rendering.RenderPipeline), and overrides its `Render()` method. This script defines your Render Pipeline Instance, and is where you write your custom rendering code.
* A Render Pipeline Asset that you have created from your [RenderPipelineAsset](xref:UnityEngine.Rendering.RenderPipelineAsset) script. This asset acts as a factory class for your Render Pipeline Instance.
Because these elements are so closely related, you should create them at the same time.
## Creating a basic Render Pipeline Asset and Render Pipeline Instance
The following example shows how to create a script for a basic custom Render Pipeline Asset that instantiates the Render Pipeline Instance, a script that defines the Render Pipeline Instance, and the Render Pipeline Asset itself.
1. Create a C# script called _ExampleRenderPipelineAsset.cs_.
2. Copy and paste the following code into the new script:
```lang-csharp
using UnityEngine;
using UnityEngine.Rendering;
// The CreateAssetMenu attribute lets you create instances of this class in the Unity Editor.
[CreateAssetMenu(menuName = "Rendering/ExampleRenderPipelineAsset")]
public class ExampleRenderPipelineAsset : RenderPipelineAsset
{
// Unity calls this method before rendering the first frame.
// If a setting on the Render Pipeline Asset changes, Unity destroys the current Render Pipeline Instance and calls this method again before rendering the next frame.
protected override RenderPipeline CreatePipeline() {
// Instantiate the Render Pipeline that this custom SRP uses for rendering.
return new ExampleRenderPipelineInstance();
}
}
```
3. Create a C# script called _ExampleRenderPipelineInstance.cs_.
4. Copy and paste the following code into the new script:
```lang-csharp
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
public class ExampleRenderPipelineInstance : RenderPipeline
{
public ExampleRenderPipelineInstance() {
}
protected override void Render (ScriptableRenderContext context, List<Camera> cameras) {
// This is where you can write custom rendering code. Customize this method to customize your SRP.
}
}
```
5. In the Project view, either click the add (+) button, or open the context menu and navigate to **Create**, and then choose **Rendering** > **Example Render Pipeline Asset**. Unity creates a new Render Pipeline Asset in the Project view.
## Creating a configurable Render Pipeline Asset and Render Pipeline Instance
By default, a Render Pipeline Asset stores information about which Render Pipeline Instance to use for rendering, and the default Materials and Shaders to use in the Editor. In your `RenderPipelineAsset` script, you can extend your Render Pipeline Asset so that it stores additional data, and you can have multiple different Render Pipeline Assets with different configurations in your Project. For example, you might use a Render Pipeline Asset to hold configuration data for each different tier of hardware. The High Definition Render Pipeline (HDRP) and the Universal Render Pipeline (URP) include examples of this.
The following example shows how to create a `RenderPipelineAsset` script that defines a Render Pipeline Asset with public data that you can set for each instance using the Inspector, and a Render Pipeline Instance that receives a Render Pipeline Asset in its constructor and uses data from that Render Pipeline Asset.
1. Create a C# script called _ExampleRenderPipelineAsset.cs_.
2. Copy and paste the following code into the new script:
```lang-csharp
using UnityEngine;
using UnityEngine.Rendering;
// The CreateAssetMenu attribute lets you create instances of this class in the Unity Editor.
[CreateAssetMenu(menuName = "Rendering/ExampleRenderPipelineAsset")]
public class ExampleRenderPipelineAsset : RenderPipelineAsset
{
// This data can be defined in the Inspector for each Render Pipeline Asset
public Color exampleColor;
public string exampleString;
// Unity calls this method before rendering the first frame.
// If a setting on the Render Pipeline Asset changes, Unity destroys the current Render Pipeline Instance and calls this method again before rendering the next frame.
protected override RenderPipeline CreatePipeline() {
// Instantiate the Render Pipeline that this custom SRP uses for rendering, and pass a reference to this Render Pipeline Asset.
// The Render Pipeline Instance can then access the configuration data defined above.
return new ExampleRenderPipelineInstance(this);
}
}
```
3. Create a C# script called _ExampleRenderPipelineInstance.cs_.
4. Copy and paste the following code into the new script:
```lang-csharp
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
public class ExampleRenderPipelineInstance : RenderPipeline
{
// Use this variable to a reference to the Render Pipeline Asset that was passed to the constructor
private ExampleRenderPipelineAsset renderPipelineAsset;
// The constructor has an instance of the ExampleRenderPipelineAsset class as its parameter.
public ExampleRenderPipelineInstance(ExampleRenderPipelineAsset asset) {
renderPipelineAsset = asset;
}
protected override void Render(ScriptableRenderContext context, List<Camera> cameras) {
// This is an example of using the data from the Render Pipeline Asset.
Debug.Log(renderPipelineAsset.exampleString);
// This is where you can write custom rendering code. Customize this method to customize your SRP.
}
}
```
5. In the Project view, either click the add (+) button, or open the context menu and navigate to **Create**, and then choose **Rendering** > **Example Render Pipeline Asset**. Unity creates a new Render Pipeline Asset in the Project view.
@@ -0,0 +1,282 @@
---
uid: um-srp-creating-simple-render-loop
---
# Create a simple render loop in a custom render pipeline
A render loop is the term for all of the rendering operations that take place in a single frame. This page contains information on creating a simple render loop in a custom render pipeline that is based on Unity's Scriptable Render Pipeline.
The code examples on this page demonstrate the basic principles of using the Scriptable Render Pipeline. You can use this information to build your own custom Scriptable Render Pipeline, or to understand how Unity's prebuilt Scriptable Render Pipelines work.
## Preparing your project
Before you begin writing the code for your render loop, you must prepare your project.
The steps are as follows:
1. [Create an SRP-compatible shader](#creating-unity-shader).
2. [Create one or more GameObjects to render](#creating-gameobject).
3. [Create the basic structure of your custom SRP](#creating-srp).
4. *Optional:* If you plan to extend your simple custom SRP to add more complex functionality, install the SRP Core package. The SRP Core package includes the [SRP Core shader library](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@17.0/api/index.html) (which you can use to make your shaders SRP Batcher compatible), and utility functions for common operations.
<a name = "creating-unity-shader"></a>
### Creating an SRP-compatible shader
In the Scriptable Render Pipeline, you use the `LightMode` Pass tag to determine how to draw geometry. For more information on Pass tags, see [ShaderLab: assigning tags to a Pass](https://docs.unity3d.com/6000.0/Documentation/Manual/SL-PassTags).
This task shows you how to create a very simple unlit Shader object with a LightMode Pass tag value of `ExampleLightModeTag`.
1. Create a new shader asset in your project. For instructions on creating a shader asset, see [Shader assets](https://docs.unity3d.com/6000.0/Documentation/Manual/class-Shader).
2. In your Project view, double click the shader asset to open the shader source code in a text editor.
3. Replace the existing code with the following:
```
// This defines a simple unlit Shader object that is compatible with a custom Scriptable Render Pipeline.
// It applies a hardcoded color, and demonstrates the use of the LightMode Pass tag.
// It is not compatible with SRP Batcher.
Shader "Examples/SimpleUnlitColor"
{
SubShader
{
Pass
{
// The value of the LightMode Pass tag must match the ShaderTagId in ScriptableRenderContext.DrawRenderers
Tags { "LightMode" = "ExampleLightModeTag"}
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
float4x4 unity_MatrixVP;
float4x4 unity_ObjectToWorld;
struct Attributes
{
float4 positionOS : POSITION;
};
struct Varyings
{
float4 positionCS : SV_POSITION;
};
Varyings vert (Attributes IN)
{
Varyings OUT;
float4 worldPos = mul(unity_ObjectToWorld, IN.positionOS);
OUT.positionCS = mul(unity_MatrixVP, worldPos);
return OUT;
}
float4 frag (Varyings IN) : SV_TARGET
{
return float4(0.5,1,0.5,1);
}
ENDHLSL
}
}
}
```
<a name = "creating-gameobject"></a>
### Creating a GameObject to render
To test that your render loop works, you must create something to render. This task shows you how to put GameObjects in your scene that use the SRP-compatible shader that you created in the previous task.
1. Create a new material asset in your Unity project. For instructions see [Materials](https://docs.unity3d.com/6000.0/Documentation/Manual/class-Material).
2. Assign the shader asset to the material asset. For instructions, see [Materials](https://docs.unity3d.com/6000.0/Documentation/Manual/class-Material).
3. Create a cube in your scene. For instructions, see [Primitive objects](https://docs.unity3d.com/6000.0/Documentation/Manual/PrimitiveObjects).
4. Assign the material to it. For instructions, see [Materials](https://docs.unity3d.com/6000.0/Documentation/Manual/class-Material).
<a name = "creating-srp"></a>
### Creating the basic structure of your custom SRP
The final stage of preparation is to create the basic source files needed for your custom SRP, and tell Unity to begin rendering using the custom SRP.
1. Create a class that inherits from `RenderPipeline` and a compatible Render Pipeline Asset, following the instructions in [Creating a Render Pipeline Instance and Render Pipeline Asset](srp-creating-render-pipeline-asset-and-render-pipeline-instance.md)
2. Set the active Render Pipeline Asset, following the instructions in [How to get, set, and configure the active render pipeline](https://docs.unity3d.com/6000.0/Documentation/Manual/srp-setting-render-pipeline-asset.html). Unity will begin rendering using the custom SRP immediately, which means that your Scene view and Game view will be blank until you add code to your custom SRP.
## Creating the render loop
In a simple render loop, the basic operations are:
* [Clearing the render target](#clearing), which means removing the geometry that was drawn during the last frame.
* [Culling](#culling), which means filtering out geometry that is not visible to a Camera.
* [Drawing](#drawing), which means telling the GPU what geometry to draw, and how to draw it.
<a name = "clearing"></a>
### Clearing the render target
Clearing means removing the things that were drawn during the last frame. The render target is usually the screen; however, you can also render to textures to create a "picture in picture" effect. These examples demonstrate how to render to the screen, which is Unity's default behavior.
To clear the render target in the Scriptable Render Pipeline, you do the following:
1. Configure a `CommandBuffer` with a `Clear` command.
2. Add the `CommandBuffer` to the queue of commands on the `ScriptableRenderContext`; to do this, call [ScriptableRenderContext.ExecuteCommandBuffer](xref:UnityEngine.Rendering.ScriptableRenderContext.ExecuteCommandBuffer(UnityEngine.Rendering.CommandBuffer)).
3. Instruct the graphics API to perform the queue of commands on the `ScriptableRenderContext`; to do this, call [ScriptableRenderContext.Submit](xref:UnityEngine.Rendering.ScriptableRenderContext.Submit).
As with all Scriptable Render Pipeline operations, you use the [RenderPipeline.Render](https://docs.unity3d.com/6000.1/Documentation/ScriptReference/Rendering.RenderPipeline.Render.html) method as the entry point for this code. This example code demonstrates how to do this:
```lang-csharp
/*
This is a simplified example of a custom Scriptable Render Pipeline.
It demonstrates how a basic render loop works.
It shows the clearest workflow, rather than the most efficient runtime performance.
*/
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
public class ExampleRenderPipeline : RenderPipeline {
public ExampleRenderPipeline() {
}
protected override void Render(ScriptableRenderContext context, List<Camera> cameras) {
// Create and schedule a command to clear the current render target
var cmd = new CommandBuffer();
cmd.ClearRenderTarget(true, true, Color.black);
context.ExecuteCommandBuffer(cmd);
cmd.Release();
// Instruct the graphics API to perform all scheduled commands
context.Submit();
}
}
```
<a name = "culling"></a>
### Culling
Culling is the process of filtering out geometry that is not visible to a Camera.
To cull in the Scriptable Render Pipeline, you do the following:
1. Populate a [ScriptableCullingParameters](xref:UnityEngine.Rendering.ScriptableCullingParameters) struct with data about a Camera; to do this, call [Camera.TryGetCullingParameters](xref:UnityEngine.Camera.TryGetCullingParameters(UnityEngine.Rendering.ScriptableCullingParameters&)).
2. Optional: Manually update the values of the `ScriptableCullingParameters` struct.
3. Call [ScriptableRenderContext.Cull](xref:UnityEngine.Rendering.ScriptableRenderContext.Cull(UnityEngine.Rendering.ScriptableCullingParameters&)), and store the results in a `CullingResults` struct.
This example code extends the example above, and demonstrates how to clear the render target and then perform a culling operation:
```lang-csharp
/*
This is a simplified example of a custom Scriptable Render Pipeline.
It demonstrates how a basic render loop works.
It shows the clearest workflow, rather than the most efficient runtime performance.
*/
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
public class ExampleRenderPipeline : RenderPipeline {
public ExampleRenderPipeline() {
}
protected override void Render(ScriptableRenderContext context, List<Camera> cameras) {
// Create and schedule a command to clear the current render target
var cmd = new CommandBuffer();
cmd.ClearRenderTarget(true, true, Color.black);
context.ExecuteCommandBuffer(cmd);
cmd.Release();
// Iterate over all Cameras
foreach (Camera camera in cameras)
{
// Get the culling parameters from the current Camera
camera.TryGetCullingParameters(out var cullingParameters);
// Use the culling parameters to perform a cull operation, and store the results
var cullingResults = context.Cull(ref cullingParameters);
}
// Instruct the graphics API to perform all scheduled commands
context.Submit();
}
}
```
<a name="drawing"></a>
### Drawing
Drawing is the process of instructing the graphics API to draw a given set of geometry with given settings.
To draw in SRP, you do the following:
1. Perform a culling operation, as described above, and store the results in a `CullingResults` struct.
2. Create and configure [FilteringSettings](xref:UnityEngine.Rendering.FilteringSettings) struct, which describes how to filter the culling results.
3. Create and configure a [DrawingSettings](xref:UnityEngine.Rendering.DrawingSettings) struct, which describes which geometry to draw and how to draw it.
4. *Optional*: By default, Unity sets the render state based on the Shader object. If you want to override the render state for some or all of the geometry that you are about to draw, you can use a [RenderStateBlock](xref:UnityEngine.Rendering.RenderStateBlock) struct to do this.
5. Call [ScriptableRenderContext.DrawRenderers](xref:UnityEngine.Rendering.ScriptableRenderContext.DrawRenderers(UnityEngine.Rendering.CullingResults,UnityEngine.Rendering.DrawingSettings&,UnityEngine.Rendering.FilteringSettings&)), and pass the structs that you created as parameters. Unity draws the filtered set of geometry, according to the settings.
This example code builds on the examples above, and demonstrates how to clear the render target, perform a culling operation, and draw the resulting geometry:
```lang-csharp
/*
This is a simplified example of a custom Scriptable Render Pipeline.
It demonstrates how a basic render loop works.
It shows the clearest workflow, rather than the most efficient runtime performance.
*/
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
public class ExampleRenderPipeline : RenderPipeline {
public ExampleRenderPipeline() {
}
protected override void Render(ScriptableRenderContext context, List<Camera> cameras) {
// Create and schedule a command to clear the current render target
var cmd = new CommandBuffer();
cmd.ClearRenderTarget(true, true, Color.black);
context.ExecuteCommandBuffer(cmd);
cmd.Release();
// Iterate over all Cameras
foreach (Camera camera in cameras)
{
// Get the culling parameters from the current Camera
camera.TryGetCullingParameters(out var cullingParameters);
// Use the culling parameters to perform a cull operation, and store the results
var cullingResults = context.Cull(ref cullingParameters);
// Update the value of built-in shader variables, based on the current Camera
context.SetupCameraProperties(camera);
// Tell Unity which geometry to draw, based on its LightMode Pass tag value
ShaderTagId shaderTagId = new ShaderTagId("ExampleLightModeTag");
// Tell Unity how to sort the geometry, based on the current Camera
var sortingSettings = new SortingSettings(camera);
// Create a DrawingSettings struct that describes which geometry to draw and how to draw it
DrawingSettings drawingSettings = new DrawingSettings(shaderTagId, sortingSettings);
// Tell Unity how to filter the culling results, to further specify which geometry to draw
// Use FilteringSettings.defaultValue to specify no filtering
FilteringSettings filteringSettings = FilteringSettings.defaultValue;
// Schedule a command to draw the geometry, based on the settings you have defined
context.DrawRenderers(cullingResults, ref drawingSettings, ref filteringSettings);
// Schedule a command to draw the Skybox if required
if (camera.clearFlags == CameraClearFlags.Skybox && RenderSettings.skybox != null)
{
context.DrawSkybox(camera);
}
// Instruct the graphics API to perform all scheduled commands
context.Submit();
}
}
}
```
@@ -0,0 +1,40 @@
---
uid: um-srp-custom-getting-started
---
# Create a custom render pipeline
This page contains information on how to get started with creating your own custom render pipeline based on the Scriptable Render Pipeline (SRP).
<a name="creating-custom-srp"></a>
## Creating a new project and installing the packages needed for a custom render pipeline
These instructions show you how to create a custom render pipeline using the SRP Core package. SRP Core is a package made by Unity that contains a reusable code to help you make your own render pipeline, including boilerplate code for working with platform-specific graphics APIs, utility functions for common rendering operations, and the shader library that URP and HDRP use.
1. Create a new Unity Project.
2. Use Git to create a clone of the [SRP source code repository](https://github.com/Unity-Technologies/Graphics). You can place the SRP source code in any location on your disk, as long as it is not in one of the [reserved Project sub-folders](https://docs.unity3d.com/6000.0/Documentation/Manual/upm-ui-local.html#PkgLocation).
3. Use Git to update your copy of the SRP source code to a branch that is compatible with your version of the Unity Editor. Read [Using the latest version](https://github.com/Unity-Technologies/Graphics#branches-and-package-releases) in the SRP repository documentation for information on branches and versions.
4. Open your Project in Unity, and install the following packages from the SRP source code folder on your disk, in the following order. For information on installing packages from disk, see [Installing a package from a local folder](https://docs.unity3d.com/6000.0/Documentation/Manual/upm-ui-local.html).
* _com.unity.render-pipelines.core_.
* Optional: _com.unity.render-pipelines.shadergraph_. Install this package if you intend to use Shader Graph or modify the Shader Graph source code as part of your custom SRP.
* Optional: _com.unity.render-pipelines.visualeffectgraph_. Install this package if you intend to use Visual Effect Graph or modify the Visual Effect Graph source code as part of your custom SRP.
You can now debug and modify the scripts in your copy of the SRP source code, and see the results of your changes in your Unity Project.
## Creating a custom version of URP or HDRP
The Universal Render Pipeline (URP) and the High Definition Render Pipeline (HDRP) offer extensive customization options to help you achieve the graphics and performance you need. However, if you want even more control, you can create a custom version of one of these render pipelines, and modify the source code.
Follow steps 1-3 in the section above, **Creating a new Project and installing the packages needed for a custom SRP**. When you reach step 4, install the following packages in the following order:
**URP:**
* _com.unity.render-pipelines.core_
* _com.unity.render-pipelines.shadergraph_
* _com.unity.render-pipelines.universal_
**HDRP:**
* _com.unity.render-pipelines.core_
* _com.unity.render-pipelines.shadergraph_
* _com.unity.render-pipelines.high-defintion_
@@ -0,0 +1,19 @@
---
uid: um-srp-custom
---
# Creating a custom render pipeline
Unity provides two prebuilt render pipelines based on the Scriptable Render Pipeline (SRP): the High Definition Render Pipeline (HDRP), and the Universal Render Pipeline (URP). HDRP and URP offer extensive customization options; however, if you want even more control over your rendering pipeline, you can create your own custom render pipeline based on SRP.
| **Page** | **Description** |
| --- | --- |
| [Create a custom Scriptable Render Pipeline](srp-custom-getting-started.md) | Install the packages needed for a custom render pipeline based on SRP, or create a custom version of URP or HDRP. |
| [Create a Render Pipeline Asset and Render Pipeline Instance in a custom render pipeline](srp-creating-render-pipeline-asset-and-render-pipeline-instance.md) | Create scripts that inherit from `RenderPipelineAsset` and `RenderPipeline`, then create a Render Pipeline Asset. |
| [Create a simple render loop in the Scriptable Render Pipeline](srp-creating-simple-render-loop.md) | Create a simple loop to clear the render target, perform a culling operation, and draw geometry. |
| [Extend a Scriptable Render Pipeline with command buffers or API calls](srp-using-scriptable-render-context.md) | Use the `ScriptableRenderContext` API to configure and schedule rendering commands. |
| [Scriptable Render Pipeline callbacks reference](srp-callbacks-reference.md) | Learn about the callbacks you can use to call your C# code at specific times. |
## Additional resources
- [Render pipelines](https://docs.unity3d.com/6000.0/Documentation/Manual/render-pipelines.html)
@@ -0,0 +1,55 @@
---
uid: um-srp-using-scriptable-render-context
---
# Execute rendering commands in a custom render pipeline
This page explains how to schedule and execute rendering commands in the Scriptable Render Pipeline (SRP)ScriptableRenderPipeline, either by using CommandBuffers or by making direct API calls to the ScriptableRenderContext. The information on this page is applicable to the Universal Render Pipeline (URP), the High Definition Render Pipeline (HDRP), and custom render pipelines that are based on SRP.
In SRP, you use C# scripts to configure and schedule rendering commands. You then tell Unity's low-level graphics architecture to execute them, which sends instructions to the graphics API.
The main way of doing this is by making API calls to the ScriptableRenderContext, but you can also execute CommandBuffers immediately.
## Using the ScriptableRenderContext APIs
In SRP, the ScriptableRenderContext class acts as an interface between the C# render pipeline code and Unity's low-level graphics code. SRP rendering works using delayed execution; you use the ScriptableRenderContext to build up a list of rendering commands, and then you tell Unity to execute them. Unity's low-level graphics architecture then sends instructions to the graphics API.
To schedule rendering commands, you can:
* Pass [CommandBuffers](xref:UnityEngine.Rendering.CommandBuffer) to the ScriptableRenderContext, using [ScriptableRenderContext.ExecuteCommandBuffer](xref:UnityEngine.Rendering.ScriptableRenderContext.ExecuteCommandBuffer(UnityEngine.Rendering.CommandBuffer))
* Make direct API calls to the Scriptable Render Context, such as [ScriptableRenderContext.Cull](xref:UnityEngine.Rendering.ScriptableRenderContext.Cull(UnityEngine.Rendering.ScriptableCullingParameters&)) or [ScriptableRenderContext.DrawRenderers](xref:UnityEngine.Rendering.ScriptableRenderContext.DrawRenderers(UnityEngine.Rendering.CullingResults,UnityEngine.Rendering.DrawingSettings&,UnityEngine.Rendering.FilteringSettings&))
To tell Unity to perform the commands that you have scheduled, call [ScriptableRenderContext.Submit](xref:UnityEngine.Rendering.ScriptableRenderContext.Submit). Note that it does not matter whether you used a CommandBuffer to schedule the command, or whether you scheduled the command by calling an API; Unity schedules all rendering commands on the ScriptableRenderContext in the same way, and does not execute any of them until you call `Submit()`.
This example code demonstrates how to schedule and perform a command to clear the current render target, using a CommandBuffer.
```lang-csharp
using UnityEngine;
using UnityEngine.Rendering;
using System.Collections.Generic;
public class ExampleRenderPipeline : RenderPipeline
{
public ExampleRenderPipeline() {
}
protected override void Render(ScriptableRenderContext context, List<Camera> cameras) {
// Create and schedule a command to clear the current render target
var cmd = new CommandBuffer();
cmd.ClearRenderTarget(true, true, Color.red);
context.ExecuteCommandBuffer(cmd);
cmd.Release();
// Tell the Scriptable Render Context to tell the graphics API to perform the scheduled commands
context.Submit();
}
}
```
## Executing CommandBuffers immediately
You can execute CommandBuffers immediately without using the ScriptableRenderContext, by calling [Graphics.ExecuteCommandBuffer](xref:UnityEngine.Graphics.ExecuteCommandBuffer(UnityEngine.Rendering.CommandBuffer)). Calls to this API take place outside of the render pipeline.
## Additional information
For more information on commands that you can schedule using CommandBuffers, see [CommandBuffers API documentation](xref:UnityEngine.Rendering.CommandBuffer).
@@ -0,0 +1,29 @@
# What's new in SRP Core version 12 / Unity 2021.2
This page contains an overview of new features, improvements, and issues resolved in version 12 of the Core Render Pipeline package, embedded in Unity 2021.2.
## Improvements
### RTHandle System and MSAA
The RTHandle System no longer requires you to specify the number of MSAA samples at initialization time. This means that you can now set the number of samples on a per texture basis, rather than for the whole system.
In practice, this means that the initialization APIs no longer require MSAA related parameters. The `Alloc` functions have replaced the `enableMSAA` parameter and enables you to explicitly set the number of samples.
### New API to disable runtime Rendering Debugger UI
It is now possible to disable the Rendering Debugger UI at runtime by using [DebugManager.enableRuntimeUI](https://docs.unity3d.com/Packages/com.unity.render-pipelines.core@latest/api/UnityEngine.Rendering.DebugManager.html#UnityEngine_Rendering_DebugManager_enableRuntimeUI).
## Added
### High performance sorting algorithms in CoreUnsafeUtils
New high performance sorting algorithms in the CoreUnsafeUtils helper methods. The new sorting algorithms include:
* RadixSort - ideal for very large lists, more then 512 elements.
* MergeSort (non recursive) - ideal for mid size lists, less than 512 elements.
* InsertionSort - ideal for very small lists, less than 32 elements.
The sorting algorithms only work on uint elements. They include methods that support standard c# arrays, NativeArray objects or raw pointers.
RadixSort and MergeSort require support array data, which can be allocated by the user, or allocated automatically via ref parameter passing. InsertionSort is in-place and does not require support data.
These algorithms are compatible with burst kernels when using raw pointers or NativeArray. Currently HDRP utilizes them to sort lights in the CPU lightloop.
@@ -0,0 +1,10 @@
# What's new in SRP Core version 13 / Unity 2022.1
This page contains an overview of new features, improvements, and issues resolved in version 13 of the Core Render Pipeline package, embedded in Unity 2022.1.
## Added
### AMD Fidelity FX Super Sampling helper API - FSRUtils
Introducing new stream lined API for AMD Fidelity FX Super Sampling. The new API is located in the static class FSRUtils and allows scriptable pipelines to have direct access / implement and integrate easilty FSR super sampler.
For more information please review the API located in Runtime/Utitilies/FSRUtils.cs
@@ -0,0 +1,37 @@
# What's new in SRP Core 17 / Unity 6
**Note:** Starting with 17.2 (Unity 6.2), refer to [What’s new in Unity](xref:um-whats-new) for the latest updates and improvements.
## What's new in SRP Core 17.1 / Unity 6.1
The following are the new features and improvements added to the SRP Core package 17.1, embedded Unity 6.1.
## Added
### Disable pass merging in the render graph system
Added a render graph debug setting that allows you to temporarily disable pass merging to isolate issues or investigate performance changes.
### New variable rate shading (VRS) API
You can use the new variable rate shading (VRS) API to control the shading rate of Scriptable Renderer Features, and balance between GPU performance and image quality. This API is supported on DirectX 12, Vulkan, and compatible consoles.
VRS is also known as fragment shading rate, and is a technique which allows you to decouple the rasterization and pixel shading rate. VRS can vary the shading rate across the screen space by using a shading rate image, which encodes the shading rates for different regions of the screen at different rates. When setting a lower shading rate, the pixel shader will execute at a lower frequency, which can drastically improve GPU performance.
![A scene with a shading rate image (SRI) in the corner. The blue and red areas represent the different shading rates of the UI and the game visuals.](Images/srp-vrs-example.jpg)
For more information about VRS, refer to the [Optimize Renderer Features with Variable Rate Shading in Unity 6.1](https://discussions.unity.com/t/optimize-renderer-features-with-variable-rate-shading-in-unity-6-1/1605893/1) Unity Discussions page.
## What's new in SRP Core version 17.0 / Unity 6.0
The following is an overview of new features, improvements, and issues resolved in version 17 of the Scriptable Render Pipeline (SRP) Core package, embedded in Unity 6.
## Improvements
### Render graph system optimization
The render graph system API and compiler are now carefully optimized to reduce their cost on the main CPU thread. To prevent Unity compiling the render graph each frame, there's now a caching system so Unity only compiles when the rendering is different from the previous frame. This means performance on the main CPU thread should be faster, especially in non-development builds.
### Native Render Pass support in the render graph system
The render graph system API now provides automatic Native Render Pass support using the `AddRasterRenderPass` API. This means Unity can use framebuffer fetch operations on platforms with tile-based GPUs, which improves performance.
Native Render Pass support is implemented in the Universal Render Pipeline (URP). For more information, refer to [Render graph system](https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@17.0/manual/render-graph.html) in the URP manual.
**Note:** You can't use the `AddRasterRenderPass` API with the existing `AddRenderPass` API. Instead, use the new `AddComputePass` and `AddUnsafePass` APIs.

Some files were not shown because too many files have changed in this diff Show More