BorrowedTorch.RayTracing 1.7.1

Prefix Reserved
dotnet add package BorrowedTorch.RayTracing --version 1.7.1
                    
NuGet\Install-Package BorrowedTorch.RayTracing -Version 1.7.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BorrowedTorch.RayTracing" Version="1.7.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BorrowedTorch.RayTracing" Version="1.7.1" />
                    
Directory.Packages.props
<PackageReference Include="BorrowedTorch.RayTracing" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BorrowedTorch.RayTracing --version 1.7.1
                    
#r "nuget: BorrowedTorch.RayTracing, 1.7.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BorrowedTorch.RayTracing@1.7.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BorrowedTorch.RayTracing&version=1.7.1
                    
Install as a Cake Addin
#tool nuget:?package=BorrowedTorch.RayTracing&version=1.7.1
                    
Install as a Cake Tool

BorrowedTorch.RayTracing

Ray casting for MonoGame on the GPU and the CPU: a binned-SAH bounding volume hierarchy, per-mesh bottom-level and per-scene top-level acceleration structures (BLAS/TLAS), their upload to structured buffers, any-hit and closest-hit traversals in HLSL, and the depth/normal G-buffer that screen-space traced passes start from.

What you get:

  • CPU queries: closest hit (picking, placement) and any hit (visibility), with barycentrics for attribute lookup.
  • GPU queries: RtTraceAny and RtTraceClosest in a compute (or pixel) shader. Shadows, ambient occlusion and other occlusion-style effects can be written on top of the first; bounced light and reflections, which need to know what a ray landed on, on top of the second.
  • Incremental updates: re-declare the scene every frame. The TLAS works out on its own whether that means nothing, a refit or a rebuild, and the GPU copy uploads only what changed. An idle scene costs a few comparisons a frame.

It does not shade hits or sort them by material: it answers "is anything in the way" and "where does this ray hit", on both sides, and what is there - a material, a colour - is yours to look up by what the hit names.

Requirements

  • BorrowedTorch's MonoGame compute fork: BorrowedTorch.MonoGame.Framework.Compute.WindowsDX 3.8.6.101 (DirectX 11, HiDef profile, compute shaders and structured buffers), which comes with the package. 1.5.0 and earlier came with the old fork, MonoGame.Framework.Compute.WindowsDX.NoMemoryLeak 3.8.3.1.
  • Shaders compiled for DirectX_11, kernels as cs_5_0, by that fork's effect compiler: it loads effects of its own format (MGFX 100) only, and the old fork's content builder (dotnet-mgcb-compute 3.8.3) writes effects it refuses.
  • Windows, .NET 8 or later.

Installing

dotnet add package BorrowedTorch.RayTracing

The two HLSL headers, RayTraversal.fxh and GBuffer.fxh, are delivered to your build output at Content/Effects/Lib/. If you compile effects at runtime from that folder, #include "Lib/RayTraversal.fxh" from an effect in Content/Effects finds them as they are. If you build effects with the content pipeline instead, copy the two headers beside your own effects: they are plain HLSL with no further includes.

Concepts

Type What it is
ITriangleMesh Your mesh, as the library reads it: a triangle count and three positions per triangle - and, optionally, texture coordinates and normals.
MeshBlas A BVH over one mesh's triangles, in the mesh's own space. Built once per mesh, shared by every instance of it.
Tlas A BVH over the scene's instances: a MeshBlas placed by a world matrix, under an id of yours.
GpuAccelerationStructure The GPU copy of a Tlas and every MeshBlas it uses, as structured buffers.
GBuffer Linear view-space depth and view-space normals, the input a screen-space traced pass reconstructs points from.
RayTracingFlags Per-instance switches a query can require: CastsShadow, VisibleToGI, Pickable - and AlphaTested, for an instance with holes in it (section 6a).
AnyHitFilter Your test of whether a hit on an alpha-tested instance counts, on the CPU; RtAnyHit is its HLSL twin.

Coordinates are MonoGame's: row vectors, p * M. Rays are traced in the space the instances' world matrices put them in, so a shader has to hand the traversal origins in that same space.

1. Expose your meshes

Implement ITriangleMesh over whatever your engine keeps on the CPU. Triangle lists only: convert strips first.

using BorrowedTorch.RayTracing;
using Microsoft.Xna.Framework;

public sealed class IndexedTriangles : ITriangleMesh
{
    private readonly Vector3[] _positions;
    private readonly int[] _indices;

    public IndexedTriangles(Vector3[] positions, int[] indices)
    {
        _positions = positions;
        _indices = indices;
    }

    public int TriangleCount => _indices.Length / 3;

    public void GetTriangle(int triangle, out Vector3 v0, out Vector3 v1, out Vector3 v2)
    {
        v0 = _positions[_indices[triangle * 3]];
        v1 = _positions[_indices[triangle * 3 + 1]];
        v2 = _positions[_indices[triangle * 3 + 2]];
    }
}

2. Build a BLAS per mesh

// Once per mesh. Null for a mesh with no triangles - there is nothing to trace.
MeshBlas? crateBlas = MeshBlas.Build(new IndexedTriangles(cratePositions, crateIndices));

Share one MeshBlas between every instance of the mesh. Build a new one if the mesh itself is replaced. The mesh is read twice at build time and once per refit; between those, the BLAS keeps its own copy of the triangles (MeshBlas.Triangles, a vertex and two edges each, in the tree's order), which is what both the CPU walks and the GPU upload read.

A large tree - from some 32,000 triangles, or instances - is built on several threads, and the call returns once it is done. The tree is exactly the one a single thread would build, on any number of cores; the mesh itself is still read on the calling thread only.

3. Declare the scene every frame

var tlas = new Tlas();

void UpdateScene()
{
    tlas.BeginUpdate();

    foreach (var obj in sceneObjects)
        tlas.Add(obj.Id, obj.Blas, obj.WorldMatrix);   // obj.Id is any ulong of yours, stable per object

    TlasUpdateResult result = tlas.EndUpdate();         // Unchanged, Refitted or Rebuilt
}
  • Declare in a stable order. Each Add is compared against what the same position held last update. A different order is still correct, but reads as a structural change and forces a rebuild.
  • The id is yours. It is never interpreted beyond equality, and comes back in every hit. An ECS entity of an id and a generation packs into the 64 bits, so a recycled id reads as a new object.
  • Flags default to RayTracingFlags.Default (everything). Pass fewer to keep an object out of some queries: tlas.Add(id, blas, world, RayTracingFlags.Pickable) is clickable but casts no shadow.
  • Odd transforms. A transform that flattens an object (a zero scale on one axis) is still traced, through a stand-in a hair thick. One that collapses it to a line or a point, or puts it at infinity, is left out.
  • Rebuilds are automatic. Moving objects only refits the tree. It rebuilds when the refit has grown the root's area 2x or the tree's surface-area cost 1.5x.
  • An unchanged instance costs a few comparisons. Its box is reused as long as its transform and its BLAS (by version) are what they were.

4. Query on the CPU

Closest hit, for picking:

// Unproject the cursor into a world-space ray (MonoGame does the maths).
Vector3 near = viewport.Unproject(new Vector3(mouse.X, mouse.Y, 0f), projection, view, Matrix.Identity);
Vector3 far = viewport.Unproject(new Vector3(mouse.X, mouse.Y, 1f), projection, view, Matrix.Identity);
var ray = new Ray(near, Vector3.Normalize(far - near));

if (tlas.Intersect(ray, float.MaxValue, out RayHit hit, RayTracingFlags.Pickable))
{
    ulong picked = hit.InstanceId;
    Vector3 point = ray.Position + ray.Direction * hit.Distance;
}

hit.Distance is the ray parameter t: a world distance for a unit-length direction. The direction does not have to be unit length; distances are then in its parameterisation.

Any hit, for visibility. It stops at the first occluder and is cheaper than asking for the nearest:

// Start a little off the surface, or the ray finds the surface it starts on.
var shadowRay = new Ray(point + surfaceNormal * 0.02f, directionToLight);

bool inShadow = tlas.IntersectAny(shadowRay, distanceToLight, RayTracingFlags.CastsShadow);

Attributes at a hit: hit.TriangleIndex and the barycentrics hit.U, hit.V (the third weight is 1 - U - V). They interpolate any per-vertex attribute you keep. Positions are in the mesh's own space:

TlasInstance instance = tlas.Instances[hit.InstanceIndex];
instance.Blas.Geometry.GetTriangle(hit.TriangleIndex, out var a, out var b, out var c);

Vector3 local = a * (1 - hit.U - hit.V) + b * hit.U + c * hit.V;
Vector3 world = Vector3.Transform(local, instance.World);

The structures are not thread-safe: do not query a Tlas while it is being updated.

5. Upload to the GPU

var acceleration = new GpuAccelerationStructure(graphicsDevice);

// Every frame, after tlas.EndUpdate(), on the thread that owns the device.
acceleration.Upload(tlas);

Upload sends a mesh's geometry when its BLAS first appears - appended after the meshes already there - and re-sends a refitted BLAS in place. The scene half (the tree and one record per instance) goes when the tree or an instance's flags changed. The buffers are allocated with room to spare, so an object added or removed does not usually reallocate anything; everything is laid out afresh only when that room runs out, which is also when meshes nothing uses any more are dropped. A frame with no changes uploads nothing. IsReady is false while the scene is empty. Version moves whenever the buffers change, so a pass can keep last frame's result while it has not moved.

GpuAccelerationStructure and GBuffer (section 7) own GPU resources: Dispose them with the device's other resources.

6. Trace in a shader

A compute kernel that marks each pixel lit or shadowed by one directional light. It reads the G-buffer (section 7) for the point to trace from:

#include "Lib/RayTraversal.fxh"
#include "Lib/GBuffer.fxh"

Texture2D<float>    DepthMap;     // GBuffer.Depth
Texture2D<float4>   NormalMap;    // GBuffer.Normal
RWTexture2D<float4> ShadowMask;   // 1 = lit, 0 = shadowed

float4x4 InverseView;             // view -> the space the instances were declared in
float4x4 InverseProjection;
float4   ScreenSize;              // (width, height, 1 / width, 1 / height)
float3   ToLight;                 // world space, towards the light
float    NormalBias = 0.02;

[numthreads(8, 8, 1)]
void CS(uint3 id : SV_DispatchThreadID)
{
    if (id.x >= (uint) ScreenSize.x || id.y >= (uint) ScreenSize.y) return;

    float depth = DepthMap[id.xy];

    if (depth <= 0.0)               // nothing drawn here
    {
        ShadowMask[id.xy] = float4(1.0, 1.0, 1.0, 1.0);
        return;
    }

    float3 position = GBufferWorldPosition(int2(id.xy), ScreenSize, depth, InverseProjection, InverseView);
    float3 normal   = GBufferWorldNormal(NormalMap[id.xy], InverseView);

    // A directional light is far away, not infinitely far: give the ray a long, finite length.
    bool blocked = RtTraceAny(position + normal * NormalBias, ToLight, 1e8, RT_FLAG_CASTS_SHADOW);

    float lit = blocked ? 0.0 : 1.0;
    ShadowMask[id.xy] = float4(lit, lit, lit, 1.0);
}

technique Shadow
{
    pass P0
    {
        ComputeShader = compile cs_5_0 CS();
    }
}

Dispatch it from C#. Bind hands the kernel the buffers and the node count under the names RayTraversal.fxh declares:

// A texture a compute shader can write to.
var shadowMask = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color, ShaderAccess.ReadWrite);

if (acceleration.IsReady && gBuffer.IsCurrent)
{
    shadowEffect.Parameters["DepthMap"].SetValue(gBuffer.Depth);
    shadowEffect.Parameters["NormalMap"].SetValue(gBuffer.Normal);
    shadowEffect.Parameters["ShadowMask"].SetValue(shadowMask);
    shadowEffect.Parameters["InverseView"].SetValue(Matrix.Invert(view));
    shadowEffect.Parameters["InverseProjection"].SetValue(Matrix.Invert(projection));
    shadowEffect.Parameters["ScreenSize"].SetValue(new Vector4(width, height, 1f / width, 1f / height));
    shadowEffect.Parameters["ToLight"].SetValue(Vector3.Normalize(-sunDirection));

    acceleration.Bind(shadowEffect);

    foreach (var pass in shadowEffect.CurrentTechnique.Passes)
    {
        pass.ApplyCompute();
        graphicsDevice.DispatchCompute((width + 7) / 8, (height + 7) / 8, 1);   // one thread per pixel
    }
}

The fork binds and unbinds compute resources itself, so the forward pass can sample shadowMask straight after.

6a. Alpha-tested geometry

Leaves, fences and grates are a few quads with holes cut in them by a texture's alpha. Traced as their triangles, they cast the shadow of the whole quad. To trace them as their texture says:

  1. Give the mesh its texture coordinates. ITriangleMesh has two optional members, HasTextureCoordinates and GetTextureCoordinates(triangle, out uv0, out uv1, out uv2); a mesh that implements them has its coordinates kept in the BLAS (MeshBlas.TextureCoordinates) and uploaded beside its triangles.

    public bool HasTextureCoordinates => _uvs != null;
    
    public void GetTextureCoordinates(int triangle, out Vector2 uv0, out Vector2 uv1, out Vector2 uv2)
    {
        uv0 = _uvs![_indices[triangle * 3]];
        uv1 = _uvs[_indices[triangle * 3 + 1]];
        uv2 = _uvs[_indices[triangle * 3 + 2]];
    }
    
  2. Flag the instance, and say what to test it against. RayTracingFlags.AlphaTested, and a value of yours - which texture, which cutoff - as its user data:

    tlas.Add(fence.Id, fenceBlas, fence.World, RayTracingFlags.Default | RayTracingFlags.AlphaTested, fenceAlphaSlot);
    

    Changing an instance's user data alone moves Tlas.FlagsVersion, as a flag edit does.

  3. Test the hits. On the GPU, define RT_ANY_HIT before including RayTraversal.fxh and define RtAnyHit after it. It is asked about every hit on an alpha-tested instance, and a false lets the ray through:

    #define RT_ANY_HIT
    #include "Lib/RayTraversal.fxh"
    
    Texture2D<float4> FenceAlpha;   // yours: an atlas, an array - whatever userData indexes
    float AlphaCutoff;
    
    bool RtAnyHit(int userData, int triangleIndex, float2 barycentrics)
    {
        float2 uv = frac(RtTriangleUv(triangleIndex, barycentrics));   // a repeating texture
    
        uint width, height;
        FenceAlpha.GetDimensions(width, height);
    
        // Load or SampleLevel: a compute shader has no derivatives to pick a mip with.
        return FenceAlpha.Load(int3(uv * float2(width, height), 0)).a > AlphaCutoff;
    }
    

    On the CPU, pass an AnyHitFilter to Tlas.IntersectAny or Tlas.Intersect - the same test, so that a click goes through the holes too:

    bool Solid(in TlasInstance instance, int triangle, float u, float v)
    {
        instance.Blas.Geometry.GetTextureCoordinates(triangle, out var uv0, out var uv1, out var uv2);
    
        return SampleAlpha(instance.UserData, new GpuTriangleUv(uv0, uv1, uv2).At(u, v)) > cutoff;
    }
    
    tlas.Intersect(ray, float.MaxValue, out var hit, RayTracingFlags.Pickable, Solid);
    

An alpha-tested instance whose query has no test - no RT_ANY_HIT, a null filter - is solid. Instances without the flag are never tested, so they cost nothing more than before. The test answers yes or no: light through stained glass, partly blocked, is not something an any-hit query can say.

6b. Closest hit on the GPU

A bounce or a reflection has to know what the ray landed on, not only whether something was in the way. RtTraceClosest finds the nearest hit, through the holes of alpha-tested instances as the any-hit walk does when the kernel defines RT_ANY_HIT, and says where it is:

#include "Lib/RayTraversal.fxh"

StructuredBuffer<float4> Albedos;   // yours: one per instance, by the user data each was declared with

float3 Bounce(float3 position, float3 normal, float3 direction)
{
    RtHit hit;

    if (!RtTraceClosest(position + normal * 0.02, direction, 1e8, RT_FLAG_VISIBLE_TO_GI, hit))
        return SkyRadiance(direction);                  // yours: nothing hit, the ray left the scene

    float3 hitPosition = position + normal * 0.02 + direction * hit.Distance;
    float3 hitNormal   = RtHitShadingNormal(hit, direction);   // world space, facing back along the ray
    float2 uv          = RtHitUv(hit);                         // for a texture of yours

    return Albedos[hit.UserData].rgb * LightAt(hitPosition, hitNormal);   // yours
}

What an RtHit holds:

  • Distance - the ray parameter t, as RayHit.Distance is: the hit is at origin + t * direction. maxDistance when nothing was hit.
  • UserData - the instance's, as it was declared (Tlas.Add). This is how a kernel finds its own data about what was hit - a material, an albedo - which is why it is worth giving every instance some, not only the alpha-tested ones.
  • Instance, Triangle, Barycentrics - for RtHitNormal, RtHitShadingNormal and RtHitUv. These are the GPU's own numbering, not RayHit's: Instance indexes the uploaded records, in the TLAS's tree order rather than Tlas.Instances', and Triangle the uploaded triangles, in each tree's order rather than the mesh's. -1 for no hit.

A kernel of yours that wants one mesh's triangles - to pick a point on a glowing one and aim a ray at it, say, or to tell by a hit's Triangle which of them it landed on - finds them with GpuAccelerationStructure.TryGetTriangles(blas, out first, out count): the run of Triangles (and TriangleUvs, TriangleNormals) that mesh's tree occupies, first numbered as RtHit.Triangle is. In the mesh's own space, as MeshBlas.Triangles has them - an instance's world transform is yours to apply - and good until the next Upload, which may lay everything out afresh.

Two normals can be had at a hit, each in world space, unit, and turned to face the side the ray came from, as every triangle here is two-sided - and right under any transform, mirrored and non-uniformly scaled included:

  • RtHitNormal - the triangle's own plane: flat, faceted on a sphere.
  • RtHitShadingNormal - the mesh's own normals, weighted at the hit as RtHitUv weighs texture coordinates: smooth across the triangles, as the mesh is shaded. For it the mesh hands its normals over, as it does texture coordinates for 6a - HasNormals and GetNormals(triangle, out n0, out n1, out n2) on ITriangleMesh, in the mesh's own space and its corners' order. They are read when the BLAS is built and again on every Refit, as a deforming mesh's turn with it. A mesh that hands none over gets RtHitNormal.

The walk is Tlas.Intersect's, line for line: it opens the nearer of two children first, so a hit found in it can turn the other down unopened, and keeps the child it put off on a stack. That stack - 24 entries for each of the two levels, one per level of the deepest tree - is a per-thread array the compiler keeps in scratch memory, and is what the any-hit walk does without. A ray that only asks whether it is blocked should still ask RtTraceAny.

HLSL reference

RayTraversal.fxh:

Name
bool RtTraceAny(float3 origin, float3 direction, float maxDistance, int requiredFlags) Whether any instance carrying every flag in requiredFlags blocks the ray within maxDistance. The direction need not be unit length.
bool RtTraceAnyCounted(..., inout uint steps) The same walk, adding every box and triangle it tests to steps, for heat maps and cost measurements.
bool RtTraceClosest(float3 origin, float3 direction, float maxDistance, int requiredFlags, out RtHit hit) The nearest hit on an instance carrying every flag in requiredFlags, within maxDistance (section 6b). The direction need not be unit length.
bool RtTraceClosestCounted(..., out RtHit hit, inout uint steps) The same walk, counting as RtTraceAnyCounted does.
struct RtHit Distance, Instance, Triangle, UserData, Barycentrics - see section 6b.
float3 RtHitNormal(RtHit hit, float3 direction) The hit triangle's normal, world space and unit, facing back along direction.
float3 RtHitShadingNormal(RtHit hit, float3 direction) The mesh's own normal at the hit, its corners' weighted, world space and unit, on the side RtHitNormal faces - or RtHitNormal for a mesh without normals.
float3 RtTriangleNormal(int triangleIndex, float2 barycentrics) The corners' normals weighted at a hit, in the mesh's space, not renormalised; zero for a mesh without normals.
float2 RtHitUv(RtHit hit) The texture coordinate where the hit landed.
RT_TRAVERSAL_STACK_SIZE The closest-hit walk's stack, per level: Bvh.MaxTreeDepth.
RT_FLAG_CASTS_SHADOW, RT_FLAG_VISIBLE_TO_GI, RT_FLAG_ALPHA_TESTED The GPU's view of RayTracingFlags (Pickable is CPU-only).
RT_ANY_HIT Defined by a kernel before the include: hits on alpha-tested instances are put to its RtAnyHit.
bool RtAnyHit(int userData, int triangleIndex, float2 barycentrics) The kernel's own, defined after the include: whether a hit counts. userData is the instance's.
float2 RtTriangleUv(int triangleIndex, float2 barycentrics) The texture coordinate at a hit.
RT_MIN_DISTANCE Hits closer than this (1e-4) are ignored, as on the CPU. Still offset rays off the surface.
RT_MAX_DISTANCE The longest a ray may be, float's largest finite value. A longer maxDistance is clamped to it.
TlasNodes, Instances, BlasNodes, Triangles, TriangleUvs, TriangleNormals, TlasNodeCount What GpuAccelerationStructure.Bind sets.

RayTraversal.fxh needs nothing compute-only, so a pixel shader can include it too.

GBuffer.fxh:

Function
GBufferViewPosition(pixel, gBufferSize, depth, inverseProjection) The view-space point at a G-buffer pixel, under a perspective or an orthographic projection.
GBufferWorldPosition(..., inverseView) The same point through inverseView.
GBufferViewLine(pixel, gBufferSize, inverseProjection, out origin, out through) The pixel's line of sight in view space: origin + through * depth is its point at that depth. From the eye under perspective; parallel, from the pixel's own point on the z = 0 plane, under orthographic. through.z is -1.
GBufferViewLineAt(ndc, inverseProjection, out origin, out through) The same for any point on the screen, in normalized device coordinates.
GBufferViewNormal(packed), GBufferWorldNormal(packed, inverseView) The unpacked normal.
GBufferPixelOf(pixel, pixelScale), ReducedGridPosition(position, pixelScale) Mapping between a pass at 1/pixelScale resolution and the full-resolution G-buffer, when the pass reads one G-buffer pixel per pixel of its own.

7. Fill the G-buffer

GBuffer owns two render targets: Depth (R32F, the linear view-space distance, 0 where nothing was drawn) and Normal (RGBA8, the view-space normal packed into 0..1). Both are null until the first Resize. Your own prepass fills them:

var gBuffer = new GBuffer(graphicsDevice);

// Every frame, before anything traces.
gBuffer.Resize(width, height);   // a no-op unless the size changed; BindAndClear refuses to run before it
gBuffer.BindAndClear();          // both targets, depth cleared to 0 ("nothing here")

graphicsDevice.BlendState = BlendState.Opaque;
graphicsDevice.DepthStencilState = DepthStencilState.Default;
// ... draw your opaque meshes with the prepass effect below ...

gBuffer.Unbind();                // back to the back buffer; IsCurrent = true, ContentVersion moves

The prepass pixel shader writes the two values in this encoding, which GBuffer.fxh undoes:

struct PSOutput
{
    float  Depth  : SV_Target0;   // -PositionVS.z
    float4 Normal : SV_Target1;   // view-space normal * 0.5 + 0.5
};

PSOutput PS(VSOutput input)
{
    PSOutput o;
    o.Depth  = -input.PositionVS.z;
    o.Normal = float4(normalize(input.NormalVS) * 0.5 + 0.5, 1.0);
    return o;
}
  • What to draw: only what ends up the nearest surface on screen, which means opaque, depth-writing materials, drawn with the cull mode they are shaded with. A blended surface in the G-buffer would have the traced results of whatever is behind it applied to itself.
  • IsCurrent says the targets hold this frame's surfaces. Gate every traced pass on it.
  • Skipping a frame: call ConfirmCurrent() instead of redrawing when nothing changed, and Invalidate() when the prepass cannot run.
  • ContentVersion moves on every real redraw, so a pass can tell new surfaces from old.
  • Either projection. GBufferViewPosition finds the surface along the pixel's line of sight, which GBufferViewLine gives: from the eye through the pixel under a perspective camera, and parallel to the view axis from the pixel's own point under an orthographic one. Both come from un-projecting the pixel at the near and far clip depths, so a jittered or off-centre projection works the same. A traced pass that starts rays at the viewer starts them at origin, not the eye.

Deforming meshes

Update the positions your ITriangleMesh returns, then refit the BLAS:

skinnedMesh.UpdatePositions(currentPose);
characterBlas.Refit();

The next Tlas update sees the new bounds, and the next Upload re-sends that BLAS in place. A refit keeps the tree's topology, so the mesh must keep its triangle count - Refit throws if it changed - and after a large change of pose, MeshBlas.Build a fresh one.

Deforming meshes on the GPU

A mesh whose vertices never leave the GPU - a cloth simulated there, a mesh skinned in a compute pass - is refitted there too. Build it as a deformable BLAS, over its rest pose, from a mesh that can also name each triangle's vertices (IIndexedTriangleMesh):

var clothBlas = MeshBlas.BuildDeformable(restMesh);

Each frame, write its vertices - position and normal, RtVertex, 24 bytes, in its own space, indexed as GetTriangleIndices indexes them - into a structured buffer of your own, then, after the Upload that placed it:

clothBlas.SetBounds(reachOfTheCloth);   // for the TLAS: a box holding every pose it can take, in its own space
tlas.BeginUpdate(); /* ... */ tlas.Add(id, clothBlas, Matrix.Identity, flags); /* ... */ tlas.EndUpdate();
gpu.Upload(tlas);

if (moved || gpu.NeedsRefit(clothBlas))
    gpu.Refit(blasRefitEffect, clothBlas, vertexBuffer);
  • Refit rewrites its triangles, their normals and every box of its tree in place in the shared buffers: one dispatch over its triangles, then one per level of the tree, deepest first. Version moves, as for any change the traced kernels have to see; RefitCount counts the refits among its moves, for a pass that keeps what it gathered over frames to tell a mesh deforming in place from the scene changing.
  • BlasRefit.fx is the effect it runs: it ships beside RayTraversal.fxh, at Content/Effects/Lib, for you to compile as you compile your other kernels. Its parameters are bound by Refit - RefitVertices, RefitVertexIndices, RefitLevelNodes, RefitTriangles, RefitNormals, RefitNodes, RefitTriangleOffset, RefitTriangleCount, RefitNodeOffset, RefitLevelStart, RefitLevelCount - under names of its own, never to be compiled with RayTraversal.fxh, which reads the same buffers.
  • NeedsRefit is true until the first refit, and again whenever an Upload has laid everything out afresh and written its rest pose back: a host that refits only when its mesh moved refits then too.
  • SetBounds is what the CPU knows of it: the Tlas boxes its instance by it, and nothing of its geometry is sent again for it. The CPU's own queries - Intersect, IntersectAny, picking through the Tlas - still find the rest pose.
  • One instance each: a deforming mesh's tree is its own.

Limits

  • Triangles only: each one double-sided.
  • Smooth normals only from the mesh: RtHitShadingNormal weighs the normals the mesh hands over, and is the flat RtHitNormal for a mesh that hands over none. Per corner, as ITriangleMesh gives them: a normal map is the caller's to apply.
  • Finite rays: the any-hit walks treat an infinite maxDistance as float.MaxValue, on both sides; the closest-hit walks accept it as it is, on both sides too.
  • Units: the triangle test treats a determinant below 1e-12 as a degenerate triangle, so a mesh authored in units where triangles are smaller than about 1e-6 on a side is never hit. Metres or centimetres are fine; nanometres are not.
  • Tree depth is capped at Bvh.MaxTreeDepth (24). Deeper nodes stay leaves, so pathological input gets slower, never wrong.
  • One structure per scene: the Tlas and its GPU copy are updated in place.

License

MIT.

Product Compatible and additional computed target framework versions.
.NET net8.0-windows7.0 is compatible.  net9.0-windows was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on BorrowedTorch.RayTracing:

Package Downloads
BorrowedTorch.Engine

Kindling, Borrowed Torch's game engine: what a game's own code builds against - its features registering components, systems, keys and UI handlers - for the Kindling editor and player to run

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.7.1 53 11/18/2026
1.7.0 136 11/16/2026
1.6.0 100 11/14/2026
1.5.0 107 11/5/2026
1.4.0 91 11/4/2026
1.3.0 97 11/3/2026
1.2.0 89 11/3/2026
1.1.1 105 11/2/2026
1.1.0 110 10/31/2026
1.0.0 123 10/15/2026