| 1 |
/* |
| 2 |
See LICENSE folder for this sample’s licensing information. |
| 3 |
|
| 4 |
Abstract: |
| 5 |
The Metal shaders used for this sample. |
| 6 |
*/ |
| 7 |
|
| 8 |
#include <metal_stdlib> |
| 9 |
#include <simd/simd.h> |
| 10 |
|
| 11 |
using namespace metal; |
| 12 |
|
| 13 |
using namespace raytracing; |
| 14 |
|
| 15 |
|
| 16 |
#define GEOMETRY_MASK_TRIANGLE 1 |
| 17 |
#define GEOMETRY_MASK_SPHERE 2 |
| 18 |
#define GEOMETRY_MASK_LIGHT 4 |
| 19 |
|
| 20 |
#define GEOMETRY_MASK_GEOMETRY (GEOMETRY_MASK_TRIANGLE | GEOMETRY_MASK_SPHERE) |
| 21 |
|
| 22 |
#define RAY_MASK_PRIMARY (GEOMETRY_MASK_GEOMETRY | GEOMETRY_MASK_LIGHT) |
| 23 |
#define RAY_MASK_SHADOW GEOMETRY_MASK_GEOMETRY |
| 24 |
#define RAY_MASK_SECONDARY GEOMETRY_MASK_GEOMETRY |
| 25 |
|
| 26 |
struct Camera { |
| 27 |
vector_float3 position; |
| 28 |
vector_float3 right; |
| 29 |
vector_float3 up; |
| 30 |
vector_float3 forward; |
| 31 |
}; |
| 32 |
|
| 33 |
struct AreaLight { |
| 34 |
vector_float3 position; |
| 35 |
vector_float3 forward; |
| 36 |
vector_float3 right; |
| 37 |
vector_float3 up; |
| 38 |
vector_float3 color; |
| 39 |
}; |
| 40 |
|
| 41 |
struct Uniforms { |
| 42 |
unsigned int width; |
| 43 |
unsigned int height; |
| 44 |
unsigned int frameIndex; |
| 45 |
unsigned int lightCount; |
| 46 |
Camera camera; |
| 47 |
}; |
| 48 |
|
| 49 |
struct Sphere { |
| 50 |
packed_float3 origin; |
| 51 |
float radiusSquared; |
| 52 |
packed_float3 color; |
| 53 |
float radius; |
| 54 |
}; |
| 55 |
|
| 56 |
struct Triangle { |
| 57 |
vector_float3 normals[3]; |
| 58 |
vector_float3 colors[3]; |
| 59 |
}; |
| 60 |
|
| 61 |
constant unsigned int resourcesStride [[function_constant(0)]]; |
| 62 |
constant bool useIntersectionFunctions [[function_constant(1)]]; |
| 63 |
constant bool usePerPrimitiveData [[function_constant(2)]]; |
| 64 |
constant bool useResourcesBuffer = !usePerPrimitiveData; |
| 65 |
|
| 66 |
constant unsigned int primes[] = { |
| 67 |
2, 3, 5, 7, |
| 68 |
11, 13, 17, 19, |
| 69 |
23, 29, 31, 37, |
| 70 |
41, 43, 47, 53, |
| 71 |
59, 61, 67, 71, |
| 72 |
73, 79, 83, 89 |
| 73 |
}; |
| 74 |
|
| 75 |
// Returns the i'th element of the Halton sequence using the d'th prime number as a |
| 76 |
// base. The Halton sequence is a low discrepency sequence: the values appear |
| 77 |
// random, but are more evenly distributed than a purely random sequence. Each random |
| 78 |
// value used to render the image uses a different independent dimension, `d`, |
| 79 |
// and each sample (frame) uses a different index `i`. To decorrelate each pixel, |
| 80 |
// you can apply a random offset to `i`. |
| 81 |
float halton(unsigned int i, unsigned int d) { |
| 82 |
unsigned int b = primes[d]; |
| 83 |
|
| 84 |
float f = 1.0f; |
| 85 |
float invB = 1.0f / b; |
| 86 |
|
| 87 |
float r = 0; |
| 88 |
|
| 89 |
while (i > 0) { |
| 90 |
f = f * invB; |
| 91 |
r = r + f * (i % b); |
| 92 |
i = i / b; |
| 93 |
} |
| 94 |
|
| 95 |
return r; |
| 96 |
} |
| 97 |
|
| 98 |
// Interpolates the vertex attribute of an arbitrary type across the surface of a triangle |
| 99 |
// given the barycentric coordinates and triangle index in an intersection structure. |
| 100 |
template<typename T, typename IndexType> |
| 101 |
inline T interpolateVertexAttribute(device T *attributes, |
| 102 |
IndexType i0, |
| 103 |
IndexType i1, |
| 104 |
IndexType i2, |
| 105 |
float2 uv) { |
| 106 |
// Look up value for each vertex. |
| 107 |
const T T0 = attributes[i0]; |
| 108 |
const T T1 = attributes[i1]; |
| 109 |
const T T2 = attributes[i2]; |
| 110 |
|
| 111 |
// Compute the sum of the vertex attributes weighted by the barycentric coordinates. |
| 112 |
// The barycentric coordinates sum to one. |
| 113 |
return (1.0f - uv.x - uv.y) * T0 + uv.x * T1 + uv.y * T2; |
| 114 |
} |
| 115 |
|
| 116 |
template<typename T> |
| 117 |
inline T interpolateVertexAttribute(thread T *attributes, float2 uv) { |
| 118 |
// Look up the value for each vertex. |
| 119 |
const T T0 = attributes[0]; |
| 120 |
const T T1 = attributes[1]; |
| 121 |
const T T2 = attributes[2]; |
| 122 |
|
| 123 |
// Compute the sum of the vertex attributes weighted by the barycentric coordinates. |
| 124 |
// The barycentric coordinates sum to one. |
| 125 |
return (1.0f - uv.x - uv.y) * T0 + uv.x * T1 + uv.y * T2; |
| 126 |
} |
| 127 |
|
| 128 |
// Uses the inversion method to map two uniformly random numbers to a 3D |
| 129 |
// unit hemisphere, where the probability of a given sample is proportional to the cosine |
| 130 |
// of the angle between the sample direction and the "up" direction (0, 1, 0). |
| 131 |
inline float3 sampleCosineWeightedHemisphere(float2 u) { |
| 132 |
float phi = 2.0f * M_PI_F * u.x; |
| 133 |
|
| 134 |
float cos_phi; |
| 135 |
float sin_phi = sincos(phi, cos_phi); |
| 136 |
|
| 137 |
float cos_theta = sqrt(u.y); |
| 138 |
float sin_theta = sqrt(1.0f - cos_theta * cos_theta); |
| 139 |
|
| 140 |
return float3(sin_theta * cos_phi, cos_theta, sin_theta * sin_phi); |
| 141 |
} |
| 142 |
|
| 143 |
// Maps two uniformly random numbers to the surface of a 2D area light |
| 144 |
// source and returns the direction to this point, the amount of light that travels |
| 145 |
// between the intersection point and the sample point on the light source, as well |
| 146 |
// as the distance between these two points. |
| 147 |
|
| 148 |
inline void sampleAreaLight(constant AreaLight & light, |
| 149 |
float2 u, |
| 150 |
float3 position, |
| 151 |
thread float3 & lightDirection, |
| 152 |
thread float3 & lightColor, |
| 153 |
thread float & lightDistance) |
| 154 |
{ |
| 155 |
// Map to -1..1 |
| 156 |
u = u * 2.0f - 1.0f; |
| 157 |
|
| 158 |
// Transform into the light's coordinate system. |
| 159 |
float3 samplePosition = light.position + |
| 160 |
light.right * u.x + |
| 161 |
light.up * u.y; |
| 162 |
|
| 163 |
// Compute the vector from sample point on the light source to intersection point. |
| 164 |
lightDirection = samplePosition - position; |
| 165 |
|
| 166 |
lightDistance = length(lightDirection); |
| 167 |
|
| 168 |
float inverseLightDistance = 1.0f / max(lightDistance, 1e-3f); |
| 169 |
|
| 170 |
// Normalize the light direction. |
| 171 |
lightDirection *= inverseLightDistance; |
| 172 |
|
| 173 |
// Start with the light's color. |
| 174 |
lightColor = light.color; |
| 175 |
|
| 176 |
// Light falls off with the inverse square of the distance to the intersection point. |
| 177 |
lightColor *= (inverseLightDistance * inverseLightDistance); |
| 178 |
|
| 179 |
// Light also falls off with the cosine of the angle between the intersection point |
| 180 |
// and the light source. |
| 181 |
lightColor *= saturate(dot(-lightDirection, light.forward)); |
| 182 |
} |
| 183 |
|
| 184 |
// Aligns a direction on the unit hemisphere such that the hemisphere's "up" direction |
| 185 |
// (0, 1, 0) maps to the given surface normal direction. |
| 186 |
inline float3 alignHemisphereWithNormal(float3 sample, float3 normal) { |
| 187 |
// Set the "up" vector to the normal |
| 188 |
float3 up = normal; |
| 189 |
|
| 190 |
// Find an arbitrary direction perpendicular to the normal, which becomes the |
| 191 |
// "right" vector. |
| 192 |
float3 right = normalize(cross(normal, float3(0.0072f, 1.0f, 0.0034f))); |
| 193 |
|
| 194 |
// Find a third vector perpendicular to the previous two, which becomes the |
| 195 |
// "forward" vector. |
| 196 |
float3 forward = cross(right, up); |
| 197 |
|
| 198 |
// Map the direction on the unit hemisphere to the coordinate system aligned |
| 199 |
// with the normal. |
| 200 |
return sample.x * right + sample.y * up + sample.z * forward; |
| 201 |
} |
| 202 |
|
| 203 |
// Return the type for a bounding box intersection function. |
| 204 |
struct BoundingBoxIntersection { |
| 205 |
bool accept [[accept_intersection]]; // Whether to accept or reject the intersection. |
| 206 |
float distance [[distance]]; // Distance from the ray origin to the intersection point. |
| 207 |
}; |
| 208 |
|
| 209 |
// Resources for a piece of triangle geometry. |
| 210 |
struct TriangleResources { |
| 211 |
device uint16_t *indices; |
| 212 |
device float3 *vertexNormals; |
| 213 |
device float3 *vertexColors; |
| 214 |
}; |
| 215 |
|
| 216 |
// Resources for a piece of sphere geometry. |
| 217 |
struct SphereResources { |
| 218 |
device Sphere *spheres; |
| 219 |
}; |
| 220 |
|
| 221 |
/* |
| 222 |
Custom sphere intersection function. The [[intersection]] keyword marks this as an intersection |
| 223 |
function. The [[bounding_box]] keyword means that this intersection function handles intersecting rays |
| 224 |
with bounding box primitives. To create sphere primitives, the sample creates bounding boxes that |
| 225 |
enclose the sphere primitives. |
| 226 |
|
| 227 |
The [[triangle_data]] and [[instancing]] keywords indicate that the intersector that calls this |
| 228 |
intersection function returns barycentric coordinates for triangle intersections and traverses |
| 229 |
an instance acceleration structure. These keywords must match between the intersection functions, |
| 230 |
intersection function table, intersector, and intersection result to ensure that Metal propagates |
| 231 |
data correctly between stages. Using fewer tags when possible may result in better performance, |
| 232 |
as Metal may need to store less data and pass less data between stages. For example, if you do not |
| 233 |
need barycentric coordinates, omitting [[triangle_data]] means Metal can avoid computing and storing |
| 234 |
them. |
| 235 |
|
| 236 |
The arguments to the intersection function contain information about the ray, primitive to be |
| 237 |
tested, and so on. The ray intersector provides this datas when it calls the intersection function. |
| 238 |
Metal provides other built-in arguments, but this sample doesn't use them. |
| 239 |
*/ |
| 240 |
[[intersection(bounding_box, triangle_data, instancing)]] |
| 241 |
BoundingBoxIntersection sphereIntersectionFunction(// Ray parameters passed to the ray intersector below |
| 242 |
float3 origin [[origin]], |
| 243 |
float3 direction [[direction]], |
| 244 |
float minDistance [[min_distance]], |
| 245 |
float maxDistance [[max_distance]], |
| 246 |
// Information about the primitive. |
| 247 |
unsigned int primitiveIndex [[primitive_id]], |
| 248 |
unsigned int geometryIndex [[geometry_intersection_function_table_offset]], |
| 249 |
// Custom resources bound to the intersection function table. |
| 250 |
device void *resources [[buffer(0), function_constant(useResourcesBuffer)]] |
| 251 |
,const device void* perPrimitiveData [[primitive_data]]) |
| 252 |
{ |
| 253 |
Sphere sphere; |
| 254 |
// Look up the resources for this piece of sphere geometry. |
| 255 |
if (usePerPrimitiveData) { |
| 256 |
// Per-primitive data points to data from the specified buffer as was configured in the MTLAccelerationStructureBoundingBoxGeometryDescriptor. |
| 257 |
sphere = *(const device Sphere*)perPrimitiveData; |
| 258 |
} else |
| 259 |
{ |
| 260 |
device SphereResources& sphereResources = *(device SphereResources *)((device char *)resources + resourcesStride * geometryIndex); |
| 261 |
// Get the actual sphere enclosed in this bounding box. |
| 262 |
sphere = sphereResources.spheres[primitiveIndex]; |
| 263 |
} |
| 264 |
|
| 265 |
// Check for intersection between the ray and sphere mathematically. |
| 266 |
float3 oc = origin - sphere.origin; |
| 267 |
|
| 268 |
float a = dot(direction, direction); |
| 269 |
float b = 2 * dot(oc, direction); |
| 270 |
float c = dot(oc, oc) - sphere.radiusSquared; |
| 271 |
|
| 272 |
float disc = b * b - 4 * a * c; |
| 273 |
|
| 274 |
BoundingBoxIntersection ret; |
| 275 |
|
| 276 |
if (disc <= 0.0f) { |
| 277 |
// If the ray missed the sphere, return false. |
| 278 |
ret.accept = false; |
| 279 |
} |
| 280 |
else { |
| 281 |
// Otherwise, compute the intersection distance. |
| 282 |
ret.distance = (-b - sqrt(disc)) / (2 * a); |
| 283 |
|
| 284 |
// The intersection function must also check whether the intersection distance is |
| 285 |
// within the acceptable range. Intersection functions do not run in any particular order, |
| 286 |
// so the maximum distance may be different from the one passed into the ray intersector. |
| 287 |
ret.accept = ret.distance >= minDistance && ret.distance <= maxDistance; |
| 288 |
} |
| 289 |
|
| 290 |
return ret; |
| 291 |
} |
| 292 |
|
| 293 |
__attribute__((always_inline)) |
| 294 |
float3 transformPoint(float3 p, float4x4 transform) { |
| 295 |
return (transform * float4(p.x, p.y, p.z, 1.0f)).xyz; |
| 296 |
} |
| 297 |
|
| 298 |
__attribute__((always_inline)) |
| 299 |
float3 transformDirection(float3 p, float4x4 transform) { |
| 300 |
return (transform * float4(p.x, p.y, p.z, 0.0f)).xyz; |
| 301 |
} |
| 302 |
|
| 303 |
// Main ray tracing kernel. |
| 304 |
kernel void raytracingKernel( |
| 305 |
uint2 tid [[thread_position_in_grid]], |
| 306 |
constant Uniforms & uniforms [[buffer(0)]], |
| 307 |
texture2d<unsigned int> randomTex [[texture(0)]], |
| 308 |
texture2d<float> prevTex [[texture(1)]], |
| 309 |
texture2d<float, access::write> dstTex [[texture(2)]], |
| 310 |
device void *resources [[buffer(1), function_constant(useResourcesBuffer)]], |
| 311 |
constant MTLAccelerationStructureInstanceDescriptor *instances [[buffer(2)]], |
| 312 |
constant AreaLight *areaLights [[buffer(3)]], |
| 313 |
instance_acceleration_structure accelerationStructure [[buffer(4)]], |
| 314 |
intersection_function_table<triangle_data, instancing> intersectionFunctionTable [[buffer(5)]] |
| 315 |
) |
| 316 |
{ |
| 317 |
// The sample aligns the thread count to the threadgroup size, which means the thread count |
| 318 |
// may be different than the bounds of the texture. Test to make sure this thread |
| 319 |
// is referencing a pixel within the bounds of the texture. |
| 320 |
if (tid.x >= uniforms.width || tid.y >= uniforms.height) return; |
| 321 |
|
| 322 |
// The ray to cast. |
| 323 |
ray ray; |
| 324 |
|
| 325 |
// Pixel coordinates for this thread. |
| 326 |
float2 pixel = (float2)tid; |
| 327 |
|
| 328 |
// Apply a random offset to the random number index to decorrelate pixels. |
| 329 |
unsigned int offset = randomTex.read(tid).x; |
| 330 |
|
| 331 |
// Add a random offset to the pixel coordinates for antialiasing. |
| 332 |
float2 r = float2(halton(offset + uniforms.frameIndex, 0), |
| 333 |
halton(offset + uniforms.frameIndex, 1)); |
| 334 |
|
| 335 |
pixel += r; |
| 336 |
|
| 337 |
// Map pixel coordinates to -1..1. |
| 338 |
float2 uv = (float2)pixel / float2(uniforms.width, uniforms.height); |
| 339 |
uv = uv * 2.0f - 1.0f; |
| 340 |
|
| 341 |
constant Camera & camera = uniforms.camera; |
| 342 |
|
| 343 |
// Rays start at the camera position. |
| 344 |
ray.origin = camera.position; |
| 345 |
|
| 346 |
// Map normalized pixel coordinates into camera's coordinate system. |
| 347 |
ray.direction = normalize(uv.x * camera.right + |
| 348 |
uv.y * camera.up + |
| 349 |
camera.forward); |
| 350 |
|
| 351 |
// Don't limit intersection distance. |
| 352 |
ray.max_distance = INFINITY; |
| 353 |
|
| 354 |
// Start with a fully white color. The kernel scales the light each time the |
| 355 |
// ray bounces off of a surface, based on how much of each light component |
| 356 |
// the surface absorbs. |
| 357 |
float3 color = float3(1.0f, 1.0f, 1.0f); |
| 358 |
|
| 359 |
float3 accumulatedColor = float3(0.0f, 0.0f, 0.0f); |
| 360 |
|
| 361 |
// Create an intersector to test for intersection between the ray and the geometry in the scene. |
| 362 |
intersector<triangle_data, instancing> i; |
| 363 |
|
| 364 |
// If the sample isn't using intersection functions, provide some hints to Metal for |
| 365 |
// better performance. |
| 366 |
if (!useIntersectionFunctions) { |
| 367 |
i.assume_geometry_type(geometry_type::triangle); |
| 368 |
i.force_opacity(forced_opacity::opaque); |
| 369 |
} |
| 370 |
|
| 371 |
typename intersector<triangle_data, instancing>::result_type intersection; |
| 372 |
|
| 373 |
// Simulate up to three ray bounces. Each bounce propagates light backward along the |
| 374 |
// ray's path toward the camera. |
| 375 |
for (int bounce = 0; bounce < 3; bounce++) { |
| 376 |
// Get the closest intersection, not the first intersection. This is the default, but |
| 377 |
// the sample adjusts this property below when it casts shadow rays. |
| 378 |
i.accept_any_intersection(false); |
| 379 |
|
| 380 |
// Check for intersection between the ray and the acceleration structure. If the sample |
| 381 |
// isn't using intersection functions, it doesn't need to include one. |
| 382 |
if (useIntersectionFunctions) |
| 383 |
intersection = i.intersect(ray, accelerationStructure, bounce == 0 ? RAY_MASK_PRIMARY : RAY_MASK_SECONDARY, intersectionFunctionTable); |
| 384 |
else |
| 385 |
intersection = i.intersect(ray, accelerationStructure, bounce == 0 ? RAY_MASK_PRIMARY : RAY_MASK_SECONDARY); |
| 386 |
|
| 387 |
// Stop if the ray didn't hit anything and has bounced out of the scene. |
| 388 |
if (intersection.type == intersection_type::none) |
| 389 |
break; |
| 390 |
|
| 391 |
unsigned int instanceIndex = intersection.instance_id; |
| 392 |
|
| 393 |
// Look up the mask for this instance, which indicates what type of geometry the ray hit. |
| 394 |
unsigned int mask = instances[instanceIndex].mask; |
| 395 |
|
| 396 |
// If the ray hit a light source, set the color to white, and stop immediately. |
| 397 |
if (mask == GEOMETRY_MASK_LIGHT) { |
| 398 |
accumulatedColor = float3(1.0f, 1.0f, 1.0f); |
| 399 |
break; |
| 400 |
} |
| 401 |
|
| 402 |
// The ray hit something. Look up the transformation matrix for this instance. |
| 403 |
float4x4 objectToWorldSpaceTransform(1.0f); |
| 404 |
|
| 405 |
for (int column = 0; column < 4; column++) |
| 406 |
for (int row = 0; row < 3; row++) |
| 407 |
objectToWorldSpaceTransform[column][row] = instances[instanceIndex].transformationMatrix[column][row]; |
| 408 |
|
| 409 |
// Compute the intersection point in world space. |
| 410 |
float3 worldSpaceIntersectionPoint = ray.origin + ray.direction * intersection.distance; |
| 411 |
|
| 412 |
unsigned primitiveIndex = intersection.primitive_id; |
| 413 |
unsigned int geometryIndex = instances[instanceIndex].accelerationStructureIndex; |
| 414 |
float2 barycentric_coords = intersection.triangle_barycentric_coord; |
| 415 |
|
| 416 |
float3 worldSpaceSurfaceNormal = 0.0f; |
| 417 |
float3 surfaceColor = 0.0f; |
| 418 |
|
| 419 |
if (mask & GEOMETRY_MASK_TRIANGLE) { |
| 420 |
Triangle triangle; |
| 421 |
|
| 422 |
float3 objectSpaceSurfaceNormal; |
| 423 |
if (usePerPrimitiveData) { |
| 424 |
// Per-primitive data points to data from the specified buffer as was configured in the MTLAccelerationStructureTriangleGeometryDescriptor. |
| 425 |
triangle = *(const device Triangle*)intersection.primitive_data; |
| 426 |
} else |
| 427 |
{ |
| 428 |
// The ray hit a triangle. Look up the corresponding geometry's normal and UV buffers. |
| 429 |
device TriangleResources & triangleResources = *(device TriangleResources *)((device char *)resources + resourcesStride * geometryIndex); |
| 430 |
|
| 431 |
triangle.normals[0] = triangleResources.vertexNormals[triangleResources.indices[primitiveIndex * 3 + 0]]; |
| 432 |
triangle.normals[1] = triangleResources.vertexNormals[triangleResources.indices[primitiveIndex * 3 + 1]]; |
| 433 |
triangle.normals[2] = triangleResources.vertexNormals[triangleResources.indices[primitiveIndex * 3 + 2]]; |
| 434 |
|
| 435 |
triangle.colors[0] = triangleResources.vertexColors[triangleResources.indices[primitiveIndex * 3 + 0]]; |
| 436 |
triangle.colors[1] = triangleResources.vertexColors[triangleResources.indices[primitiveIndex * 3 + 1]]; |
| 437 |
triangle.colors[2] = triangleResources.vertexColors[triangleResources.indices[primitiveIndex * 3 + 2]]; |
| 438 |
} |
| 439 |
|
| 440 |
// Interpolate the vertex normal at the intersection point. |
| 441 |
objectSpaceSurfaceNormal = interpolateVertexAttribute(triangle.normals, barycentric_coords); |
| 442 |
|
| 443 |
// Interpolate the vertex color at the intersection point. |
| 444 |
surfaceColor = interpolateVertexAttribute(triangle.colors, barycentric_coords); |
| 445 |
|
| 446 |
// Transform the normal from object to world space. |
| 447 |
worldSpaceSurfaceNormal = normalize(transformDirection(objectSpaceSurfaceNormal, objectToWorldSpaceTransform)); |
| 448 |
} |
| 449 |
else if (mask & GEOMETRY_MASK_SPHERE) { |
| 450 |
Sphere sphere; |
| 451 |
if (usePerPrimitiveData) { |
| 452 |
// Per-primitive data points to data from the specified buffer as was configured in the MTLAccelerationStructureBoundingBoxGeometryDescriptor. |
| 453 |
sphere = *(const device Sphere*)intersection.primitive_data; |
| 454 |
} else |
| 455 |
{ |
| 456 |
// The ray hit a sphere. Look up the corresponding sphere buffer. |
| 457 |
device SphereResources & sphereResources = *(device SphereResources *)((device char *)resources + resourcesStride * geometryIndex); |
| 458 |
sphere = sphereResources.spheres[primitiveIndex]; |
| 459 |
} |
| 460 |
|
| 461 |
// Transform the sphere's origin from object space to world space. |
| 462 |
float3 worldSpaceOrigin = transformPoint(sphere.origin, objectToWorldSpaceTransform); |
| 463 |
|
| 464 |
// Compute the surface normal directly in world space. |
| 465 |
worldSpaceSurfaceNormal = normalize(worldSpaceIntersectionPoint - worldSpaceOrigin); |
| 466 |
|
| 467 |
// The sphere is a uniform color, so you don't need to interpolate the color across the surface. |
| 468 |
surfaceColor = sphere.color; |
| 469 |
} |
| 470 |
|
| 471 |
dstTex.write(float4(accumulatedColor, 1.0f), tid); |
| 472 |
|
| 473 |
// Choose a random light source to sample. |
| 474 |
float lightSample = halton(offset + uniforms.frameIndex, 2 + bounce * 5 + 0); |
| 475 |
unsigned int lightIndex = min((unsigned int)(lightSample * uniforms.lightCount), uniforms.lightCount - 1); |
| 476 |
|
| 477 |
// Choose a random point to sample on the light source. |
| 478 |
float2 r = float2(halton(offset + uniforms.frameIndex, 2 + bounce * 5 + 1), |
| 479 |
halton(offset + uniforms.frameIndex, 2 + bounce * 5 + 2)); |
| 480 |
|
| 481 |
float3 worldSpaceLightDirection; |
| 482 |
float3 lightColor; |
| 483 |
float lightDistance; |
| 484 |
|
| 485 |
// Sample the lighting between the intersection point and the point on the area light. |
| 486 |
sampleAreaLight(areaLights[lightIndex], r, worldSpaceIntersectionPoint, worldSpaceLightDirection, |
| 487 |
lightColor, lightDistance); |
| 488 |
|
| 489 |
// Scale the light color by the cosine of the angle between the light direction and |
| 490 |
// surface normal. |
| 491 |
lightColor *= saturate(dot(worldSpaceSurfaceNormal, worldSpaceLightDirection)); |
| 492 |
|
| 493 |
// Scale the light color by the number of lights to compensate for the fact that |
| 494 |
// the sample samples only one light source at random. |
| 495 |
lightColor *= uniforms.lightCount; |
| 496 |
|
| 497 |
// Scale the ray color by the color of the surface to simulate the surface absorbing light. |
| 498 |
color *= surfaceColor; |
| 499 |
|
| 500 |
// Compute the shadow ray. The shadow ray checks whether the sample position on the |
| 501 |
// light source is visible from the current intersection point. |
| 502 |
// If it is, the kernel adds lighting to the output image. |
| 503 |
struct ray shadowRay; |
| 504 |
|
| 505 |
// Add a small offset to the intersection point to avoid intersecting the same |
| 506 |
// triangle again. |
| 507 |
shadowRay.origin = worldSpaceIntersectionPoint + worldSpaceSurfaceNormal * 1e-3f; |
| 508 |
|
| 509 |
// Travel toward the light source. |
| 510 |
shadowRay.direction = worldSpaceLightDirection; |
| 511 |
|
| 512 |
// Don't overshoot the light source. |
| 513 |
shadowRay.max_distance = lightDistance - 1e-3f; |
| 514 |
|
| 515 |
// Shadow rays check only whether there is an object between the intersection point |
| 516 |
// and the light source. Tell Metal to return after finding any intersection. |
| 517 |
i.accept_any_intersection(true); |
| 518 |
|
| 519 |
if (useIntersectionFunctions) |
| 520 |
intersection = i.intersect(shadowRay, accelerationStructure, RAY_MASK_SHADOW, intersectionFunctionTable); |
| 521 |
else |
| 522 |
intersection = i.intersect(shadowRay, accelerationStructure, RAY_MASK_SHADOW); |
| 523 |
|
| 524 |
// If there was no intersection, then the light source is visible from the original |
| 525 |
// intersection point. Add the light's contribution to the image. |
| 526 |
if (intersection.type == intersection_type::none) |
| 527 |
accumulatedColor += lightColor * color; |
| 528 |
|
| 529 |
// Choose a random direction to continue the path of the ray. This causes light to |
| 530 |
// bounce between surfaces. An app might evaluate a more complicated equation to |
| 531 |
// calculate the amount of light that reflects between intersection points. However, |
| 532 |
// all the math in this kernel cancels out because this app assumes a simple diffuse |
| 533 |
// BRDF and samples the rays with a cosine distribution over the hemisphere (importance |
| 534 |
// sampling). This requires that the kernel only multiply the colors together. This |
| 535 |
// sampling strategy also reduces the amount of noise in the output image. |
| 536 |
r = float2(halton(offset + uniforms.frameIndex, 2 + bounce * 5 + 3), |
| 537 |
halton(offset + uniforms.frameIndex, 2 + bounce * 5 + 4)); |
| 538 |
|
| 539 |
float3 worldSpaceSampleDirection = sampleCosineWeightedHemisphere(r); |
| 540 |
worldSpaceSampleDirection = alignHemisphereWithNormal(worldSpaceSampleDirection, worldSpaceSurfaceNormal); |
| 541 |
|
| 542 |
ray.origin = worldSpaceIntersectionPoint + worldSpaceSurfaceNormal * 1e-3f; |
| 543 |
ray.direction = worldSpaceSampleDirection; |
| 544 |
} |
| 545 |
|
| 546 |
// Average this frame's sample with all of the previous frames. |
| 547 |
if (uniforms.frameIndex > 0) { |
| 548 |
float3 prevColor = prevTex.read(tid).xyz; |
| 549 |
prevColor *= uniforms.frameIndex; |
| 550 |
|
| 551 |
accumulatedColor += prevColor; |
| 552 |
accumulatedColor /= (uniforms.frameIndex + 1); |
| 553 |
} |
| 554 |
|
| 555 |
dstTex.write(float4(accumulatedColor, 1.0f), tid); |
| 556 |
} |
| 557 |
|
| 558 |
// Screen filling quad in normalized device coordinates. |
| 559 |
constant float2 quadVertices[] = { |
| 560 |
float2(-1, -1), |
| 561 |
float2(-1, 1), |
| 562 |
float2( 1, 1), |
| 563 |
float2(-1, -1), |
| 564 |
float2( 1, 1), |
| 565 |
float2( 1, -1) |
| 566 |
}; |
| 567 |
|
| 568 |
struct CopyVertexOut { |
| 569 |
float4 position [[position]]; |
| 570 |
float2 uv; |
| 571 |
}; |
| 572 |
|
| 573 |
// Simple vertex shader that passes through NDC quad positions. |
| 574 |
vertex CopyVertexOut copyVertex(unsigned short vid [[vertex_id]]) { |
| 575 |
float2 position = quadVertices[vid]; |
| 576 |
|
| 577 |
CopyVertexOut out; |
| 578 |
|
| 579 |
out.position = float4(position, 0, 1); |
| 580 |
out.uv = position * 0.5f + 0.5f; |
| 581 |
|
| 582 |
return out; |
| 583 |
} |
| 584 |
|
| 585 |
// Simple fragment shader that copies a texture and applies a simple tonemapping function. |
| 586 |
fragment float4 copyFragment(CopyVertexOut in [[stage_in]], |
| 587 |
texture2d<float> tex) |
| 588 |
{ |
| 589 |
constexpr sampler sam(min_filter::nearest, mag_filter::nearest, mip_filter::none); |
| 590 |
|
| 591 |
float3 color = tex.sample(sam, in.uv).xyz; |
| 592 |
|
| 593 |
// Apply a simple tonemapping function to reduce the dynamic range of the |
| 594 |
// input image into a range which the screen can display. |
| 595 |
color = color / (1.0f + color); |
| 596 |
|
| 597 |
return float4(color, 1.0f); |
| 598 |
} |