Skip to content

Instantly share code, notes, and snippets.

@anhedonix
Created October 7, 2024 21:38
Show Gist options
  • Save anhedonix/9a93d320d7ed239d1acc9cf7b708901c to your computer and use it in GitHub Desktop.
Save anhedonix/9a93d320d7ed239d1acc9cf7b708901c to your computer and use it in GitHub Desktop.
Fragment shaders detailed explanation
#version 300 es
precision highp float;

// Input variables
in vec3 v_position;  // The position of the current fragment in world space
in vec3 v_normal;    // The normal vector of the current fragment
in vec2 v_texcoord;  // The texture coordinates of the current fragment

// Technical: These are interpolated values passed from the vertex shader
// ELI5: Imagine these as little notes passed to each tiny dot on your screen, telling it where it is and which way it's facing

// Output variable
out vec4 fragColor;  // The final color of the fragment

// Technical: This is the color we'll calculate and output for this pixel
// ELI5: This is like choosing the final crayon color for each dot in our picture

// Material properties
uniform vec3 u_albedo;    // The base color of the material
uniform float u_metallic; // How metallic the material is (0 to 1)
uniform float u_roughness; // How rough the material is (0 to 1)

// Technical: These define the core properties of our material for PBR calculations
// ELI5: These tell us what the object is made of - its color, if it's like metal, and how smooth or bumpy it is

// Light properties
uniform vec3 u_lightPosition; // The position of the light in world space
uniform vec3 u_lightColor;    // The color of the light

// Technical: These define our light source for illumination calculations
// ELI5: This is like saying where we put our lamp and what color it glows

// Camera position
uniform vec3 u_viewPosition;  // The position of the camera in world space

// Technical: This is used to calculate view direction for specular reflections
// ELI5: This tells us where we're looking from, like where our eyes are in the scene

// Constants
const float PI = 3.14159265359;

// Technical: Mathematical constant used in various calculations
// ELI5: This is a special number that helps us do math with circles and roundness

// Function to calculate the distribution of microfacets (GGX/Trowbridge-Reitz)
float DistributionGGX(vec3 N, vec3 H, float roughness) {
    // Technical: This function models how light scatters on a microscopically rough surface
    // ELI5: This helps us figure out how light bounces off tiny bumps we can't see

    float a = roughness * roughness;
    float a2 = a * a;
    float NdotH = max(dot(N, H), 0.0);
    float NdotH2 = NdotH * NdotH;

    // Technical: We're calculating the probability of microfacets being aligned to reflect light towards the viewer
    // ELI5: We're guessing how many tiny mirrors on the surface are pointing the right way to shine light at us

    float nom   = a2;
    float denom = (NdotH2 * (a2 - 1.0) + 1.0);
    denom = PI * denom * denom;

    return nom / max(denom, 0.0000001);
    // Technical: The result is the relative surface area of microfacets contributing to reflection
    // ELI5: This tells us how much of the bumpy surface is helping to make things look shiny
}

// Function to calculate geometric occlusion (Smith's Schlick-GGX)
float GeometrySchlickGGX(float NdotV, float roughness) {
    // Technical: This function models how microfacets shadow and mask each other
    // ELI5: This helps us understand how tiny bumps might block light from reaching other bumps

    float r = (roughness + 1.0);
    float k = (r * r) / 8.0;

    float nom   = NdotV;
    float denom = NdotV * (1.0 - k) + k;

    return nom / denom;
    // Technical: The result is the proportion of microfacets that are not shadowed or masked
    // ELI5: This tells us how much of the surface we can actually see, considering all the tiny hills and valleys
}

float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) {
    // Technical: This combines geometry terms for both view and light directions
    // ELI5: This looks at how bumps affect light coming in AND going out

    float NdotV = max(dot(N, V), 0.0);
    float NdotL = max(dot(N, L), 0.0);
    float ggx2 = GeometrySchlickGGX(NdotV, roughness);
    float ggx1 = GeometrySchlickGGX(NdotL, roughness);

    return ggx1 * ggx2;
    // Technical: The combined geometry term for the BRDF
    // ELI5: This gives us one number that tells us how much the bumpiness affects the overall shininess
}

// Function to calculate the Fresnel effect (Schlick approximation)
vec3 fresnelSchlick(float cosTheta, vec3 F0) {
    // Technical: This approximates how reflectivity changes with viewing angle
    // ELI5: This helps us see how the shininess changes when you look at something from different angles

    return F0 + (1.0 - F0) * pow(max(1.0 - cosTheta, 0.0), 5.0);
    // Technical: Interpolates between base reflectivity and full reflection based on view angle
    // ELI5: This decides how mirror-like the surface looks depending on how you're looking at it
}

void main() {
    // Normalize vectors
    vec3 N = normalize(v_normal);
    vec3 V = normalize(u_viewPosition - v_position);
    vec3 L = normalize(u_lightPosition - v_position);
    vec3 H = normalize(V + L);

    // Technical: Ensuring all direction vectors have unit length for correct calculations
    // ELI5: We're making sure all our arrows pointing in different directions are the same size

    // Calculate reflectance at normal incidence
    vec3 F0 = vec3(0.04); 
    F0 = mix(F0, u_albedo, u_metallic);

    // Technical: Sets base reflectivity, interpolating between dielectric and metallic
    // ELI5: This decides how shiny the surface is when you look straight at it, based on if it's metal or not

    // Calculate radiance
    float distance = length(u_lightPosition - v_position);
    float attenuation = 1.0 / (distance * distance);
    vec3 radiance = u_lightColor * attenuation;

    // Technical: Computes incoming light intensity considering distance falloff
    // ELI5: This figures out how bright the light is when it reaches our surface, knowing it gets dimmer farther away

    // Calculate Cook-Torrance BRDF
    float NDF = DistributionGGX(N, H, u_roughness);   
    float G   = GeometrySmith(N, V, L, u_roughness);      
    vec3 F    = fresnelSchlick(max(dot(H, V), 0.0), F0);

    // Technical: Combines microfacet distribution, geometry, and Fresnel terms
    // ELI5: We're putting together all our information about bumpiness, shadowing, and shininess

    vec3 nominator    = NDF * G * F; 
    float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0);
    vec3 specular = nominator / max(denominator, 0.001);
    
    // Technical: Computes the specular BRDF term
    // ELI5: This calculates how much light bounces off in a mirror-like way

    // Calculate the contribution of diffuse and specular to the final color
    vec3 kS = F;
    vec3 kD = vec3(1.0) - kS;
    kD *= 1.0 - u_metallic;

    // Technical: Balances between specular and diffuse reflection based on Fresnel and metallicness
    // ELI5: This decides how much light bounces off directly and how much scatters inside before coming out

    float NdotL = max(dot(N, L), 0.0);        

    // Combine diffuse and specular lighting
    vec3 Lo = (kD * u_albedo / PI + specular) * radiance * NdotL;

    // Technical: Combines diffuse and specular components with incoming light
    // ELI5: We're mixing the scattered light and the mirror-like reflections based on how much light is hitting the surface

    // Add ambient lighting
    vec3 ambient = vec3(0.03) * u_albedo;
    
    vec3 color = ambient + Lo;

    // Technical: Adds a simple ambient term to approximate global illumination
    // ELI5: We're adding a little bit of light everywhere to fake the bouncing of light in the real world

    // Tone mapping and gamma correction
    color = color / (color + vec3(1.0));
    color = pow(color, vec3(1.0/2.2)); 

    // Technical: Applies HDR tone mapping and gamma correction for display
    // ELI5: We're adjusting the colors so they look right on your screen, not too bright or too dark

    fragColor = vec4(color, 1.0);
    // Technical: Sets the final output color with full opacity
    // ELI5: We're putting our final crayon color onto the paper, making sure it's not see-through
}
@anhedonix
Copy link
Author

#version 300 es
precision highp float;

// ELI5: This is like telling the computer we want to use its best crayons for our drawing.

// Input variables
in vec3 v_position;
in vec3 v_normal;
in vec2 v_texcoord;

// ELI5: These are like special notes for each tiny dot on our screen.
// v_position is like saying where the dot is in our 3D world, using three numbers (imagine X, Y, Z in a game).
// v_normal is like an arrow saying which way the dot is facing.
// v_texcoord is like coordinates on a flat map, helping us put the right picture on our 3D shape.

// Output variable
out vec4 fragColor;

// ELI5: This is the color we'll choose for each dot. It uses four numbers: 
// how much red, green, blue, and how see-through it is.

// Material properties
uniform vec3 u_albedo;
uniform float u_metallic;
uniform float u_roughness;

// ELI5: These tell us what our object is made of.
// u_albedo is the main color, like "red" or "blue" but with three numbers for the computer.
// u_metallic is how much like metal it is, from 0 (not metal) to 1 (very metal).
// u_roughness is how bumpy it is, from 0 (super smooth) to 1 (very rough).
// "float" just means it's a single number that can have decimal points.

// Light properties
uniform vec3 u_lightPosition;
uniform vec3 u_lightColor;

// ELI5: This is about our pretend light bulb.
// u_lightPosition says where our light bulb is in our 3D world.
// u_lightColor is what color the light is, again with three numbers.

// Camera position
uniform vec3 u_viewPosition;

// ELI5: This is where we're looking from, like where our eyes are in the 3D world.

// Constants
const float PI = 3.14159265359;

// ELI5: PI is a special number that helps us with circular things. 
// It's about how many times a wheel's edge would fit around the middle.

// Function to calculate the distribution of microfacets
float DistributionGGX(vec3 N, vec3 H, float roughness) {
    // ELI5: This function helps us figure out how light bounces off tiny bumps we can't see.
    // It's like guessing how many tiny mirrors are pointing the right way on our surface.
    // Don't worry about the math inside - it's just a way to count these imaginary tiny mirrors.

    float a = roughness * roughness;
    float a2 = a * a;
    float NdotH = max(dot(N, H), 0.0);
    float NdotH2 = NdotH * NdotH;

    float nom   = a2;
    float denom = (NdotH2 * (a2 - 1.0) + 1.0);
    denom = PI * denom * denom;

    return nom / max(denom, 0.0000001);
}

// Function to calculate geometric occlusion
float GeometrySchlickGGX(float NdotV, float roughness) {
    // ELI5: This function helps us understand how tiny bumps might block light.
    // Imagine tiny hills on our surface - some might cast shadows on others.
    // This math helps us guess how much of our surface is in these tiny shadows.

    float r = (roughness + 1.0);
    float k = (r * r) / 8.0;

    float nom   = NdotV;
    float denom = NdotV * (1.0 - k) + k;

    return nom / denom;
}

float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) {
    // ELI5: This combines two ways of looking at our tiny hills:
    // How they block light coming in, and how they block light bouncing back to our eyes.

    float NdotV = max(dot(N, V), 0.0);
    float NdotL = max(dot(N, L), 0.0);
    float ggx2 = GeometrySchlickGGX(NdotV, roughness);
    float ggx1 = GeometrySchlickGGX(NdotL, roughness);

    return ggx1 * ggx2;
}

// Function to calculate the Fresnel effect
vec3 fresnelSchlick(float cosTheta, vec3 F0) {
    // ELI5: This helps us see how shiny things look different when you view them from different angles.
    // Like how a lake looks more reflective when you look at it from the side.

    return F0 + (1.0 - F0) * pow(max(1.0 - cosTheta, 0.0), 5.0);
}

void main() {
    // ELI5: This is where we do all our coloring for each tiny dot on the screen.

    // Normalize vectors
    vec3 N = normalize(v_normal);
    vec3 V = normalize(u_viewPosition - v_position);
    vec3 L = normalize(u_lightPosition - v_position);
    vec3 H = normalize(V + L);

    // ELI5: We're making sure all our direction arrows are the same length.
    // It's like making sure all our measuring sticks are the same size before we start measuring.

    // Calculate reflectance at normal incidence
    vec3 F0 = vec3(0.04); 
    F0 = mix(F0, u_albedo, u_metallic);

    // ELI5: This is figuring out how shiny our surface is when you look straight at it.
    // It changes based on whether we're dealing with metal or not.

    // Calculate radiance
    float distance = length(u_lightPosition - v_position);
    float attenuation = 1.0 / (distance * distance);
    vec3 radiance = u_lightColor * attenuation;

    // ELI5: We're figuring out how bright our light is when it reaches our dot.
    // The further away the light is, the dimmer it gets.

    // Calculate Cook-Torrance BRDF
    float NDF = DistributionGGX(N, H, u_roughness);   
    float G   = GeometrySmith(N, V, L, u_roughness);      
    vec3 F    = fresnelSchlick(max(dot(H, V), 0.0), F0);

    // ELI5: This is where we use all our special functions to figure out how light bounces.
    // We're combining information about bumpiness, tiny shadows, and shininess.

    vec3 nominator    = NDF * G * F; 
    float denominator = 4.0 * max(dot(N, V), 0.0) * max(dot(N, L), 0.0);
    vec3 specular = nominator / max(denominator, 0.001);
    
    // ELI5: This math gives us the amount of light that bounces off like a mirror.

    // Calculate the contribution of diffuse and specular
    vec3 kS = F;
    vec3 kD = vec3(1.0) - kS;
    kD *= 1.0 - u_metallic;

    // ELI5: We're deciding how much light bounces off directly (like a mirror) 
    // and how much scatters inside before coming out (like through a leaf).

    float NdotL = max(dot(N, L), 0.0);        

    // Combine diffuse and specular lighting
    vec3 Lo = (kD * u_albedo / PI + specular) * radiance * NdotL;

    // ELI5: We're mixing our scattered light and mirror-like reflections 
    // based on how much light is hitting our dot.

    // Add ambient lighting
    vec3 ambient = vec3(0.03) * u_albedo;
    
    vec3 color = ambient + Lo;

    // ELI5: We're adding a little bit of light everywhere, 
    // like the soft glow you see on a cloudy day.

    // Tone mapping and gamma correction
    color = color / (color + vec3(1.0));
    color = pow(color, vec3(1.0/2.2)); 

    // ELI5: We're adjusting our colors so they look right on a computer screen.
    // It's like making sure our painting looks good in different kinds of light.

    fragColor = vec4(color, 1.0);

    // ELI5: Finally, we're setting our dot's color, making sure it's not see-through.
}

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