Refraction.hlsl 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #ifndef UNITY_REFRACTION_INCLUDED
  2. #define UNITY_REFRACTION_INCLUDED
  3. //-----------------------------------------------------------------------------
  4. // Util refraction
  5. //-----------------------------------------------------------------------------
  6. struct RefractionModelResult
  7. {
  8. real dist; // length of the transmission during refraction through the shape
  9. float3 positionWS; // out ray position
  10. real3 rayWS; // out ray direction
  11. };
  12. RefractionModelResult RefractionModelSphere(real3 V, float3 positionWS, real3 normalWS, real ior, real thickness)
  13. {
  14. // Sphere shape model:
  15. // We approximate locally the shape of the object as sphere, that is tangent to the shape.
  16. // The sphere has a diameter of {thickness}
  17. // The center of the sphere is at {positionWS} - {normalWS} * {thickness}
  18. //
  19. // So the light is refracted twice: in and out of the tangent sphere
  20. // First refraction (tangent sphere in)
  21. // Refracted ray
  22. real3 R1 = refract(-V, normalWS, 1.0 / ior);
  23. // Center of the tangent sphere
  24. real3 C = positionWS - normalWS * thickness * 0.5;
  25. // Second refraction (tangent sphere out)
  26. real NoR1 = dot(normalWS, R1);
  27. // Optical depth within the sphere
  28. real dist = -NoR1 * thickness;
  29. // Out hit point in the tangent sphere
  30. real3 P1 = positionWS + R1 * dist;
  31. // Out normal
  32. real3 N1 = normalize(C - P1);
  33. // Out refracted ray
  34. real3 R2 = refract(R1, N1, ior);
  35. real N1oR2 = dot(N1, R2);
  36. real VoR1 = dot(V, R1);
  37. RefractionModelResult result;
  38. result.dist = dist;
  39. result.positionWS = P1;
  40. result.rayWS = R2;
  41. return result;
  42. }
  43. RefractionModelResult RefractionModelBox(real3 V, float3 positionWS, real3 normalWS, real ior, real thickness)
  44. {
  45. // Plane shape model:
  46. // We approximate locally the shape of the object as a plane with normal {normalWS} at {positionWS}
  47. // with a thickness {thickness}
  48. // Refracted ray
  49. real3 R = refract(-V, normalWS, 1.0 / ior);
  50. // Optical depth within the thin plane
  51. real dist = thickness / max(dot(R, -normalWS), 1e-5f);
  52. RefractionModelResult result;
  53. result.dist = dist;
  54. result.positionWS = positionWS + R * dist;
  55. result.rayWS = -V;
  56. return result;
  57. }
  58. #endif