ObbIntersection.azsl 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <Atom/Features/RayTracing/RayTracingIntersectionAttributes.azsli>
  9. #include <Atom/Features/SrgSemantics.azsli>
  10. // https://github.com/erich666/GraphicsGems/blob/master/gems/RayBox.c
  11. bool IntersectRayAABB(float3 rayOrigin, float3 rayDirection, float3 aabbMin, float3 aabbMax, out float t, out float3 normal)
  12. {
  13. t = 0.f;
  14. normal = float3(1, 0, 0);
  15. float3 maxT;
  16. for (int i = 0; i < 3; i++)
  17. {
  18. if ((rayOrigin[i] < aabbMin[i] || rayOrigin[i] > aabbMax[i]) && rayDirection[i] != 0)
  19. {
  20. maxT[i] = ((rayOrigin[i] < aabbMin[i] ? aabbMin[i] : aabbMax[i]) - rayOrigin[i]) / rayDirection[i];
  21. }
  22. else
  23. {
  24. maxT[i] = -1;
  25. }
  26. }
  27. int whichPlane = 0;
  28. for (int i = 1; i < 3; i++)
  29. {
  30. if (maxT[whichPlane] < maxT[i])
  31. {
  32. whichPlane = i;
  33. }
  34. }
  35. t = maxT[whichPlane];
  36. if (t < 0)
  37. {
  38. return false;
  39. }
  40. for (int i = 0; i < 3; i++)
  41. {
  42. if (whichPlane != i)
  43. {
  44. float coord = rayOrigin[i] + t * rayDirection[i];
  45. if (coord < aabbMin[i] || coord > aabbMax[i])
  46. {
  47. return false;
  48. }
  49. }
  50. }
  51. normal = float3(0, 0, 0);
  52. normal[whichPlane] = rayDirection[whichPlane] > 0 ? -1 : 1;
  53. return true;
  54. }
  55. [shader("intersection")]
  56. void ObbIntersection()
  57. {
  58. const float3 aabbMin = float3(-1, -1, -1);
  59. const float3 aabbMax = float3(1, 1, 1);
  60. float t;
  61. float3 normal;
  62. if (IntersectRayAABB(ObjectRayOrigin(), ObjectRayDirection(), aabbMin, aabbMax, t, normal))
  63. {
  64. ProceduralGeometryIntersectionAttributes attrib;
  65. attrib.m_position = ObjectRayOrigin() + ObjectRayDirection() * t;
  66. attrib.m_normal = half3(normal);
  67. attrib.m_uv = half2(0, 0);
  68. attrib.m_tangent = half4(1, 0, 0, 1);
  69. ReportHit(t, 0, attrib);
  70. }
  71. }