diff options
| author | skal <pascal.massimino@gmail.com> | 2026-02-08 15:52:26 +0100 |
|---|---|---|
| committer | skal <pascal.massimino@gmail.com> | 2026-02-08 15:52:26 +0100 |
| commit | 8d3c540e097a659d7ac9b1594a0b00404002925f (patch) | |
| tree | a741a7d34b4af29c0c4afb125313a5089b0bcac2 /assets/final | |
| parent | 9339aff2360730df56690d2f2f69adff861fd8a6 (diff) | |
feat(shaders): Extract common WGSL utilities for better composability
Created math/common_utils.wgsl with reusable shader functions:
- transform_normal() - Normal matrix transform (2 call sites)
- spherical_uv() - Spherical UV mapping (7 call sites)
- spherical_uv_from_dir() - For direction vectors (1 call site)
- grid_pattern() - Procedural checkerboard (2 call sites)
- Constants: PI, TAU
Refactored shaders:
- renderer_3d.wgsl: 7 spherical_uv + 1 normal + 2 grid (~12 lines removed)
- mesh_render.wgsl: 1 normal transform (~3 lines removed)
- skybox.wgsl: 1 spherical UV (~2 lines removed)
Impact: ~200 bytes saved, 12 call sites deduplicated
Tests: 31/31 passing
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Diffstat (limited to 'assets/final')
| -rw-r--r-- | assets/final/shaders/math/common_utils.wgsl | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/assets/final/shaders/math/common_utils.wgsl b/assets/final/shaders/math/common_utils.wgsl new file mode 100644 index 0000000..7131216 --- /dev/null +++ b/assets/final/shaders/math/common_utils.wgsl @@ -0,0 +1,36 @@ +// Common utility functions for WGSL shaders. +// Reduces duplication across renderer_3d, mesh_render, etc. + +// Constants +const PI: f32 = 3.14159265359; +const TAU: f32 = 6.28318530718; + +// Transform normal from local to world space using inverse model matrix +fn transform_normal(inv_model: mat4x4<f32>, normal_local: vec3<f32>) -> vec3<f32> { + let normal_matrix = mat3x3<f32>(inv_model[0].xyz, inv_model[1].xyz, inv_model[2].xyz); + return normalize(normal_matrix * normal_local); +} + +// Spherical UV mapping (sphere or any radial surface) +// Returns UV in [0,1] range +fn spherical_uv(p: vec3<f32>) -> vec2<f32> { + let u = atan2(p.x, p.z) / TAU + 0.5; + let v = acos(clamp(p.y / length(p), -1.0, 1.0)) / PI; + return vec2<f32>(u, v); +} + +// Spherical UV from direction vector (for skybox, etc.) +fn spherical_uv_from_dir(dir: vec3<f32>) -> vec2<f32> { + let u = atan2(dir.z, dir.x) / TAU + 0.5; + let v = asin(clamp(dir.y, -1.0, 1.0)) / PI + 0.5; + return vec2<f32>(u, v); +} + +// Grid pattern for procedural texturing (checkerboard-like) +fn grid_pattern(uv: vec2<f32>) -> f32 { + let grid = 0.5 + 0.5 * sin(uv.x * PI) * sin(uv.y * PI); + return smoothstep(0.45, 0.55, grid); +} + +// NOTE: calc_sdf_normal_bumped() removed - too specialized, depends on get_dist() +// from scene_query snippets. Keep bump mapping code inline in shaders that use it. |
