75 lines
1.9 KiB
Plaintext
75 lines
1.9 KiB
Plaintext
[nzsl_version("1.0")]
|
|
module Math.CookTorrancePBR;
|
|
|
|
import Pi from Math.Constants;
|
|
|
|
[export]
|
|
fn DistributionGGX(N: vec3[f32], H: vec3[f32], roughness: f32) -> f32
|
|
{
|
|
let a = roughness * roughness;
|
|
let a2 = a * a;
|
|
|
|
let NdotH = max(dot(N, H), 0.0);
|
|
let NdotH2 = NdotH * NdotH;
|
|
|
|
let num = a2;
|
|
let denom = (NdotH2 * (a2 - 1.0) + 1.0);
|
|
denom = Pi * denom * denom;
|
|
|
|
return num / denom;
|
|
}
|
|
|
|
[export]
|
|
fn GeometrySchlickGGX(NdotV: f32, roughness: f32) -> f32
|
|
{
|
|
let r = (roughness + 1.0);
|
|
let k = (r * r) / 8.0;
|
|
|
|
let num = NdotV;
|
|
let denom = NdotV * (1.0 - k) + k;
|
|
|
|
return num / denom;
|
|
}
|
|
|
|
[export]
|
|
fn GeometrySmith(N: vec3[f32], V: vec3[f32], L: vec3[f32], roughness: f32) -> f32
|
|
{
|
|
let NdotV = max(dot(N, V), 0.0);
|
|
let NdotL = max(dot(N, L), 0.0);
|
|
let ggx2 = GeometrySchlickGGX(NdotV, roughness);
|
|
let ggx1 = GeometrySchlickGGX(NdotL, roughness);
|
|
|
|
return ggx1 * ggx2;
|
|
}
|
|
|
|
[export]
|
|
fn FresnelSchlick(cosTheta: f32, F0: vec3[f32]) -> vec3[f32]
|
|
{
|
|
// TODO: Clamp
|
|
return F0 + (vec3[f32](1.0, 1.0, 1.0) - F0) * pow(min(max(1.0 - cosTheta, 0.0), 1.0), 5.0);
|
|
}
|
|
|
|
[export]
|
|
fn ComputeLightRadiance(lightColor: vec3[f32], posToLight: vec3[f32], lightAttenuation: f32, albedoFactor: vec3[f32], eyeVec: vec3[f32], F0: vec3[f32], normal: vec3[f32], metallic: f32, roughness: f32) -> vec3[f32]
|
|
{
|
|
let radiance = lightColor * lightAttenuation;
|
|
|
|
let halfDir = normalize(posToLight + eyeVec);
|
|
|
|
// Cook-Torrance BRDF
|
|
let NDF = DistributionGGX(normal, halfDir, roughness);
|
|
let G = GeometrySmith(normal, eyeVec, posToLight, roughness);
|
|
let F = FresnelSchlick(max(dot(halfDir, eyeVec), 0.0), F0);
|
|
|
|
let kS = F;
|
|
let diffuse = vec3[f32](1.0, 1.0, 1.0) - kS;
|
|
diffuse *= 1.0 - metallic;
|
|
|
|
let numerator = NDF * G * F;
|
|
let denominator = 4.0 * max(dot(normal, eyeVec), 0.0) * max(dot(normal, posToLight), 0.0);
|
|
let specular = numerator / max(denominator, 0.0001);
|
|
|
|
let NdotL = max(dot(normal, posToLight), 0.0);
|
|
return (diffuse * albedoFactor + specular) * radiance * NdotL;
|
|
}
|