Rework compute kernel

This commit is contained in:
Dynamitos
2026-08-02 07:56:02 +02:00
parent a857051eea
commit fb6b84a7b7
16 changed files with 665 additions and 658 deletions
-125
View File
@@ -1,125 +0,0 @@
import Common;
[shader("closesthit")]
void closestHit(inout RayPayload hitValue, in BuiltInTriangleIntersectionAttributes attr)
{
hitValue.hit = true;
// todo: replace with anyhit shader
if(hitValue.anyHit)
return;
const float3 barycentricCoords = float3(1.0f - attr.barycentrics.x - attr.barycentrics.y, attr.barycentrics.x, attr.barycentrics.y);
ModelReference m = pParams.modelData[InstanceID()];
// offset into the index buffer
uint indexOffset = m.indicesOffset;
// added to indices to reference correct part of global mesh pool
uint vertexOffset = m.positionOffset;
uint vertexIndex0 = vertexOffset + pParams.indexBuffer[indexOffset + 3 * PrimitiveIndex() + 0];
uint vertexIndex1 = vertexOffset + pParams.indexBuffer[indexOffset + 3 * PrimitiveIndex() + 1];
uint vertexIndex2 = vertexOffset + pParams.indexBuffer[indexOffset + 3 * PrimitiveIndex() + 2];
Vertex attr0 = loadVertex(vertexIndex0);
Vertex attr1 = loadVertex(vertexIndex1);
Vertex attr2 = loadVertex(vertexIndex2);
Vertex vert = Vertex.interpolate(attr0, attr1, attr2, barycentricCoords);
float3 normalLight = dot(vert.normal, WorldRayDirection()) < 0 ? vert.normal : -vert.normal;
MaterialParameter mat = pParams.materialData[m.materialIndex];
float3 emissive = mat.emissive_type.xyz;
float3 localAccRad = float3(0);
float3 rnd = rand01(uint3(vertexIndex0, vertexIndex1, vertexIndex2));
//float kt = ka + ks;
//float s = -log(rnd.z) / kt;
//float3 xs = r.o + s * r.d;
//if (s < t) {
// float p = kt * rnd.z;
// if (depth > 5) {
// if (rnd.z >= p) break;
// else accmat /= p;
// }
// float3 ldirect = nextEventEstimation(accmat, r.d, xs, -r.d, kt, true, rnd);
// accrad += (fogEmm + ks * ldirect) / kt;
// accmat *= ks / kt;
// rayDesc.Origin = xs;
// rayDesc.Direction = float3(
// cos(2*PI*rnd.x)*sqrt(1-rnd.y*rnd.y),
// sin(2*PI*rnd.x)*sqrt(1-rnd.y*rnd.y),
// rnd.y
// );
// continue;
//}
//float p = max(max(mat.albedo.x, mat.albedo.y), mat.albedo.z);
//if(hitValue.depth > 5) {
// if (rnd.z >= p) return;
// else hitValue.accmat /= p;
//}
//-- Ideal DIFFUSE reflection
//if(bool(useNEE)) {
// accrad += nextEventEstimation(accmat, r.d, params.x, params.nl, kt, false, rnd);
//}
for(uint i = 0; i < pSamps.numDirectionalLights; ++i) {
float3 x = vert.position;
float3 l = -pParams.directionalLights[i].direction.xyz;
RayDesc rayDesc;
rayDesc.TMax = 10000.0f;
rayDesc.TMin = 0.001f;
rayDesc.Origin = x;
rayDesc.Direction = l;
RayPayload payload;
payload.depth = hitValue.depth;
payload.emissive = 1;
payload.anyHit = true;
TraceRay(pParams.scene, 0, 0xff, 0, 0, 0, rayDesc, payload);
// we have missed all geometry, so directional light is affecting us
if(!payload.hit) {
localAccRad += mat.shade(vert.normal, -WorldRayDirection(), -pParams.directionalLights[i].direction, pParams.directionalLights[i].color);
}
}
for(uint i = 0; i < pSamps.numPointLights; ++i) {
RayPayload payload;
float3 x = vert.position;
float3 l = pParams.pointLights[i].position - vert.position;
// todo: cancel if light too far away to affect
RayDesc rayDesc;
rayDesc.TMax = 1.0f;
rayDesc.TMin = 0.001f;
rayDesc.Origin = x;
rayDesc.Direction = l;
TraceRay(pParams.scene, 0, 0xff, 0, 0, 0, rayDesc, payload);
// hitting only after the light
if(!payload.hit) {
localAccRad += mat.shade(vert.normal, -WorldRayDirection(), normalize(l), pParams.pointLights[i].color);
}
}
hitValue.light += localAccRad + emissive;
// Indirect Illumination: cosine-weighted importance sampling
if(hitValue.depth < 12) {
float r1 = 2 * PI * rnd.x, r2 = rnd.y, r2s = sqrt(r2);
float3 w = normalLight;
float3 u = normalize((cross(abs(w.x)>0.1 ? float3(0,1,0) : float3(1,0,0), w)));
float3 v = cross(w,u);
RayDesc rayDesc;
rayDesc.TMax = 10000.0f;
rayDesc.TMin = 0.001f;
rayDesc.Origin = vert.position;
rayDesc.Direction = normalize(u*cos(r1)*r2s + v * sin(r1)*r2s + w * sqrt(1 - r2));
RayPayload payload;
payload.light = float3(0);
payload.emissive = 0; // in the next bounce, consider reflective part only!
payload.depth = hitValue.depth+1;
payload.anyHit = false;
TraceRay(pParams.scene, 0, 0xff, 0, 0, 0, rayDesc, payload);
}
}
+168 -64
View File
@@ -1,81 +1,185 @@
import Common;
struct HitInfo
{
float3 position;
float3 normal;
float3 barycentricCoords;
uint instanceIndex;
uint primitiveIndex;
};
HitInfo get_hit_info(RayQuery<RAY_FLAG_NONE> q)
{
HitInfo info;
// In Slang for Metal/Vulkan, these are the standard names for ray query results
info.instanceIndex = q.CommittedInstanceID();
info.primitiveIndex = q.CommittedPrimitiveIndex();
float2 baryCenter = q.CommittedRayBarycentrics();
info.barycentricCoords = float3(1.0f - baryCenter.x - baryCenter.y, baryCenter.x, baryCenter.y);
return info;
}
Vertex interpolate_vertex(uint vertexIdx0, uint vertexIdx1, uint vertexIdx2, float3 bary)
{
Vertex v0 = loadVertex(vertexIdx0);
Vertex v1 = loadVertex(vertexIdx1);
Vertex v2 = loadVertex(vertexIdx2);
Vertex vert;
vert.position = v0.position * bary.x + v1.position * bary.y + v2.position * bary.z;
vert.texCoords = v0.texCoords * bary.x + v1.texCoords * bary.y + v2.texCoords * bary.z;
vert.normal = v0.normal * bary.x + v1.normal * bary.y + v2.normal * bary.z;
return vert;
}
[shader("compute")]
[numthreads(8, 8, 1)]
void computeKernel(uint2 threadId [[thread_position_in_grid]])
void computeKernel(uint2 threadId: SV_DispatchThreadID)
{
if (threadId.x >= pParams.cam.width || threadId.y >= pParams.cam.height)
return;
if (threadId.x >= pParams.cam.width || threadId.y >= pParams.cam.height)
return;
uint pass = pSamps.pass;
uint samplesPerPixel = pSamps.samplesPerPixel;
if (pass == samplesPerPixel) return;
uint pass = pSamps.pass;
uint samplesPerPixel = pSamps.samplesPerPixel;
if (pass == samplesPerPixel)
return;
uint2 pix = threadId;
uint imgWidth = pParams.cam.width;
uint imgHeight = pParams.cam.height;
uint2 pix = threadId;
uint imgWidth = pParams.cam.width;
uint imgHeight = pParams.cam.height;
//-- define cam
float3 camPos = pParams.cam.cameraPosition;
float3 camForward = pParams.cam.cameraForward;
float f = pParams.cam.f;
float S_O = pParams.cam.S_O;
float3 fogEmm = pParams.cam.fogEmm;
float ks = pParams.cam.ks;
float A = pParams.cam.A;
float ka = pParams.cam.ka;
float2 sensorSize = pParams.cam.sensorSize;
// -- Camera setup --
float3 camPos = pParams.cam.cameraPosition;
float3 camForward = pParams.cam.cameraForward;
float f = pParams.cam.f;
float S_O = pParams.cam.S_O;
float3 fogEmm = pParams.cam.fogEmm;
float ks = pParams.cam.ks;
float A = pParams.cam.A;
float ka = pParams.cam.ka;
float2 sensorSize = pParams.cam.sensorSize;
float3 cx = -normalize(cross(camForward, abs(camForward.y) < 0.9 ? float3(0, 1, 0) : float3(0, 0, 1)));
float3 cy = cross(camForward, cx);
const float2 sdim = sensorSize;
float3 cx = -normalize(cross(camForward, abs(camForward.y) < 0.9 ? float3(0, 1, 0) : float3(0, 0, 1)));
float3 cy = cross(camForward, cx);
const float2 sdim = sensorSize;
float S_I = (S_O * f) / (S_O - f);
float S_I = (S_O * f) / (S_O - f);
//-- sample sensor
float3 rnd = rand01(uint3(pix, pass));
float2 rnd2 = 2.0f * float2(rnd.xy); // tent filter
float2 tent = float2(rnd2.x < 1 ? sqrt(rnd2.x) - 1 : 1 - sqrt(2 - rnd2.x),
rnd2.y < 1 ? sqrt(rnd2.y) - 1 : 1 - sqrt(2 - rnd2.y));
float2 s = ((float2(pix) + 0.5f * (0.5f + float2((pass / 2) % 2, pass % 2) + tent)) / float2(imgWidth, imgHeight) - 0.5f) * sdim;
float3 lc = camPos + camForward * 0.035f; // sample on 3d sensor plane
float3 spos = camPos + cx * s.x + cy * s.y;
float3 rayDir = normalize(lc - spos);
// -- Sample sensor --
float3 rnd = rand01(uint3(pix, pass));
float2 rnd2 = 2.0f * float2(rnd.xy); // tent filter
float2 tent = float2(rnd2.x < 1 ? sqrt(rnd2.x) - 1 : 1 - sqrt(2 - rnd2.x), rnd2.y < 1 ? sqrt(rnd2.y) - 1 : 1 - sqrt(2 - rnd2.y));
float2 s = ((float2(pix) + 0.5f * (0.5f + float2((pass / 2) % 2, pass % 2) + tent)) / float2(imgWidth, imgHeight) - 0.5f) * sdim;
//-- setup lens (simplified)
float3 lensSample = lc; // for now, just use camera position slightly offset if needed?
// Actually let's do it properly based on A parameter
float3 lensN = -camForward;
float3 lensX = cross(lensN, float3(0, 1, 0));
float3 lensY = cross(lensN, lensX);
float2 rnd01 = rand01(uint3(pix, pass)).xy;
lensSample = lc + rnd01.x * A * lensX + rnd01.y * A * lensY;
float3 lc = camPos + camForward * 0.035f; // sample on 3d sensor plane
float3 spos = camPos + cx * s.x + cy * s.y;
float3 rayDir = normalize(lc - spos);
float focalPoint = camPos + (S_O + S_I) * camForward;
float t_focus = dot(focalPoint - lensSample, lensN) / dot(rayDir, lensN);
float3 focus = lensSample + t_focus * rayDir;
float3 rayOrg = lensSample;
float3 rayDirFinal = normalize(focus - lensSample);
// -- Lens (Aperture) --
float3 lensN = -camForward;
float3 lensX = cross(lensN, float3(0, 1, 0));
float3 lensY = cross(lensN, lensX);
float2 rndL = rand01(uint3(pix, pass + 100)).xy;
float3 lensSample = lc + (rndL.x - 0.5) * A * lensX + (rndL.y - 0.5) * A * lensY;
// Ray Tracing Loop
RayPayload payload;
payload.light = float3(0);
payload.emissive = 1.0f;
payload.depth = 1;
payload.hit = false;
payload.anyHit = false;
float3 focalPoint = camPos + (S_O + S_I) * camForward;
// Note: We are using the compute-based intersection loop because it's easier to implement in a single kernel
// and we have access to common helper functions. In a full RT pipeline we would use dedicated shaders.
// Since we don't have the specialized 'intersector' object from before,
// we will use a placeholder for now or assume it's available if provided by Slang/Metal context.
// BUT since I am writing this from scratch, I should probably implement the traversal OR
// just use MS's Compute-based approach as in Compute.metal which worked.
// Wait! To keep it simple and "lazy", I will just copy the logic from Compute.metal into this Slang file
// and replace all its types with pParams fields.
// Simple ray construction
float3 rayOrg = lensSample;
float3 rayDirFinal = normalize(focalPoint - lensSample);
// -- Path Tracing Loop --
float3 accumulatedRadiance = float3(0.0);
float3 throughput = float3(1.0);
for (int bounce = 0; bounce < 4; ++bounce)
{
RayQuery<RAY_FLAG_NONE> q;
RayDesc rayDesc;
rayDesc.Origin = rayOrg;
rayDesc.Direction = rayDirFinal;
rayDesc.TMin = 0.001;
rayDesc.TMax = 1e20;
q.TraceRayInline(pParams.scene, RAY_FLAG_NONE, 0xff, rayDesc);
if (q.Proceed())
{
HitInfo hit = get_hit_info(q);
ModelReference m = pParams.modelData[hit.instanceIndex];
uint indexOffset = m.indicesOffset;
uint vertexOffset = m.positionOffset;
uint v0 = vertexOffset + pParams.indexBuffer[indexOffset + 3 * hit.primitiveIndex + 0];
uint v1 = vertexOffset + pParams.indexBuffer[indexOffset + 3 * hit.primitiveIndex + 1];
uint v2 = vertexOffset + pParams.indexBuffer[indexOffset + 3 * hit.primitiveIndex + 2];
Vertex vert = interpolate_vertex(v0, v1, v2, hit.barycentricCoords);
MaterialParameter mat = pParams.materialData[m.materialIndex];
accumulatedRadiance += throughput * mat.emissive_type.xyz;
// --- Direct Lighting (NEE) ---
float3 directLight = float3(0);
for (uint i = 0; i < pSamps.numDirectionalLights; ++i)
{
float3 lDir = -pParams.directionalLights[i].direction.xyz;
RayQuery<RAY_FLAG_NONE> sq;
RayDesc rayDesc;
rayDesc.Origin = vert.position + vert.normal * 0.001;
rayDesc.Direction = lDir;
rayDesc.TMin = 0.001;
rayDesc.TMax = 1e20;
sq.TraceRayInline(pParams.scene, RAY_FLAG_NONE, 0xff, rayDesc);
if (!sq.Proceed())
{
directLight += mat.shade(vert.normal, -rayDirFinal, lDir, pParams.directionalLights[i].color);
}
}
for (uint i = 0; i < pSamps.numPointLights; ++i)
{
float3 lVec = pParams.pointLights[i].position - vert.position;
float3 lDir = normalize(lVec);
RayQuery<RAY_FLAG_NONE> sq;
RayDesc rayDesc;
rayDesc.Origin = vert.position + vert.normal * 0.001;
rayDesc.Direction = lDir;
rayDesc.TMin = 0.001;
rayDesc.TMax = 1e20;
sq.TraceRayInline(pParams.scene, RAY_FLAG_NONE, 0xff, rayDesc);
if (sq.Proceed() == false || sq.CommittedRayT() > length(lVec))
{
directLight += mat.shade(vert.normal, -rayDirFinal, lDir, pParams.pointLights[i].color);
}
}
accumulatedRadiance += throughput * directLight;
// --- Indirect Lighting (Cosine-weighted sampling) ---
float3 rnd = rand01(uint3(pix, pass + bounce + 200));
float r1 = 2.0 * PI * rnd.x;
float r2 = rnd.y;
float r2s = sqrt(r2);
float3 w = vert.normal;
float3 u = normalize(cross(abs(w.x) > 0.1 ? float3(0, 1, 0) : float3(1, 0, 0), w));
float3 v = cross(w, u);
float3 nextDir = normalize(u * cos(r1) * r2s + v * sin(r1) * r2s + w * sqrt(1.0 - r2));
throughput *= mat.albedo_alpha.xyz;
rayOrg = vert.position + vert.normal * 0.001;
rayDirFinal = nextDir;
if (length(throughput) < 0.01)
break;
}
else
{
accumulatedRadiance += throughput * float3(0.05, 0.05, 0.1);
break;
}
}
pParams.image[threadId] = float4(accumulatedRadiance, 1.0);
}
-8
View File
@@ -1,8 +0,0 @@
import Common;
[shader("miss")]
void miss(inout RayPayload p)
{
p.light = float3(0.05, 0.05, 0.1); // Dark blueish background instead of black
p.hit = false;
}
-57
View File
@@ -1,57 +0,0 @@
import Common;
[shader("raygeneration")]
void raygen()
{
if(pSamps.pass == pSamps.samplesPerPixel) return;
uint2 pix = DispatchRaysIndex().xy;
uint2 imgdim = DispatchRaysDimensions().xy;
//-- define cam
Ray cam = Ray(pParams.cam.cameraPosition, pParams.cam.cameraForward);
float3 cx = -normalize(cross(cam.d, abs(cam.d.y) < 0.9 ? float3(0, 1, 0) : float3(0, 0, 1))), cy = cross(cam.d, cx);
const float2 sdim = float2(0.036, 0.024);
float S_I = (pParams.cam.S_O * pParams.cam.f) / (pParams.cam.S_O - pParams.cam.f);
//-- sample sensor
float2 rnd2 = 2*rand01(uint3(pix, pSamps.pass)).xy; // vvv tent filter sample
float2 tent = float2(rnd2.x<1 ? sqrt(rnd2.x)-1 : 1-sqrt(2-rnd2.x), rnd2.y<1 ? sqrt(rnd2.y)-1 : 1-sqrt(2-rnd2.y));
float2 s = ((pix + 0.5 * (0.5 + float2((pSamps.pass/2)%2, pSamps.pass%2) + tent)) / float2(imgdim) - 0.5) * sdim;
float3 spos = cam.o + cx*s.x + cy*s.y, lc = cam.o + cam.d * 0.035; // sample on 3d sensor plane
Ray r = Ray(lc, normalize(lc - spos)); // construct ray
//-- setup lens
float3 lensP = lc;
float3 lensN = -cam.d;
float3 lensX = cross(lensN, float3(0, 1, 0)); // the exact vector doesnt matter
float3 lensY = cross(lensN, lensX);
uint3 rndSeed = uint3(pix, pSamps.pass);
float2 rnd01 = rand01(rndSeed).xy;
float3 lensSample = lensP + rnd01.x * pParams.cam.A * lensX + rnd01.y * pParams.cam.A * lensY;
float3 focalPoint = cam.o + (pParams.cam.S_O + S_I) * cam.d;
float t = dot(focalPoint - r.o, lensN) / dot(r.d, lensN);
float3 focus = r.o + t * r.d;
RayDesc rayDesc;
rayDesc.Origin = lensSample;
rayDesc.Direction = normalize(focus - lensSample);
rayDesc.TMin = 0.001;
rayDesc.TMax = 10000.0;
const uint maxDepth = 12;
RayPayload payload;
// initialize accumulated radiance and bxdf
payload.light=float3(0);
payload.emissive = 1;
payload.depth = 1;
payload.anyHit = false;
TraceRay(pParams.scene, 0, 0xff, 0, 0, 0, rayDesc, payload);
if(pSamps.pass == 0) pParams.radianceAccumulator[pix] = float4(0);
pParams.radianceAccumulator[pix] += float4(payload.light / pSamps.samplesPerPixel, 0);
pParams.image[pix] = float4(clamp(pParams.radianceAccumulator[pix].xyz, 0, 1), 1);
}