Skip to content

Instantly share code, notes, and snippets.

@hyblocker
Last active January 3, 2023 02:37
Show Gist options
  • Save hyblocker/ee703ec676db7b43c150aec6860148a1 to your computer and use it in GitHub Desktop.
Save hyblocker/ee703ec676db7b43c150aec6860148a1 to your computer and use it in GitHub Desktop.
Skybox Hemisphere Projection
/*
Copyright 2023 Hyblocker
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
struct HemisphereProjectionParams {
float3 view;
float3 cameraPosition;
float radius;
float scale;
};
float3 getProjectedHemisphereCoord(HemisphereProjectionParams params)
{
params.cameraPosition.xz = params.cameraPosition.xz / params.radius * 0.1f;
params.cameraPosition.y = min(params.cameraPosition.y, -1.f) * params.scale;
const float3 planeNormal = float3(0.f, 1.f, 0.f);
const float rayLength = dot(params.cameraPosition, planeNormal) / dot(params.view, planeNormal);
const float3 intersectPoint = params.cameraPosition + params.view * rayLength;
const float3 finalView = normalize(intersectPoint);
return lerp(finalView, params.view, params.view.y > 0.f);
}
//
// Usage
//
const float3 view = normalize(i.viewDir);
// Compute camera position with capture point offset taken into account
const float3 cameraPos = (_CapturePoint - _WorldSpaceCameraPos) * lerp(1.f, float3(0.f, 1.f, 0.f), _AltitudeOnly);
HemisphereProjectionParams projectParams = (HemisphereProjectionParams)0;
projectParams.view = view;
projectParams.cameraPosition = cameraPos;
projectParams.radius = _Radius;
projectParams.scale = _Scale;
// Project it onto the floor
float3 adjustedView = getProjectedHemisphereCoord(projectParams);
// sample the texture
return texCUBE(_MainTex, adjustedView);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment