DefaultAnyHit.hlsl 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "Common.hlsl"
  2. StructuredBuffer<int> textureIdBuffer : register(t1, space2);
  3. StructuredBuffer<int> indexBuffer : register(t1, space3);
  4. StructuredBuffer<VertexData> vertexData : register(t1, space4);
  5. StructuredBuffer<int> polygonSizeBuffer : register(t1, space5);
  6. ByteAddressBuffer lightBuffer : register(t1, space6);
  7. [shader("anyhit")]
  8. void AnyHit(inout RayHits rayPayload, SimpleBlocksAttributes attrib)
  9. {
  10. int instanceId = InstanceID();
  11. int currentTriangle = PrimitiveIndex();
  12. int textureId = 0;
  13. int i;
  14. for (i = 0; currentTriangle >= 0 && polygonSizeBuffer[i] > 0; i++)
  15. {
  16. currentTriangle -= polygonSizeBuffer[i];
  17. textureId = textureIdBuffer[i];
  18. }
  19. if (polygonSizeBuffer[i] <= 0)
  20. {
  21. // Could not find geometry index, ignore hit
  22. IgnoreHit();
  23. return;
  24. }
  25. Texture2D<float4> texture = textures[textureId];
  26. int index = PrimitiveIndex() * 3;
  27. // Bounds check for vertex indices
  28. if (indexBuffer[index] < 0 || indexBuffer[index + 1] < 0 || indexBuffer[index + 2] < 0)
  29. {
  30. IgnoreHit();
  31. return;
  32. }
  33. VertexData v0 = vertexData[indexBuffer[index]];
  34. VertexData v1 = vertexData[indexBuffer[index + 1]];
  35. VertexData v2 = vertexData[indexBuffer[index + 2]];
  36. float3 normal = v0.normal * (1 - attrib.bary.x - attrib.bary.y) + v1.normal * attrib.bary.x + v2.normal * attrib.bary.y;
  37. float2 texcoord = v0.texcoord * (1 - attrib.bary.x - attrib.bary.y) + v1.texcoord * attrib.bary.x + v2.texcoord * attrib.bary.y;
  38. float4 color = texture.SampleLevel(gSampler, texcoord, 0);
  39. if (color.w == 0.f)
  40. {
  41. IgnoreHit();
  42. return;
  43. }
  44. if (rayPayload.hitCount < 0)
  45. { // shadow ray
  46. rayPayload.hitCount = 0;
  47. // TODO: transparent objects should lead to half shadows
  48. AcceptHitAndEndSearch();
  49. return;
  50. }
  51. SingleHit hit;
  52. hit.color = color;
  53. hit.normal = normal;
  54. hit.distance = RayTCurrent();
  55. hit.dayLight = getLight(lightBuffer, 0);
  56. hit.dynamicLight = getLight(lightBuffer, 3);
  57. applyHit(rayPayload, hit);
  58. if (color.w < 1.f)
  59. {
  60. IgnoreHit();
  61. return;
  62. }
  63. }