18
0
mirror of https://github.com/MaSzyna-EU07/maszyna.git synced 2026-11-27 21:45:16 +01:00
Files
maszyna/shaders/light_common.glsl
maj00r 571487612b fix(render): old assets drawn as 26.05 drew them; the headlight beam spread sideways (#481)
* fix(render): old assets drawn as 26.05 drew them: metal, sun highlight, tonemapping, sun scale, diffuse colour

The shader changes since 26.05.2 were made for PBR-authored assets; the assets in the game
data were tuned for 26.05, and none of them is authored for the new combine.

- Metal keeps its diffuse term as far as its reflection mask is low (metal_diffuse_loss =
  metalic * reflectivity). Assets marking metal in the specgloss with a low mask went
  almost black (the gold EN63A-031); a full mask is drawn as before.
- The direct sun highlight is tinted by the albedo again, for dielectrics too. Old assets
  tuned param_specular / specgloss R with that multiply; untinted, dark glossy plastic broke
  into white glints along edges (Impuls fronts) and speckles on cab desks (SA132).
- ACES instead of AgX: AgX with its look crushed the dark end, a night scene lost half its
  brightness and the ground beside the track went black.
- SUN_DIFFUSE_SCALE 2.5 again (1.5 dimmed the moon at night as well).
- The Diffuse colour of submodels and shapes scales the light as it is, as in 26.05, not
  raised to 2.2: that took a quarter off the default 0.8 of every scenery shape and more off
  the ~64 000 textured submodels with a darker Diffuse.

Checked on screenshots of 10 vehicles by day (Ultra preset) and from cabs at night against
the 26.05.2 shaders on the same executable. No game data changes.

* feat(render): the headlight beam spread sideways, gfx.headlights.beamwidth (default 1.7)

The projected beam texture lit the track and the ballast, and the ground beside them only
with its dark edge (24-45 against 116 on the ballast close ahead, nearly 0 further on), so at
night only the ballast showed. The beam is spread sideways around its middle by
gfx.headlights.beamwidth: at 1.7 the ground gets most of the light of the ballast, the
brightness along the track stays as it was. 1 draws the narrow beam of 26.05; range 1-4.

The value reaches the shaders as HEADLIGHT_BEAM_WIDTH, written with the classic locale so
that a decimal comma can't break the glsl; the shader validator compiles them with and
without the spread. The key is written to the log with the other settings.

* fix(render): the sunless specgloss shader combines metal as apply_lights does

* fix(render): an untextured submodel takes its linearised colour as the texture again, as 26.05 did

mat_colored.frag gave apply_lights() a white base, so the albedo of a Map: none submodel was its diffuse colour c,
where 26.05.2 drew c^2.2 * c. A dark grey came out tens of times lighter: on the road vehicles of pctga the tyres
(25-40 grey) 60-165x, the glass 23x, whole untextured cars (a4, golf, passat, ka, arosa) 1.5-3x. With the
linearised colour as the texture a grey matches 26.05 in the ambient and the sun; a saturated colour is up to
a third darker in the sun, as 26.05 scaled the sun by the value of the colour, not by the colour.

* fix(render): the sun highlight is tinted by the texture alone, as 26.05 drew it
2026-11-24 19:44:46 +01:00

412 lines
20 KiB
GLSL
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#if SHADOWMAP_ENABLED
in vec4 f_light_pos[MAX_CASCADES];
uniform sampler2DArrayShadow shadowmap;
#endif
uniform sampler2D headlightmap;
#include <envmapping.glsl>
#include <conversion.glsl>
float glossiness = 1.0;
float metalic = 0.0;
in vec4 UserData;
// a slot of its own, the shaders of the materials using all of param[2]: how weathered the steel is as far as the userdata of
// its vertices says; below 0: the texture tinted to the colour of tint as far instead
#param (weathering, 3, 3, 1, zero)
#param (tint, 3, 0, 3, one)
// ---------------------------------------------------------------------
// Lighting balance tunables - tweak these to control overall scene
// exposure without touching tonemapping.glsl.
//
// AMBIENT_SCALE: brightness of SHADED faces (indirect/sky term).
// Lower -> deeper shadows, less burn under bright
// textures. Higher -> flatter / brighter shading.
//
// SUN_DIFFUSE_SCALE: brightness of UNSHADED (sun-lit) faces. Lower
// this to dim hot surfaces in direct sunlight
// without affecting shaded areas. Was 3.5; 2.5
// calmly fits the ACES tonemap shoulder.
//
// SUN_NDOTL_SHARPNESS: N.L curve on the sun. 1.0 = pure Lambert, higher
// = sharper terminator (more contrast between
// lit and shaded faces of the same surface).
// ---------------------------------------------------------------------
const float AMBIENT_SCALE = 0.65;
const float SUN_DIFFUSE_SCALE = 2.5; // 26.05; at 1.5 the moon left the night black around the headlights
const float SUN_NDOTL_SHARPNESS = 1.25;
float length2(vec3 v)
{
return dot(v, v);
}
float calc_shadow()
{
#if SHADOWMAP_ENABLED
float distance = dot(f_pos.xyz, f_pos.xyz);
uint cascade;
for (cascade = 0U; cascade < MAX_CASCADES; cascade++)
if (distance <= cascade_end[cascade])
break;
float dist_casc = distance / cascade_end[cascade];
// Normal offset: sample the shadow map from a point pushed along the surface normal
// by a fraction of the cascade's texel footprint. A constant depth bias can't keep up
// with large texels (far cascades, small shadow maps) on surfaces at a grazing angle
// to the sun, which then show shadow acne stripes. lightview maps view space metres
// to [0,1] shadow map coordinates, so its x/y row lengths give texels per metre.
vec3 shadownormal = normalize(f_normal);
float shadowNdotL = clamp(dot(shadownormal, normalize(-lights[0].dir)), 0.0, 1.0);
mat4 shadowview = lightview[cascade];
float texelspermetre = min(length(vec3(shadowview[0][0], shadowview[1][0], shadowview[2][0])),
length(vec3(shadowview[0][1], shadowview[1][1], shadowview[2][1]))) * float(textureSize(shadowmap, 0).x);
float texelsize = 1.0 / texelspermetre;
vec3 shadowpos = f_pos.xyz + shadownormal * (texelsize * 1.5 * (1.0 - shadowNdotL));
vec4 lightpos = shadowview * vec4(shadowpos, 1.0);
vec3 coords = lightpos.xyz / lightpos.w;
if (coords.z < 0.0)
return 0.0f;
float bias = 0.00005f * float(cascade + 1U);
vec2 texel = vec2(1.0) / vec2(textureSize(shadowmap, 0));
//float radius = 1.0; f_light_pos[cascade].w; //0.5 + 2.0 * max(abs(2.0 * coords.x - 1.0), abs(2.0 * coords.y - 1.0));
float radius = 1.0;
float minradius = 0.0;
if (cascade == 0U)
minradius = 1.0;
if (cascade < MAX_CASCADES - 1U)
radius = mix(minradius, f_light_pos[cascade+1U].w/f_light_pos[cascade].w, dist_casc);
else
radius = 0.5;
#if defined(GL_ARB_gpu_shader5) || defined(GL_EXT_gpu_shader5) || __VERSION__ >= 400
// Fast path: 4 textureGather() calls cover a 4x4 texel block. Raw gathered
// comparisons must be weighted by the sub-texel position (bilinear weights),
// otherwise the result is constant across each shadow map texel and shadow
// edges turn into texel-sized stair steps. With per-axis weights
// (1-f, 1, 1, f) this equals a 3x3 grid of hardware bilinear PCF taps.
vec2 size = vec2(textureSize(shadowmap, 0).xy);
vec2 uv = coords.xy * size - 0.5;
vec2 base = floor(uv);
vec2 f = uv - base;
float refz = coords.z + bias;
float layer = float(cascade);
// sampling at texel corners selects blocks with lower-left texel base-1 and base+1
vec4 g00 = textureGather(shadowmap, vec3((base + vec2(0.0, 0.0)) / size, layer), refz);
vec4 g10 = textureGather(shadowmap, vec3((base + vec2(2.0, 0.0)) / size, layer), refz);
vec4 g01 = textureGather(shadowmap, vec3((base + vec2(0.0, 2.0)) / size, layer), refz);
vec4 g11 = textureGather(shadowmap, vec3((base + vec2(2.0, 2.0)) / size, layer), refz);
// gather component order: x=(0,1) y=(1,1) z=(1,0) w=(0,0)
float shadow = dot(g00, vec4(1.0 - f.x, 1.0, 1.0 - f.y, (1.0 - f.x) * (1.0 - f.y)))
+ dot(g10, vec4(1.0, f.x, f.x * (1.0 - f.y), 1.0 - f.y))
+ dot(g01, vec4((1.0 - f.x) * f.y, f.y, 1.0, 1.0 - f.x))
+ dot(g11, vec4(f.y, f.x * f.y, f.x, 1.0));
return shadow / 9.0;
#else
// Fallback for drivers without textureGather on shadow samplers
// (notably GLES 3.0 and any 3.3 desktop driver that doesn't expose
// GL_ARB_texture_gather). Identical to the previous implementation.
float shadow = 0.0;
for (float y = -1.5; y <= 1.5; y += 1.0)
for (float x = -1.5; x <= 1.5; x += 1.0)
shadow += texture(shadowmap, vec4(coords.xy + vec2(x, y) * radius * texel, cascade, coords.z + bias) );
shadow /= 16.0;
return shadow;
#endif
#else
return 0.0;
#endif
}
// -----------------------------------------------------------------------
// GGX Microfacet BRDF helpers (Cook-Torrance)
// -----------------------------------------------------------------------
// Trowbridge-Reitz (GGX) Normal Distribution Function
// D(N,H,α) = α⁴ / (π · ((NdotH)²·(α⁴−1)+1)²)
// α = roughness² (perceptual remapping so the slider feels linear)
float D_GGX(float NdotH, float roughness)
{
float a = roughness * roughness; // perceptual -> linear roughness
float a2 = a * a;
float d = (NdotH * NdotH) * (a2 - 1.0) + 1.0;
return a2 / (3.14159265359 * d * d);
}
// Schlick-GGX single-term masking/shadowing (k remapped for direct lighting)
float G_SchlickGGX(float NdotX, float roughness)
{
float r = roughness + 1.0;
float k = (r * r) * (1.0 / 8.0); // k_direct = (roughness+1)²/8
return NdotX / (NdotX * (1.0 - k) + k);
}
// Height-correlated Smith geometry term
// G(N,V,L) = G_SchlickGGX(NdotV) · G_SchlickGGX(NdotL)
float G_Smith(float NdotV, float NdotL, float roughness)
{
return G_SchlickGGX(NdotV, roughness) * G_SchlickGGX(NdotL, roughness);
}
// Returns vec2(diffuse, specular) for a single punctual light.
//
// diffuse – Lambert N·L (Fresnel-weighted diffuse is handled per-material
// in apply_lights, so we return raw N·L here).
// specular – Cook-Torrance GGX: D·G / (4·NdotL·NdotV).
// The Fresnel factor (F) is intentionally omitted here;
// apply_lights already carries a per-material Fresnel term
// that is applied to env reflections and can be routed to
// direct specular there.
//
// Roughness is derived identically to env_roughness in apply_lights so
// that direct and indirect specular highlights read consistently.
vec2 calc_light(vec3 light_dir, vec3 fragnormal)
{
vec3 N = fragnormal;
vec3 L = light_dir;
vec3 V = normalize(-f_pos.xyz);
vec3 H = normalize(L + V);
float NdotL = max(dot(N, L), 0.0);
float NdotV = max(dot(N, V), 1e-4);
float NdotH = max(dot(N, H), 0.0);
float diffuse_v = NdotL;
// Mirror the env-map roughness derivation so direct and indirect lobes match.
// glossiness == param[1].w → roughness == 0.04 (near-mirror)
// glossiness == 0 → roughness == 1.0 (fully diffuse)
float roughness = clamp(1.0 - glossiness / max(abs(param[1].w), 1.0), 0.04, 1.0);
// Cook-Torrance specular (no Fresnel — see above):
// f_spec = D(N,H,α) · G(N,V,L,α) / (4 · NdotL · NdotV)
float D = D_GGX(NdotH, roughness);
float G = G_Smith(NdotV, NdotL, roughness);
float specular_v = (NdotL > 0.0)
? (D * G) / max(4.0 * NdotL * NdotV, 1e-4)
: 0.0;
return vec2(diffuse_v, specular_v);
}
vec2 calc_point_light(light_s light, vec3 fragnormal)
{
vec3 light_dir = normalize(light.pos - f_pos.xyz);
vec2 val = calc_light(light_dir, fragnormal);
val.x += light.ambient;
val *= light.intensity;
float distance = length(light.pos - f_pos.xyz);
float atten = 1.0f / (distance * distance);
//float atten = 1.0f / (1.0f + light.linear * distance + light.quadratic * (distance * distance));
return val * atten;
}
vec2 calc_spot_light(light_s light, vec3 fragnormal)
{
vec3 light_dir = normalize(light.pos - f_pos.xyz);
float theta = dot(light_dir, normalize(-light.dir));
float epsilon = light.in_cutoff - light.out_cutoff;
float intensity = clamp((theta - light.out_cutoff) / epsilon, 0.0, 1.0);
vec2 point = calc_point_light(light, fragnormal);
return point * intensity;
}
vec2 calc_dir_light(light_s light, vec3 fragnormal)
{
vec3 light_dir = normalize(-light.dir);
return calc_light(light_dir, fragnormal);
}
vec2 calc_headlights(light_s light, vec3 fragnormal)
{
vec4 headlightpos = light.headlight_projection * f_pos;
vec3 coords = headlightpos.xyz / headlightpos.w;
if (coords.z > 1.0)
return vec2(0.0);
if (coords.z < 0.0)
return vec2(0.0);
vec3 light_dir = normalize(light.pos - f_pos.xyz);
// Tighter wrap (was +0.25): faces angled away from the headlight cone
// fall off to dark much faster, so cab/exterior surfaces read with a
// clear directional shape instead of a flat half-lit wash.
vec2 part = vec2(1.0) * clamp(dot(fragnormal, light_dir) + 0.10, 0.0, 1.0);
float distance = length(light.pos - f_pos.xyz);
float atten = 1.0f / (1.0f + light.linear * distance + light.quadratic * (distance * distance));
atten *= mix(1.0, 0.0, clamp((coords.z - 0.998) * 500.0, 0.0, 1.0));
// gfx.headlights.beamwidth spreads the beam sideways around its middle (0.5 of the projected x), so the
// ground beside the track gets the light of the ballast; the brightness along the track stays as it was
vec4 beampos = headlightpos;
#ifdef HEADLIGHT_BEAM_WIDTH
beampos.x = 0.5 * beampos.w + (beampos.x - 0.5 * beampos.w) / HEADLIGHT_BEAM_WIDTH;
#endif
vec3 lights = textureProj(headlightmap, beampos).rgb * light.headlight_weights.rgb;
float lightintensity = max(max(lights.r, lights.g), lights.b);
return part * atten * lightintensity;
}
// -----------------------------------------------------------------------
// Split-sum environment BRDF (Karis / UE4 analytic approximation).
//
// This is the missing piece that made matte specgloss surfaces "shine like
// crazy": previously the env reflection was added at full strength
// (envcolor * fresnel * reflectivity) and roughness only blurred the mip,
// never dimmed the energy. A rough surface therefore mirrored the bright
// sky just as strongly as a polished one.
//
// EnvBRDFApprox returns the pre-integrated specular scale (the "DFG" term)
// for a given F0, roughness and view angle. For rough surfaces it collapses
// toward ~0, so low-glossiness materials reflect almost nothing — matching
// what Substance 3D Painter shows. Polished surfaces keep their full
// reflection, and the grazing-angle Fresnel edge is preserved.
// roughness 1.0 (matte) -> scale ~0.015 (virtually no reflection)
// roughness 0.0 (mirror) -> scale ~F0..1 (full reflection + Fresnel rim)
vec3 EnvBRDFApprox(vec3 F0, float roughness, float NoV)
{
const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);
const vec4 c1 = vec4( 1.0, 0.0425, 1.040, -0.040);
vec4 r = roughness * c0 + c1;
float a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;
vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;
return F0 * AB.x + AB.y;
}
// Diffuse colour of the submodel (t3d/e3d) or shape, used as the albedo multiplier:
// untextured materials take it as their colour, textured ones multiply the base texture by it
// (same as the legacy renderer's GL_MODULATE). param[0].rgb holds the authored sRGB colour,
// param[1].x its intensity (HSV value unless a material overrides it).
vec3 material_diffuse()
{
// the colour as it is, as 26.05 scaled the light by it; linearised (^2.2) it took a quarter off the default
// 0.8 of every scenery shape and more off darker submodels, and the night went black
vec3 diffusecolor = max(param[0].rgb, vec3(0.0));
float value = max(param[0].r, max(param[0].g, param[0].b));
return (value > 0.0 ? diffusecolor * (param[1].x / value) : vec3(0.0));
}
// [0] - diffuse, [1] - specular
// do magic here
vec3 apply_lights(vec3 fragcolor, vec3 fragnormal, vec3 texturecolor, float reflectivity, float specularity, float shadowtone)
{
// the sun highlight is tinted by the texture alone, as 26.05 drew it, not by the diffuse colour too
vec3 highlight_tint = texturecolor;
// Diffuse colour is applied once, to the albedo; the light terms below are not scaled by it again
texturecolor *= material_diffuse();
float weathered = (param[3].w > 0.0 ? clamp(param[3].w * UserData.x, 0.0, 1.0) : 0.0);
float tinted = (param[3].w < 0.0 ? clamp(-param[3].w * UserData.x, 0.0, 1.0) : 0.0);
// a tint only scales the colour of the texture, the steel keeps its own polish
float polished = weathered * smoothstep(0.03, 0.12, dot(texturecolor, vec3(0.2126, 0.7152, 0.0722)));
float weatheredluma = min(dot(texturecolor, vec3(0.2126, 0.7152, 0.0722)), 0.05);
vec3 unused = texturecolor * (weatheredluma / max(dot(texturecolor, vec3(0.2126, 0.7152, 0.0722)), 1e-4));
unused = mix(unused, vec3(1.0, 0.82, 0.74) * (weatheredluma / 0.8525), 0.5);
texturecolor = mix(texturecolor, unused, smoothstep(0.0, 0.4, weathered));
texturecolor = (tinted > 0.0 ? texturecolor * mix(vec3(1.0), param[3].rgb, tinted) : texturecolor);
specularity = mix(specularity, min(specularity, 0.03), smoothstep(0.0, 0.4, polished));
metalic = mix(metalic, 0.0, polished);
glossiness = mix(glossiness, min(glossiness, 0.06 * abs(param[1].w)), polished);
reflectivity = mix(reflectivity, min(reflectivity, 0.08 * param[1].z), smoothstep(0.0, 0.4, polished));
// Scale ambient before it gets tinted by the texture.
// Sun, headlights and emission are added afterwards so they are NOT
// attenuated by AMBIENT_SCALE - this only dims the indirect term.
fragcolor *= AMBIENT_SCALE;
vec3 emissioncolor = vec3(emission);
vec3 view_dir = normalize(-f_pos.xyz);
float NdotV = max(dot(fragnormal, view_dir), 0.0);
vec3 F0 = mix(vec3(0.04), texturecolor, metalic);
// A metal gives up its diffuse term only as far as its reflection mask lets the environment take its place.
// Assets made before the metal/rough combine mark metal in the specgloss but keep a low mask, and without
// this their metal parts went almost black; a metal with the full mask is drawn as before.
float metal_diffuse_loss = metalic * clamp(reflectivity, 0.0, 1.0);
vec3 fresnel = F0 + (1.0 - F0) * pow(1.0 - NdotV, 5.0);
const float MAX_REFLECTION_LOD = 8.0;
float env_roughness = 1.0 - clamp(glossiness / max(abs(param[1].w), 1.0), 0.0, 1.0);
vec3 envcolor = envmap_color_lod(fragnormal, env_roughness * MAX_REFLECTION_LOD);
// Pre-integrated env BRDF: roughness/F0/view-dependent specular scale.
// Replaces the old raw `fresnel` weighting so matte surfaces stop
// mirroring the sky. `env_spec` is the colour to multiply the cubemap by.
vec3 env_spec = EnvBRDFApprox(F0, env_roughness, NdotV);
float env_spec_w = max(env_spec.r, max(env_spec.g, env_spec.b));
// Tint texture toward fully-saturated under strong env, weighted by the
// env BRDF (so a rough/matte surface no longer gets washed toward env hue)
vec3 texturecoloryuv = rgb2yuv(texturecolor);
vec3 texturecolorfullv = yuv2rgb(vec3(0.2176, texturecoloryuv.gb));
vec3 envyuv = rgb2yuv(envcolor);
texturecolor = mix(texturecolor, texturecolorfullv, envyuv.r * reflectivity * env_spec_w);
if (lights_count == 0U)
// Metals carry no diffuse term where they reflect; env reflection is gated by the env BRDF
// (F0-tinted, roughness-attenuated) so matte surfaces barely reflect.
return fragcolor * texturecolor * (1.0 - metal_diffuse_loss)
+ emissioncolor * texturecolor
+ envcolor * env_spec * reflectivity;
vec2 sunlight = calc_dir_light(lights[0], fragnormal);
// Sharpen sun N.L falloff so the lit-to-shaded terminator on cab
// panels, vehicle bodies and terrain reads as a clear edge rather
// than a soft Lambertian ramp. Tunable via SUN_NDOTL_SHARPNESS.
float sun_NdotL = pow(sunlight.x, SUN_NDOTL_SHARPNESS);
float diffuseamount = sun_NdotL * lights[0].intensity;
float shadow1 = 0.0;
if (shadowtone < 1.0)
shadow1 = (1.0 - shadowtone) * clamp(calc_shadow(), 0.0, 1.0);
// Sun HDR scale -> SUN_DIFFUSE_SCALE (default 2.5). Controls how
// bright sun-lit (unshaded) faces get. Lower this if surfaces in
// direct sun read as too hot/burnt; raise it for more punch.
fragcolor += lights[0].color * SUN_DIFFUSE_SCALE * (1.0 - shadow1) * diffuseamount;
for (uint i = 1U; i < lights_count; i++)
{
light_s light = lights[i];
vec2 part = calc_headlights(light, fragnormal);
fragcolor += light.color * (part.x + part.y * param[1].y) * light.intensity;
}
float specularamount = sunlight.y * param[1].y * specularity * lights[0].intensity
* clamp(1.0 - shadowtone, 0.0, 1.0);
if (shadowtone < 1.0)
specularamount *= clamp(1.0 - shadow1, 0.0, 1.0);
vec3 specularcolor = specularamount * lights[0].color;
// Env reflection tracked separately — must NOT go through the albedo multiply
// below. Gated by the pre-integrated env BRDF (env_spec) so reflection energy
// falls off with roughness; F0 inside env_spec already tints metals by albedo.
vec3 env_reflection = envcolor * env_spec * reflectivity * (1.0 - shadow1 * 0.5);
// --- Physically-based metal/rough combine (Substance 3D Painter parity) ---
// Dielectrics: keep the full diffuse albedo; the direct sun highlight is tinted
// by the albedo, as 26.05 drew it. The specular strength of the
// assets (param_specular, the specgloss R) was tuned with that
// multiply; an untinted highlight on dark glossy plastic of an old
// asset turned into white glints along edges and speckles on cab
// desks.
// Metals: drop the diffuse term where the reflection mask is full (see
// metal_diffuse_loss) and tint the direct highlight with the
// albedo (metal F0 == base colour).
// The highlight *strength* (specularamount) is deliberately left untouched so
// existing material tuning is preserved.
vec3 diffuse_albedo = texturecolor * (1.0 - metal_diffuse_loss);
vec3 spec_tint = highlight_tint;
vec3 result = fragcolor * diffuse_albedo // sun + ambient + headlight diffuse
+ specularcolor * spec_tint // direct sun highlight
+ emissioncolor * texturecolor // emissive glow (albedo-tinted, unchanged)
+ env_reflection; // env reflection (env_spec already F0-tinted)
return result;
}