Skip to content

Commit 75a39ec

Browse files
Merge pull request #8179 from Unity-Technologies/internal/master
Internal/master
2 parents f4b33bf + 0874aaa commit 75a39ec

File tree

1,581 files changed

+97684
-10691
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

1,581 files changed

+97684
-10691
lines changed
105 KB
Loading
74 KB
Loading

Packages/com.unity.render-pipelines.core/Documentation~/TableOfContents.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,14 @@
3535
* [Look Dev](Look-Dev.md)
3636
* [Environment Library](Look-Dev-Environment-Library.md)
3737
* [Rendering Debugger](Rendering-Debugger.md)
38-
* [Light Anchor](view-lighting-tool.md)
38+
* [Light Anchor](view-lighting-tool.md)
39+
* [Unified Raytracing API](UnifiedRayTracing/unified-ray-tracing-api.md)
40+
* [Get started with ray tracing](UnifiedRayTracing/get-started.md)
41+
* [Ray tracing workflow](UnifiedRayTracing/workflow.md)
42+
* [Create the ray tracing context](UnifiedRayTracing/create-ray-tracing-context.md)
43+
* [Create an acceleration structure](UnifiedRayTracing/create-acceleration-structure.md)
44+
* [Create a unified ray tracing shader](UnifiedRayTracing/create-shader.md)
45+
* [Write your ray tracing code](UnifiedRayTracing/write-shader.md)
46+
* [Execute your ray tracing code](UnifiedRayTracing/execute-shader.md)
47+
* [Sample code: Tracing camera rays](UnifiedRayTracing/trace-camera-rays-full-sample.md)
48+
* [Unified ray tracing shader code reference](UnifiedRayTracing/shader-code-reference.md)
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Create an acceleration structure
2+
[`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.
3+
4+
Create an acceleration structure with the following code:
5+
```C#
6+
var options = new AccelerationStructureOptions();
7+
IRayTracingAccelStruct rtAccelStruct = rtContext.CreateAccelerationStructure(options);
8+
```
9+
10+
## Build options
11+
[`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.
12+
13+
The following fields can be configured:
14+
15+
|Field|Description|
16+
|-|-|
17+
|`buildFlags`|Adjust the buildFlags to prioritize either faster construction of the acceleration structure or faster ray tracing.|
18+
|`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.|
19+
20+
The following example demonstrates how to get the best ray tracing performance. These options make the acceleration structure longer to build, however.
21+
```HLSL
22+
var options = new AccelerationStructureOptions() {
23+
buildFlags = BuildFlags.PreferFastTrace,
24+
useCPUBuild = true
25+
}
26+
```
27+
28+
## Populate the acceleration structure
29+
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:
30+
```C#
31+
var instanceDesc = new MeshInstanceDesc(mesh, 0 /*subMeshIndex*/);
32+
instanceDesc.localToWorldMatrix = /* desired transform */;
33+
rtAccelStruct.AddInstance(instanceDesc);
34+
```
35+
36+
To trace rays against all the Mesh-based GameObjects in your scene, add them to the [`IRayTracingAccelStruct`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct). For example:
37+
```C#
38+
var meshRenderers = UnityEngine.Object.FindObjectsByType<MeshRenderer>(FindObjectsSortMode.None);
39+
foreach (var renderer in meshRenderers)
40+
{
41+
var mesh = renderer.GetComponent<MeshFilter>().sharedMesh;
42+
int subMeshCount = mesh.subMeshCount;
43+
44+
for (int i = 0; i < subMeshCount; ++i)
45+
{
46+
var instanceDesc = new MeshInstanceDesc(mesh, i);
47+
instanceDesc.localToWorldMatrix = renderer.transform.localToWorldMatrix;
48+
rtAccelStruct.AddInstance(instanceDesc);
49+
}
50+
}
51+
```
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Create the ray tracing context
2+
3+
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.
4+
5+
Follow these steps:
6+
1. Load the ray tracing resources.
7+
2. Create the context.
8+
9+
## Load the ray tracing resources
10+
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.
11+
12+
If your project uses SRP (Scriptable Render Pipeline), load the resources via [`RayTracingResources.LoadFromRenderPipelineResources`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext.LoadFromRenderPipelineResources()). This always works in the Editor.
13+
```C#
14+
var rtResources = new RayTracingResources();
15+
bool result = rtResources.LoadFromRenderPipelineResources();
16+
```
17+
You can instruct Unity to also include the resources in Player builds:
18+
```C#
19+
using UnityEngine.Rendering;
20+
using UnityEngine.Rendering.UnifiedRayTracing;
21+
22+
#if UNITY_EDITOR
23+
class MyURTStripping: IRenderPipelineGraphicsSettingsStripper<RayTracingRenderPipelineResources>
24+
{
25+
public bool active => true;
26+
public bool CanRemoveSettings(RayTracingRenderPipelineResources settings) => false;
27+
}
28+
#endif
29+
```
30+
31+
You can also load the resources via the Asset Database:
32+
```C#
33+
var rtResources = new RayTracingResources();
34+
rtResources.Load();
35+
```
36+
**Note:** Since the Player doesn't give access to the Asset Database, this method only works in the Editor.
37+
38+
To load the [`RayTracingResources`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingResources) in the Player, you can also build the **unifiedraytracing** AssetBundle. For more information about how to build and load AssetBundles, refer to [AssetBundles](xref:AssetBundlesIntro).
39+
```C#
40+
var rtResources = new RayTracingResources();
41+
42+
// Load the AssetBundle
43+
var asssetBundle = AssetBundle.LoadFromFile("Assets/pathToYourBuiltAssetBundles/unifiedraytracing");
44+
45+
// Load the RayTracingResources
46+
rtResources.LoadFromAssetBundle(asssetBundle);
47+
```
48+
49+
## Create the context
50+
Once the [`RayTracingResources`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingResources) are loaded, use them to create the [`RayTracingContext`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext).
51+
```C#
52+
// Choose a backend
53+
var backend = RayTracingContext.IsBackendSupported(RayTracingBackend.Hardware) ? RayTracingBackend.Hardware : RayTracingBackend.Compute;
54+
55+
// Create the context
56+
var context = new RayTracingContext(backend, rtResources);
57+
```
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Create a unified ray tracing shader
2+
3+
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.
4+
5+
To create both a `.raytrace` shader and a `.compute` shader, write your shader code in a unified ray tracing shader (`.urtshader`).
6+
7+
To create a shader, follow these steps:
8+
9+
1. Create the shader asset file.
10+
2. Load the shader.
11+
12+
## Create the shader asset file
13+
To create a unified ray tracing shader:
14+
15+
1. Launch the Unity Editor.
16+
17+
1. In the **Project** window, open the **Assets** folder.
18+
19+
1. Open or create the folder in which you want to create your shader.
20+
21+
1. Open the context menu (right-click) and select **Create** &gt; **Shader** &gt; **Unified Ray Tracing Shader**.
22+
23+
1. Enter a name for the shader.
24+
25+
Ray tracing occurs in the `RayGenExecute` function. You can edit the example code snippet.
26+
27+
For more information about writing a ray tracing shader, refer to [Write your shader code](write-shader.md).
28+
29+
## Load the shader
30+
To load the `.urtshader` file in the Editor, use the following code snippet:
31+
```C#
32+
IRayTracingShader shader = rtContext.LoadRayTracingShader("Assets/yourShader.urtshader");
33+
```
34+
35+
To load the shader in the Player, add the `.urtshader` shader to an <xref:UnityEngine.AssetBundle> then load it with the following:
36+
```C#
37+
// Load the AssetBundle
38+
var asssetBundle = AssetBundle.LoadFromFile("Assets/pathToYourBuiltAssetBundles/yourAssetBundle");
39+
40+
// Load the shader
41+
IRayTracingShader shader = rtContext.LoadRayTracingShaderFromAssetBundle(asssetBundle, "Assets/yourShader.urtshader");
42+
```
43+
44+
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)).
45+
46+
[`RayTracingContext.LoadRayTracingShaderFromAssetBundle`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext.LoadRayTracingShaderFromAssetBundle(UnityEngine.AssetBundle,System.String)) is a convenience function that performs the following operations:
47+
```C#
48+
public IRayTracingShader LoadRayTracingShaderFromAssetBundle(AssetBundle assetBundle, string name)
49+
{
50+
Object asset = assetBundle.LoadAsset(name, BackendHelpers.GetTypeOfShader(BackendType));
51+
return CreateRayTracingShader(asset);
52+
}
53+
```
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Execute your ray tracing code
2+
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.
3+
4+
To execute your ray tracing shader on the GPU:
5+
1. Build the acceleration structure.
6+
2. Bind resources to the shader.
7+
3. Dispatch the shader.
8+
9+
## Build the acceleration structure
10+
You must build the acceleration structure after you create it and every time you modify it. For example:
11+
```C#
12+
IRayTracingAccelStruct rtAccelStruct = /* your acceleration structure */;
13+
var cmd = new CommandBuffer();
14+
15+
// A scratch buffer is required to build the acceleration structure, this helper function allocates one with the required size.
16+
GraphicsBuffer buildScratchBuffer = RayTracingHelper.CreateScratchBufferForBuild(rtAccelStruct);
17+
18+
// Build the ray tracing acceleration structure
19+
rtAccelStruct.Build(cmd, buildScratchBuffer);
20+
```
21+
22+
## Bind resources to the shader
23+
You must bind the acceleration structure and any additional GPU resources declared in your shader, such as constants, buffers, and textures. For example:
24+
```C#
25+
IRayTracingShader rtShader = /* your shader */;
26+
27+
// Bind the acceleration structure. It is declared in the shader as: UNIFIED_RT_DECLARE_ACCEL_STRUCT(_YourAccelStruct);
28+
rtShader.SetAccelerationStructure(cmd, "_YourAccelStruct", rtAccelStruct);
29+
30+
// Bind the other GPU resources (constants/uniforms, buffers and textures)
31+
rtShader.SetIntParam(cmd, Shader.PropertyToID("_YourInteger"), 5);
32+
```
33+
34+
## Dispatch the shader
35+
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:
36+
```C#
37+
const int threadCountX = 256, threadCountY = 256, threadCountZ = 1;
38+
39+
// A scratch buffer is required to trace rays, this helper function allocates one with the required size.
40+
GraphicsBuffer traceScratchBuffer = RayTracingHelper.CreateScratchBufferForTrace(rtShader, threadCountX, threadCountY, threadCountZ);
41+
42+
// Dispatch rays. Workgrid dimensions are supplied in threads, not workgroups
43+
rtShader.Dispatch(cmd, traceScratchBuffer, threadCountX, threadCountY, threadCountZ);
44+
45+
// Execute the command buffer to effectively run all the previously registered commands.
46+
Graphics.ExecuteCommandBuffer(cmd);
47+
```
48+
49+
**Note:** If its size satisfies the requirements for both operations, you can use the same scratch buffer for both the build and trace steps.
50+
51+
52+
53+
54+
55+
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Get started with ray tracing
2+
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,
3+
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.
4+
5+
## Backends
6+
The following backends are available:
7+
- `Hardware`: Requires a GPU that supports hardware-accelerated ray tracing. This backend uses the [`RayTracingAccelerationStructure`](xref:UnityEngine.Rendering.RayTracingAccelerationStructure) API.
8+
- `Compute` : Software implementation of ray tracing that works only on GPUs that support compute shaders.
9+
10+
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.
11+
12+
## Main concepts
13+
The API entry point is the [`RayTracingContext`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext) which is initialized for a specific backend.
14+
15+
The [`RayTracingContext`](xref:UnityEngine.Rendering.UnifiedRayTracing.RayTracingContext) enables you to create the 2 essential objects you need to perform ray tracing:
16+
- an acceleration structure ([`IRayTracingAccelStruct`]((xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct))) which represents the geometry to trace rays against.
17+
- a shader ([`IRayTracingShader`]((xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingShader))) which contains your ray tracing code that will run on the GPU.
18+
19+
![RayTracingContext class features](../Images/RayTracingContext.jpg)
20+
21+
For more information, refer to [Using the API workflow](workflow.md).
22+
23+
## Limitations
24+
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).
25+
- 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
26+
[`IRayTracingAccelStruct.RemoveInstance`](xref:UnityEngine.Rendering.UnifiedRayTracing.IRayTracingAccelStruct.RemoveInstance(System.Int32)) to update the acceleration structure.
27+
- The API supports only ray tracing with mesh geometries.
28+
- 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`).
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# Unified ray tracing shader code reference
2+
This section presents the different functions and structs provided by the API for tracing rays in a shader.
3+
4+
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.
5+
6+
## function TraceRayClosestHit
7+
```HLSL
8+
Hit TraceRayClosestHit(DispatchInfo dispatchInfo, RayTracingAccelStruct accelStruct, uint instanceMask, Ray ray, uint rayFlags)
9+
```
10+
Searches for intersections between a ray and an acceleration structure. It returns hit information about the closest triangle encountered along the ray.
11+
### Parameters
12+
|Type|Name|Description|
13+
|-|-|-|
14+
|[`DispatchInfo`](#struct-dispatchinfo)|*dispatchInfo*|The dispatch info. Must be the value that is passed by `RayGenExecute`.|
15+
|`RayTracingAccelStruct`|*accelStruct*|The acceleration structure to test the ray against.|
16+
|`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.|
17+
|[`Ray`](#struct-ray)|*ray*|Describes the ray segment that is intersected against the acceleration structure.|
18+
|`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>|
19+
### Returns
20+
[`Hit`](#struct-hit) containing geometry information about the hit triangle. When no primitive has intersected with the ray, `hit.IsValid()` returns false.
21+
22+
## function TraceRayAnyHit
23+
```HLSL
24+
bool TraceRayAnyHit(DispatchInfo dispatchInfo, RayTracingAccelStruct accelStruct, uint instanceMask, Ray ray, uint rayFlags)
25+
```
26+
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.
27+
### Parameters
28+
|Type|Name|Description|
29+
|-|-|-|
30+
|[`DispatchInfo`](#struct-dispatchinfo)|*dispatchInfo*|The dispatch info. Must be the value that is passed by `RayGenExecute`.|
31+
|`RayTracingAccelStruct`|*accelStruct*|The acceleration structure to test the ray against.|
32+
|`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.|
33+
|[`Ray`](#struct-ray)|*ray*|Describes the ray segment that is intersected against the acceleration structure.|
34+
|`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>|
35+
### Returns
36+
A boolean that is true if any primitive was hit by the ray.
37+
38+
## struct Ray
39+
Describes a ray.
40+
The `tMin` and `tMax` fields define the segment of the ray to be tested against the acceleration structures's primitives.
41+
Mathematically, the ray consists of all the points defined as `P = ray.origin + t * ray.direction`, where `ray.tMin ≤ t ≤ ray.tMax`.
42+
### Fields
43+
|Type|Name|Description|
44+
|-|-|-|
45+
|`float3`|*origin*|The ray's origin.|
46+
|`float3`|*direction*|The ray's direction.|
47+
|`float`|*tMin*|The ray's starting point.|
48+
|`float`|*tMax*|The ray's endpoint.|
49+
50+
## struct DispatchInfo
51+
Provides information about the current thread that is invoked.
52+
### Fields
53+
|Type|Name|Description|
54+
|-|-|-|
55+
|`uint3`|*dispatchThreadID*|Same semantic as `SV_DispatchThreadID`.|
56+
|`uint`|*localThreadIndex*|Same semantic as `SV_GroupIndex`.|
57+
|`uint3`|*dispatchDimensionsInThreads*|Total numbers of threads dispatched in the X, Y, and Z workgrid directions.|
58+
|`uint`|*globalThreadIndex*|Global thread index that is unique within the workgrid.|
59+
60+
## struct Hit
61+
Describes a Hit.
62+
### Fields
63+
|Type|Name|Description|
64+
|-|-|-|
65+
|`uint`|*instanceID*|Matches the `instanceID` supplied from C# in `MeshInstanceDesc.instanceID`.|
66+
|`uint`|*primitiveIndex*|Index of the hit triangle in its source Mesh.|
67+
|`float2`|*uvBarycentrics*|Barycentric coordinates of the hit triangle.|
68+
|`float`|*hitDistance*|Defines the hit position: `hitPos = ray.origin + ray.direction * hit.hitDistance`.|
69+
|`bool`|*isFrontFace*|Indicates whether the hit triangle is front-facing or back-facing.|
70+
### Methods
71+
```HLSL
72+
bool IsValid();
73+
```
74+
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 commit comments

Comments
 (0)