1+ // Copyright (C) 2018-2025 - DevSH Graphics Programming Sp. z O.O.
2+ // This file is part of the "Nabla Engine".
3+ // For conditions of distribution and use, see copyright notice in nabla.h
4+
5+ #ifndef _NBL_BUILTIN_HLSL_MATH_OCTAHEDRAL_INCLUDED_
6+ #define _NBL_BUILTIN_HLSL_MATH_OCTAHEDRAL_INCLUDED_
7+
8+ #include "nbl/builtin/hlsl/cpp_compat.hlsl"
9+ #include "nbl/builtin/hlsl/numbers.hlsl"
10+
11+ namespace nbl
12+ {
13+ namespace hlsl
14+ {
15+ namespace math
16+ {
17+
18+ // Octahedral Transform, maps 3D direction vectors to 2D square and vice versa
19+ template<typename T = float64_t>
20+ struct OctahedralTransform
21+ {
22+ using scalar_type = T;
23+ using vector2_type = vector <T, 2 >;
24+ using vector3_type = vector <T, 3 >;
25+
26+ // F : [-1, 1]^2 -> S^2
27+ static vector3_type eval (const vector2_type ndc)
28+ {
29+ vector3_type p = vector3_type (ndc.xy, scalar_type (0 ));
30+ const vector2_type a = abs (p.xy);
31+
32+ p.z = scalar_type (1 ) - a.x - a.y;
33+
34+ if (p.z < scalar_type (0 ))
35+ p.xy = hlsl::sign (p.xy) * (scalar_type (1 ) - abs (p.yx));
36+
37+ return hlsl::normalize (p);
38+ }
39+
40+ // F^-1 : S^2 -> [-1, 1]^2
41+ static vector2_type inverse (vector3_type dir)
42+ {
43+ dir = hlsl::normalize (dir);
44+ const scalar_type sum = hlsl::dot (vector3_type (scalar_type (1 ), scalar_type (1 ), scalar_type (1 )), abs (dir));
45+ vector3_type s = dir / sum;
46+
47+ if (s.z < scalar_type (0 ))
48+ s.xy = hlsl::sign (s.xy) * (scalar_type (1 ) - abs (s.yx));
49+
50+ return s.xy;
51+ }
52+
53+ // transforms direction vector into UV (for corner sampling)
54+ // dir in S^2, halfMinusHalfPixel in [0, 0.5)^2,
55+ // where halfMinusHalfPixel = 0.5-0.5/texSize
56+ // and texSize.x >= 1, texSize.y >= 1
57+ // NOTE/TODO: not best place to keep it here imo
58+ static vector2_type toCornerSampledUV (vector3_type dir, vector2_type halfMinusHalfPixel)
59+ {
60+ // note: cornerSampled(NDC*0.5+0.5) = NDC*0.5*(1-1/texSize)+0.5
61+ return inverse (dir) * halfMinusHalfPixel + scalar_type (0.5 );
62+ }
63+ };
64+
65+ }
66+ }
67+ }
68+
69+ #endif // _NBL_BUILTIN_HLSL_MATH_OCTAHEDRAL_INCLUDED_
0 commit comments