Skip to content

Instantly share code, notes, and snippets.

@maluoi
Last active February 25, 2023 05:07
Show Gist options
  • Save maluoi/5e604f028bb413309d37132502420f90 to your computer and use it in GitHub Desktop.
Save maluoi/5e604f028bb413309d37132502420f90 to your computer and use it in GitHub Desktop.
StereoKit fresnel shader
#include <stereokit.hlsli>
//--color: color = 1,1,1,1
//--color2:color = 0,0,0,1
//--slope = 1000
//--threshold = 0.2
float4 color;
float4 color2;
float threshold;
float slope;
struct vsIn {
float4 pos : SV_POSITION;
float3 norm : NORMAL0;
float2 uv : TEXCOORD0;
float4 col : COLOR0;
};
struct psIn {
float4 pos : SV_POSITION;
float4 color : COLOR0;
float3 world : TEXCOORD0;
float3 normal : TEXCOORD1;
float3 view_dir: TEXCOORD2;
uint view_id : SV_RenderTargetArrayIndex;
};
float sigmoid(float x, float slope) {
// A graph of this can be found here:
// https://www.desmos.com/calculator/mqb8farthj
return (0.5/((1 / (1 + exp(-slope )) - 0.5))) *
(1 / (1 + exp(-(2*x - 1)*slope)) - 0.5) + 0.5;
}
psIn vs(vsIn input, uint id : SV_InstanceID) {
psIn o;
o.view_id = id % sk_view_count;
id = id / sk_view_count;
o.world = mul(float4(input.pos.xyz, 1), sk_inst[id].world).xyz;
o.pos = mul(float4(o.world, 1), sk_viewproj[o.view_id]);
o.normal = normalize(mul(input.norm, (float3x3)sk_inst[id].world));
o.view_dir = sk_camera_pos[o.view_id].xyz - o.world;
o.color = input.col * color * sk_inst[id].color;
return o;
}
float4 ps(psIn input) : SV_TARGET{
float fresnel = dot(normalize(input.view_dir), normalize(input.normal));
fresnel = sigmoid(fresnel+threshold, slope);
float4 col = lerp(color, color2, fresnel);
return col * input.color;
}
using StereoKit;
SK.Initialize("FresnelEffect", "Assets");
Material fresnelMat = new Material("fresnel.hlsl");
Pose windowPose = new Pose(0.3f, 0, -0.5f, Quat.LookDir(-1,0,1));
float slope = 100;
float threshold = 0.2f;
Input.HandMaterial(Handed.Max, fresnelMat);
SK.Run(() => {
Mesh.Sphere.Draw(fresnelMat, Matrix.TS(0, 0, -0.5f, 0.3f));
UI.WindowBegin("Settings", ref windowPose, V.XY(0.24f,0));
UI.Label("Slope", V.XY(0.06f, 0));
UI.SameLine();
if (UI.HSlider("Slope", ref slope, 0, 100, 0, 0.1f))
fresnelMat["slope"] = slope;
UI.SameLine();
UI.Label($"{slope:0.0}", V.XY(0.03f, 0));
UI.Label("Threshold", V.XY(0.06f, 0));
UI.SameLine();
if (UI.HSlider("Threshold", ref threshold, -0.5f, 0.5f, 0, 0.1f))
fresnelMat["threshold"] = threshold;
UI.SameLine();
UI.Label($"{threshold:0.00}", V.XY(0.03f, 0));
UI.WindowEnd();
});
@maluoi
Copy link
Author

maluoi commented Feb 25, 2023

Looks kinda like this :)

FresnelShaderScreenshot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment