From 4d276c9b986b111611b8396f94dae56dbe736387 Mon Sep 17 00:00:00 2001 From: Mikko Rasa Date: Sat, 9 Oct 2021 20:47:39 +0300 Subject: [PATCH] Some refactoring of light calculations in shaders --- shaderlib/common.glsl | 12 ++++++++++-- shaderlib/cooktorrance.glsl | 8 ++++---- shaderlib/phong.glsl | 10 +++++----- 3 files changed, 19 insertions(+), 11 deletions(-) diff --git a/shaderlib/common.glsl b/shaderlib/common.glsl index dde09c12..4d6112d9 100644 --- a/shaderlib/common.glsl +++ b/shaderlib/common.glsl @@ -71,6 +71,12 @@ void main() } #pragma MSP stage(fragment) +struct IncomingLight +{ + vec3 direction; + vec3 color; +}; + virtual vec3 get_fragment_normal() { if(use_normal_map) @@ -79,10 +85,12 @@ virtual vec3 get_fragment_normal() return normalize(world_normal); } -virtual vec3 get_light_direction(int index) +virtual IncomingLight get_incoming_light(int index, vec3 world_pos) { vec4 light_pos = light_sources[index].position; - return normalize(light_pos.xyz-world_vertex.xyz*light_pos.w); + vec3 rel_pos = light_pos.xyz-world_pos*light_pos.w; + float d = length(rel_pos); + return IncomingLight(rel_pos/d, light_sources[index].color); } virtual vec3 get_environment_sample(vec3 direction, float roughness) diff --git a/shaderlib/cooktorrance.glsl b/shaderlib/cooktorrance.glsl index f441a6d3..79f88f64 100644 --- a/shaderlib/cooktorrance.glsl +++ b/shaderlib/cooktorrance.glsl @@ -118,7 +118,7 @@ vec3 fresnel_schlick(vec3 halfway, vec3 look, vec3 base_color, float metalness) } /* Computes the full contribution of a single light */ -vec3 cooktorrance_one_light_direct(vec3 normal, vec3 look, vec3 light, vec3 light_color, vec3 base_color, float metalness, float roughness) +vec3 cooktorrance_one_light_direct(vec3 normal, vec3 look, vec3 light, vec3 base_color, float metalness, float roughness) { vec3 halfway = normalize(light-look); float ndist = normal_distribution_ggxtr(normal, halfway, roughness); @@ -128,7 +128,7 @@ vec3 cooktorrance_one_light_direct(vec3 normal, vec3 look, vec3 light, vec3 ligh vec3 k_diff = (1.0-k_spec)*(1.0-metalness); float spec_denom = max(4.0*max(dot(normal, -look), 0.0)*max(dot(normal, light), 0.0), 0.001); - return max(dot(normal, light), 0.0)*light_color*(k_diff*lambert_diffuse(base_color)+k_spec*ndist*geom/spec_denom); + return max(dot(normal, light), 0.0)*(k_diff*lambert_diffuse(base_color)+k_spec*ndist*geom/spec_denom); } vec3 cooktorrance_environment(vec3 normal, vec3 look, vec3 base_color, float metalness, float roughness) @@ -155,9 +155,9 @@ vec3 cooktorrance_lighting(vec3 normal, vec3 look, vec3 base_color, float metaln for(int i=0; i