diff options
Diffstat (limited to 'src/shaders')
31 files changed, 1188 insertions, 0 deletions
diff --git a/src/shaders/camera_common.wgsl b/src/shaders/camera_common.wgsl new file mode 100644 index 0000000..846d052 --- /dev/null +++ b/src/shaders/camera_common.wgsl @@ -0,0 +1,52 @@ +// Camera parameters and helpers for SDF raymarching effects + +struct CameraParams { + inv_view: mat4x4f, + fov: f32, + near_plane: f32, + far_plane: f32, + aspect_ratio: f32, +} + +struct Ray { + origin: vec3f, + direction: vec3f, +} + +// Generate camera ray for given UV coordinates (-1 to 1) +fn getCameraRay(cam: CameraParams, uv: vec2f) -> Ray { + let cam_pos = vec3f(cam.inv_view[3].x, cam.inv_view[3].y, cam.inv_view[3].z); + + // Compute ray direction from FOV and aspect ratio + let tan_fov = tan(cam.fov * 0.5); + let ndc = vec3f(uv.x * cam.aspect_ratio * tan_fov, uv.y * tan_fov, -1.0); + + // Transform direction by inverse view matrix (rotation only) + let dir = normalize( + cam.inv_view[0].xyz * ndc.x + + cam.inv_view[1].xyz * ndc.y + + cam.inv_view[2].xyz * ndc.z + ); + + return Ray(cam_pos, dir); +} + +// Extract camera position from inverse view matrix +fn getCameraPosition(cam: CameraParams) -> vec3f { + return vec3f(cam.inv_view[3].x, cam.inv_view[3].y, cam.inv_view[3].z); +} + +// Extract camera forward vector (view direction) +fn getCameraForward(cam: CameraParams) -> vec3f { + return -normalize(vec3f(cam.inv_view[2].x, cam.inv_view[2].y, cam.inv_view[2].z)); +} + +// Extract camera up vector +fn getCameraUp(cam: CameraParams) -> vec3f { + return normalize(vec3f(cam.inv_view[1].x, cam.inv_view[1].y, cam.inv_view[1].z)); +} + +// Extract camera right vector +fn getCameraRight(cam: CameraParams) -> vec3f { + return normalize(vec3f(cam.inv_view[0].x, cam.inv_view[0].y, cam.inv_view[0].z)); +} diff --git a/src/shaders/combined_postprocess.wgsl b/src/shaders/combined_postprocess.wgsl new file mode 100644 index 0000000..c0acfe7 --- /dev/null +++ b/src/shaders/combined_postprocess.wgsl @@ -0,0 +1,23 @@ +// Example: Combined post-process using inline functions +// Demonstrates how to chain multiple simple effects without separate classes + +#include "sequence_uniforms" +#include "postprocess_inline" +#include "render/fullscreen_uv_vs" // <- VertexOutput + vs_main + +@group(0) @binding(0) var input_sampler: sampler; +@group(0) @binding(1) var input_texture: texture_2d<f32>; +@group(0) @binding(2) var<uniform> uniforms: UniformsSequenceParams; + +@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4f { + // Sample base color + var color = textureSample(input_texture, input_sampler, in.uv); + + // Apply effects in sequence (customize as needed) + // color = apply_solarize(color, 0.4, 0.4, uniforms.time); + // color = apply_theme(color, vec3f(1.0, 0.8, 0.6), 0.3); + color = apply_vignette(color, in.uv, 0.6, 0.1, uniforms.audio_intensity); + // color = apply_flash(color, uniforms.beat_phase * 0.2); + + return color; +} diff --git a/src/shaders/common_uniforms.wgsl b/src/shaders/common_uniforms.wgsl new file mode 100644 index 0000000..5dc0251 --- /dev/null +++ b/src/shaders/common_uniforms.wgsl @@ -0,0 +1,25 @@ +struct CommonUniforms { + resolution: vec2f, // Screen dimensions + aspect_ratio: f32, // Width/height ratio + time: f32, // Physical time in seconds (unaffected by tempo) + beat_time: f32, // Musical time in beats (absolute, tempo-scaled) + beat_phase: f32, // Fractional beat (0.0-1.0 within current beat) + audio_intensity: f32, // Audio peak for beat sync + _pad: f32, // Padding +}; +struct GlobalUniforms { + view_proj: mat4x4f, + inv_view_proj: mat4x4f, + camera_pos_time: vec4f, + params: vec4f, + resolution: vec2f, +}; +struct ObjectData { + model: mat4x4f, + inv_model: mat4x4f, + color: vec4f, + params: vec4f, +}; +struct ObjectsBuffer { + objects: array<ObjectData>, +};
\ No newline at end of file diff --git a/src/shaders/compute/gen_blend.wgsl b/src/shaders/compute/gen_blend.wgsl new file mode 100644 index 0000000..c6be7bb --- /dev/null +++ b/src/shaders/compute/gen_blend.wgsl @@ -0,0 +1,29 @@ +// This file is part of the 64k demo project. +// GPU composite shader: Blend two textures. + +struct BlendParams { + width: u32, + height: u32, + blend_factor: f32, + _pad0: f32, +} + +@group(0) @binding(0) var output_tex: texture_storage_2d<rgba8unorm, write>; +@group(0) @binding(1) var<uniform> params: BlendParams; +@group(0) @binding(2) var input_a: texture_2d<f32>; +@group(0) @binding(3) var input_b: texture_2d<f32>; +@group(0) @binding(4) var tex_sampler: sampler; + +@compute @workgroup_size(8, 8, 1) +fn main(@builtin(global_invocation_id) id: vec3<u32>) { + if (id.x >= params.width || id.y >= params.height) { return; } + + let uv = vec2f(f32(id.x) / f32(params.width), + f32(id.y) / f32(params.height)); + + let color_a = textureSampleLevel(input_a, tex_sampler, uv, 0.0); + let color_b = textureSampleLevel(input_b, tex_sampler, uv, 0.0); + let blended = mix(color_a, color_b, params.blend_factor); + + textureStore(output_tex, id.xy, blended); +} diff --git a/src/shaders/compute/gen_grid.wgsl b/src/shaders/compute/gen_grid.wgsl new file mode 100644 index 0000000..4ce7ea3 --- /dev/null +++ b/src/shaders/compute/gen_grid.wgsl @@ -0,0 +1,24 @@ +// GPU procedural grid pattern generator. +// Simple grid lines with configurable spacing and thickness. + +struct GridParams { + width: u32, + height: u32, + grid_size: u32, + thickness: u32, +} + +@group(0) @binding(0) var output_tex: texture_storage_2d<rgba8unorm, write>; +@group(0) @binding(1) var<uniform> params: GridParams; + +@compute @workgroup_size(8, 8, 1) +fn main(@builtin(global_invocation_id) id: vec3<u32>) { + if (id.x >= params.width || id.y >= params.height) { return; } + + let on_line = (id.x % params.grid_size) < params.thickness || + (id.y % params.grid_size) < params.thickness; + + let val = select(0.0, 1.0, on_line); + + textureStore(output_tex, id.xy, vec4f(val, val, val, 1.0)); +} diff --git a/src/shaders/compute/gen_mask.wgsl b/src/shaders/compute/gen_mask.wgsl new file mode 100644 index 0000000..39f5b50 --- /dev/null +++ b/src/shaders/compute/gen_mask.wgsl @@ -0,0 +1,27 @@ +// This file is part of the 64k demo project. +// GPU composite shader: Multiply texture A by texture B (masking). + +struct MaskParams { + width: u32, + height: u32, +} + +@group(0) @binding(0) var output_tex: texture_storage_2d<rgba8unorm, write>; +@group(0) @binding(1) var<uniform> params: MaskParams; +@group(0) @binding(2) var input_a: texture_2d<f32>; +@group(0) @binding(3) var input_b: texture_2d<f32>; +@group(0) @binding(4) var tex_sampler: sampler; + +@compute @workgroup_size(8, 8, 1) +fn main(@builtin(global_invocation_id) id: vec3<u32>) { + if (id.x >= params.width || id.y >= params.height) { return; } + + let uv = vec2f(f32(id.x) / f32(params.width), + f32(id.y) / f32(params.height)); + + let color_a = textureSampleLevel(input_a, tex_sampler, uv, 0.0); + let mask_b = textureSampleLevel(input_b, tex_sampler, uv, 0.0); + let masked = color_a * mask_b; + + textureStore(output_tex, id.xy, masked); +} diff --git a/src/shaders/compute/gen_noise.wgsl b/src/shaders/compute/gen_noise.wgsl new file mode 100644 index 0000000..7b75f13 --- /dev/null +++ b/src/shaders/compute/gen_noise.wgsl @@ -0,0 +1,26 @@ +// GPU procedural noise texture generator. +// Uses compute shader for parallel texture generation. + +#include "math/noise" + +struct NoiseParams { + width: u32, + height: u32, + seed: f32, + frequency: f32, +} + +@group(0) @binding(0) var output_tex: texture_storage_2d<rgba8unorm, write>; +@group(0) @binding(1) var<uniform> params: NoiseParams; + +@compute @workgroup_size(8, 8, 1) +fn main(@builtin(global_invocation_id) id: vec3<u32>) { + if (id.x >= params.width || id.y >= params.height) { return; } + + let uv = vec2f(f32(id.x) / f32(params.width), + f32(id.y) / f32(params.height)); + let p = uv * params.frequency + params.seed; + let noise = noise_2d(p); + + textureStore(output_tex, id.xy, vec4f(noise, noise, noise, 1.0)); +} diff --git a/src/shaders/compute/gen_perlin.wgsl b/src/shaders/compute/gen_perlin.wgsl new file mode 100644 index 0000000..2807f6d --- /dev/null +++ b/src/shaders/compute/gen_perlin.wgsl @@ -0,0 +1,44 @@ +// GPU procedural Perlin noise texture generator. +// Fractional Brownian Motion using value noise. + +#include "math/noise" + +struct PerlinParams { + width: u32, + height: u32, + seed: f32, + frequency: f32, + amplitude: f32, + amplitude_decay: f32, + octaves: u32, + _pad0: f32, // Padding for alignment +} + +@group(0) @binding(0) var output_tex: texture_storage_2d<rgba8unorm, write>; +@group(0) @binding(1) var<uniform> params: PerlinParams; + +@compute @workgroup_size(8, 8, 1) +fn main(@builtin(global_invocation_id) id: vec3<u32>) { + if (id.x >= params.width || id.y >= params.height) { return; } + + let uv = vec2f(f32(id.x) / f32(params.width), + f32(id.y) / f32(params.height)); + + var value = 0.0; + var amplitude = params.amplitude; + var frequency = params.frequency; + var total_amp = 0.0; + + for (var o: u32 = 0u; o < params.octaves; o++) { + let p = uv * frequency + params.seed; + value += noise_2d(p) * amplitude; + total_amp += amplitude; + frequency *= 2.0; + amplitude *= params.amplitude_decay; + } + + value /= total_amp; + let clamped = clamp(value, 0.0, 1.0); + + textureStore(output_tex, id.xy, vec4f(clamped, clamped, clamped, 1.0)); +} diff --git a/src/shaders/gaussian_blur.wgsl b/src/shaders/gaussian_blur.wgsl new file mode 100644 index 0000000..7f85719 --- /dev/null +++ b/src/shaders/gaussian_blur.wgsl @@ -0,0 +1,32 @@ +// Gaussian blur shader for Sequence v2 +#include "sequence_uniforms" +#include "render/fullscreen_uv_vs" // <- VertexOutput + vs_main + +@group(0) @binding(0) var input_sampler: sampler; +@group(0) @binding(1) var input_texture: texture_2d<f32>; +@group(0) @binding(2) var<uniform> uniforms: UniformsSequenceParams; + +struct GaussianBlurParams { + direction: vec2f, + radius: f32, + _pad: f32, +}; +@group(0) @binding(3) var<uniform> params: GaussianBlurParams; + +@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4f { + let texel_size = 1.0 / uniforms.resolution; + let offset = params.direction * texel_size; + + var color = vec4f(0.0); + let kernel_size = i32(params.radius); + var weight_sum = 0.0; + + for (var i = -kernel_size; i <= kernel_size; i++) { + let sample_offset = f32(i) * offset; + let weight = exp(-f32(i * i) / (2.0 * params.radius * params.radius)); + color += textureSample(input_texture, input_sampler, in.uv + sample_offset) * weight; + weight_sum += weight; + } + + return color / weight_sum; +} diff --git a/src/shaders/heptagon.wgsl b/src/shaders/heptagon.wgsl new file mode 100644 index 0000000..a8a450f --- /dev/null +++ b/src/shaders/heptagon.wgsl @@ -0,0 +1,33 @@ +// Heptagon shader for Sequence v2 +#include "sequence_uniforms" +#include "render/fullscreen_uv_vs" // <- VertexOutput + vs_main + +// Standard v2 post-process layout (bindings 0,1 unused for scene effects) +@group(0) @binding(2) var<uniform> uniforms: UniformsSequenceParams; + +fn sdf_heptagon(p: vec2f, r: f32) -> f32 { + let an = 3.141593 / 7.0; // PI/7 for heptagon + let acs = vec2f(cos(an), sin(an)); + let bn = (atan2(p.x, p.y) % (2.0 * an)) - an; + let q = length(p) * vec2f(cos(bn), abs(sin(bn))); + return length(q - r * acs) * sign(q.x - r * acs.x); +} + +@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4f { + let aspect = uniforms.aspect_ratio; + let uv = (in.uv * 2.0 - 1.0) * vec2f(aspect, 1.0); + + let rotation = uniforms.beat_time * 0.5; + let c = cos(rotation); + let s = sin(rotation); + let rot_uv = vec2f( + uv.x * c - uv.y * s, + uv.x * s + uv.y * c + ); + + let dist = sdf_heptagon(rot_uv, 0.3); + let color = mix(vec3f(0.2, 0.4, 0.8), vec3f(1.0, 0.8, 0.2), + smoothstep(0.01, -0.01, dist)); + + return vec4f(color, 1.0); +} diff --git a/src/shaders/lighting.wgsl b/src/shaders/lighting.wgsl new file mode 100644 index 0000000..fd92c1a --- /dev/null +++ b/src/shaders/lighting.wgsl @@ -0,0 +1,24 @@ +fn get_normal_basic(p: vec3f, obj_params: vec4f) -> vec3f { + let obj_type = obj_params.x; + if (obj_type == 1.0) { return normalize(p); } + let e = vec2f(0.001, 0.0); + return normalize(vec3f( + get_dist(p + e.xyy, obj_params) - get_dist(p - e.xyy, obj_params), + get_dist(p + e.yxy, obj_params) - get_dist(p - e.yxy, obj_params), + get_dist(p + e.yyx, obj_params) - get_dist(p - e.yyx, obj_params) + )); +} + +fn calc_shadow(ro: vec3f, rd: vec3f, tmin: f32, tmax: f32, skip_idx: u32) -> f32 { + var res = 1.0; + var t = tmin; + if (t < 0.05) { t = 0.05; } + for (var i = 0; i < 32; i = i + 1) { + let h = map_scene(ro + rd * t, skip_idx); + if (h < 0.001) { return 0.0; } + res = min(res, 16.0 * h / t); + t = t + clamp(h, 0.02, 0.4); + if (t > tmax) { break; } + } + return clamp(res, 0.0, 1.0); +} diff --git a/src/shaders/math/color.wgsl b/src/shaders/math/color.wgsl new file mode 100644 index 0000000..9352053 --- /dev/null +++ b/src/shaders/math/color.wgsl @@ -0,0 +1,27 @@ +// Common color space and tone mapping functions. + +// sRGB to Linear approximation +// Note: Assumes input is in sRGB color space. +fn sRGB(t: vec3f) -> vec3f { + return mix(1.055 * pow(t, vec3f(1.0/2.4)) - 0.055, 12.92 * t, step(t, vec3f(0.0031308))); +} + +// ACES Filmic Tone Mapping (Approximate) +// A common tone mapping algorithm used in games and film. +fn aces_approx(v_in: vec3f) -> vec3f { + var v = max(v_in, vec3f(0.0)); + v *= 0.6; + let a = 2.51; + let b = 0.03; + let c = 2.43; + let d = 0.59; + let e = 0.14; + return clamp((v * (a * v + b)) / (v * (c * v + d) + e), vec3f(0.0), vec3f(1.0)); +} + +// HSV to RGB conversion +const hsv2rgb_K = vec4f(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); +fn hsv2rgb(c: vec3f) -> vec3f { + let p = abs(fract(c.xxx + hsv2rgb_K.xyz) * 6.0 - hsv2rgb_K.www); + return c.z * mix(hsv2rgb_K.xxx, clamp(p - hsv2rgb_K.xxx, vec3f(0.0), vec3f(1.0)), c.y); +} diff --git a/src/shaders/math/common_utils.wgsl b/src/shaders/math/common_utils.wgsl new file mode 100644 index 0000000..6ebc25a --- /dev/null +++ b/src/shaders/math/common_utils.wgsl @@ -0,0 +1,46 @@ +// 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: mat4x4f, normal_local: vec3f) -> vec3f { + let normal_matrix = mat3x3f(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: vec3f) -> vec2f { + let u = atan2(p.x, p.z) / TAU + 0.5; + let v = acos(clamp(p.y / length(p), -1.0, 1.0)) / PI; + return vec2f(u, v); +} + +// Spherical UV from direction vector (for skybox, etc.) +fn spherical_uv_from_dir(dir: vec3f) -> vec2f { + let u = atan2(dir.z, dir.x) / TAU + 0.5; + let v = asin(clamp(dir.y, -1.0, 1.0)) / PI + 0.5; + return vec2f(u, v); +} + +// Grid pattern for procedural texturing (checkerboard-like) +fn grid_pattern(uv: vec2f) -> 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. + +// Calculates normalized screen coordinates from fragment position and resolution. +// Input `p` is the fragment's @builtin(position), `resolution` is the screen resolution. +// Returns a vec2f in NDC space, with X adjusted for aspect ratio. +fn getScreenCoord(p: vec4f, resolution: vec2f) -> vec2f { + let q = p.xy / resolution; + var coord = -1.0 + 2.0 * q; + coord.x *= resolution.x / resolution.y; + return coord; +} diff --git a/src/shaders/math/noise.wgsl b/src/shaders/math/noise.wgsl new file mode 100644 index 0000000..dd97e02 --- /dev/null +++ b/src/shaders/math/noise.wgsl @@ -0,0 +1,147 @@ +// Random number generation and noise functions for WGSL shaders. +// Collection of hash functions and noise generators. + +// ============================================ +// Hash Functions (Float Input) +// ============================================ + +// Hash: f32 -> f32 +// Fast fractional hash for floats +fn hash_1f(x: f32) -> f32 { + var v = fract(x * 0.3351); + v *= v + 33.33; + v *= v + v; + return fract(v); +} + +// Hash: vec2f -> f32 +// 2D coordinate to single hash value +fn hash_2f(p: vec2f) -> f32 { + var h = dot(p, vec2f(127.1, 311.7)); + return fract(sin(h) * 43758.5453123); +} + +// Hash: vec2f -> vec2f +// 2D coordinate to 2D hash (from Shadertoy 4djSRW) +fn hash_2f_2f(p: vec2f) -> vec2f { + var p3 = fract(vec3f(p.x, p.y, p.x) * vec3f(0.1021, 0.1013, 0.0977)); + p3 += dot(p3, p3.yzx + 33.33); + return fract((p3.xx + p3.yz) * p3.zy); +} + +// Hash: vec3f -> f32 +// 3D coordinate to single hash value +fn hash_3f(p: vec3f) -> f32 { + var h = dot(p, vec3f(127.1, 311.7, 74.7)); + return fract(sin(h) * 43758.5453123); +} + +// Hash: vec3f -> vec3f +// 3D coordinate to 3D hash +fn hash_3f_3f(p: vec3f) -> vec3f { + var v = fract(p); + v += dot(v, v.yxz + 32.41); + return fract((v.xxy + v.yzz) * v.zyx); +} + +// ============================================ +// Hash Functions (Integer Input) +// ============================================ + +// Hash: u32 -> f32 +// Integer hash with bit operations (high quality) +fn hash_1u(p: u32) -> f32 { + var P = (p << 13u) ^ p; + P = P * (P * P * 15731u + 789221u) + 1376312589u; + return bitcast<f32>((P >> 9u) | 0x3f800000u) - 1.0; +} + +// Hash: u32 -> vec2f +fn hash_1u_2f(p: u32) -> vec2f { + return vec2f(hash_1u(p), hash_1u(p + 1423u)); +} + +// Hash: u32 -> vec3f +fn hash_1u_3f(p: u32) -> vec3f { + return vec3f(hash_1u(p), hash_1u(p + 1423u), hash_1u(p + 124453u)); +} + +// ============================================ +// Noise Functions +// ============================================ + +// Value Noise: 2D +// Interpolated grid noise using smoothstep +fn noise_2d(p: vec2f) -> f32 { + let i = floor(p); + let f = fract(p); + let u = f * f * (3.0 - 2.0 * f); + let n0 = hash_2f(i + vec2f(0.0, 0.0)); + let n1 = hash_2f(i + vec2f(1.0, 0.0)); + let n2 = hash_2f(i + vec2f(0.0, 1.0)); + let n3 = hash_2f(i + vec2f(1.0, 1.0)); + let ix0 = mix(n0, n1, u.x); + let ix1 = mix(n2, n3, u.x); + return mix(ix0, ix1, u.y); +} + +// Value Noise: 3D +fn noise_3d(p: vec3f) -> f32 { + let i = floor(p); + let f = fract(p); + let u = f * f * (3.0 - 2.0 * f); + let n000 = hash_3f(i + vec3f(0.0, 0.0, 0.0)); + let n100 = hash_3f(i + vec3f(1.0, 0.0, 0.0)); + let n010 = hash_3f(i + vec3f(0.0, 1.0, 0.0)); + let n110 = hash_3f(i + vec3f(1.0, 1.0, 0.0)); + let n001 = hash_3f(i + vec3f(0.0, 0.0, 1.0)); + let n101 = hash_3f(i + vec3f(1.0, 0.0, 1.0)); + let n011 = hash_3f(i + vec3f(0.0, 1.0, 1.0)); + let n111 = hash_3f(i + vec3f(1.0, 1.0, 1.0)); + let ix00 = mix(n000, n100, u.x); + let ix10 = mix(n010, n110, u.x); + let ix01 = mix(n001, n101, u.x); + let ix11 = mix(n011, n111, u.x); + let iy0 = mix(ix00, ix10, u.y); + let iy1 = mix(ix01, ix11, u.y); + return mix(iy0, iy1, u.z); +} + +// ============================================ +// Special Functions +// ============================================ + +// Gyroid function (periodic triply-orthogonal minimal surface) +// Useful for procedural patterns and cellular structures +fn gyroid(p: vec3f) -> f32 { + return abs(0.04 + dot(sin(p), cos(p.zxy))); +} + +// Fractional Brownian Motion (FBM) 2D +// Multi-octave noise for natural-looking variation +fn fbm_2d(p: vec2f, octaves: i32) -> f32 { + var value = 0.0; + var amplitude = 0.5; + var frequency = 1.0; + var pos = p; + for (var i = 0; i < octaves; i++) { + value += amplitude * noise_2d(pos * frequency); + frequency *= 2.0; + amplitude *= 0.5; + } + return value; +} + +// Fractional Brownian Motion (FBM) 3D +fn fbm_3d(p: vec3f, octaves: i32) -> f32 { + var value = 0.0; + var amplitude = 0.5; + var frequency = 1.0; + var pos = p; + for (var i = 0; i < octaves; i++) { + value += amplitude * noise_3d(pos * frequency); + frequency *= 2.0; + amplitude *= 0.5; + } + return value; +} diff --git a/src/shaders/math/sdf_shapes.wgsl b/src/shaders/math/sdf_shapes.wgsl new file mode 100644 index 0000000..2dfae3e --- /dev/null +++ b/src/shaders/math/sdf_shapes.wgsl @@ -0,0 +1,30 @@ +// 3D SDF primitives +fn sdSphere(p: vec3f, r: f32) -> f32 { + return length(p) - r; +} + +fn sdBox(p: vec3f, b: vec3f) -> f32 { + let q = abs(p) - b; + return length(max(q, vec3f(0.0))) + min(max(q.x, max(q.y, q.z)), 0.0); +} + +fn sdTorus(p: vec3f, t: vec2f) -> f32 { + let q = vec2f(length(p.xz) - t.x, p.y); + return length(q) - t.y; +} + +fn sdPlane(p: vec3f, n: vec3f, h: f32) -> f32 { + return dot(p, n) + h; +} + +// 2D SDF primitives +fn sdBox2D(p: vec2f, b: vec2f) -> f32 { + let d = abs(p) - b; + return length(max(d, vec2f(0.0))) + min(max(d.x, d.y), 0.0); +} + +// Approximate +fn sdEllipse(p: vec2f, ab: vec2f) -> f32 { + let d = length(p / ab); + return length(p) * (1.0 - 1.0 / d); +} diff --git a/src/shaders/math/sdf_utils.wgsl b/src/shaders/math/sdf_utils.wgsl new file mode 100644 index 0000000..5a77c7e --- /dev/null +++ b/src/shaders/math/sdf_utils.wgsl @@ -0,0 +1,115 @@ +fn get_normal_basic(p: vec3f, obj_params: vec4f) -> vec3f { + let obj_type = obj_params.x; + if (obj_type == 1.0) { return normalize(p); } + let e = vec2f(0.001, 0.0); + return normalize(vec3f( + get_dist(p + e.xyy, obj_params) - get_dist(p - e.xyy, obj_params), + get_dist(p + e.yxy, obj_params) - get_dist(p - e.yxy, obj_params), + get_dist(p + e.yyx, obj_params) - get_dist(p - e.yyx, obj_params) + )); +} + +// Optimized normal estimation using tetrahedron pattern (4 SDF evals instead of 6). +// Slightly less accurate than central differences but faster. +// Uses tetrahedral gradient approximation with corners at (±1, ±1, ±1). +fn get_normal_fast(p: vec3f, obj_params: vec4f) -> vec3f { + let obj_type = obj_params.x; + if (obj_type == 1.0) { return normalize(p); } + let eps = 0.0001; + let k = vec2f(1.0, -1.0); + return normalize( + k.xyy * get_dist(p + k.xyy * eps, obj_params) + + k.yyx * get_dist(p + k.yyx * eps, obj_params) + + k.yxy * get_dist(p + k.yxy * eps, obj_params) + + k.xxx * get_dist(p + k.xxx * eps, obj_params) + ); +} + +// Bump-mapped normal using central differences (6 samples: SDF + texture). +// High quality, suitable for detailed surfaces with displacement mapping. +// Note: Requires spherical_uv() function and get_dist() to be available in calling context. +fn get_normal_bump( + p: vec3f, + obj_params: vec4f, + noise_tex: texture_2d<f32>, + noise_sampler: sampler, + disp_strength: f32 +) -> vec3f { + let e = vec2f(0.005, 0.0); + + let q_x1 = p + e.xyy; + let uv_x1 = spherical_uv(q_x1); + let h_x1 = textureSample(noise_tex, noise_sampler, uv_x1).r; + let d_x1 = get_dist(q_x1, obj_params) - disp_strength * h_x1; + + let q_x2 = p - e.xyy; + let uv_x2 = spherical_uv(q_x2); + let h_x2 = textureSample(noise_tex, noise_sampler, uv_x2).r; + let d_x2 = get_dist(q_x2, obj_params) - disp_strength * h_x2; + + let q_y1 = p + e.yxy; + let uv_y1 = spherical_uv(q_y1); + let h_y1 = textureSample(noise_tex, noise_sampler, uv_y1).r; + let d_y1 = get_dist(q_y1, obj_params) - disp_strength * h_y1; + + let q_y2 = p - e.yxy; + let uv_y2 = spherical_uv(q_y2); + let h_y2 = textureSample(noise_tex, noise_sampler, uv_y2).r; + let d_y2 = get_dist(q_y2, obj_params) - disp_strength * h_y2; + + let q_z1 = p + e.yyx; + let uv_z1 = spherical_uv(q_z1); + let h_z1 = textureSample(noise_tex, noise_sampler, uv_z1).r; + let d_z1 = get_dist(q_z1, obj_params) - disp_strength * h_z1; + + let q_z2 = p - e.yyx; + let uv_z2 = spherical_uv(q_z2); + let h_z2 = textureSample(noise_tex, noise_sampler, uv_z2).r; + let d_z2 = get_dist(q_z2, obj_params) - disp_strength * h_z2; + + return normalize(vec3f(d_x1 - d_x2, d_y1 - d_y2, d_z1 - d_z2)); +} + +// Optimized bump-mapped normal using tetrahedron pattern (4 samples instead of 6). +// 33% faster than get_normal_bump(), slightly less accurate. +// Suitable for real-time rendering with displacement mapping. +fn get_normal_bump_fast( + p: vec3f, + obj_params: vec4f, + noise_tex: texture_2d<f32>, + noise_sampler: sampler, + disp_strength: f32 +) -> vec3f { + let eps = 0.0005; + let k = vec2f(1.0, -1.0); + + let q1 = p + k.xyy * eps; + let uv1 = spherical_uv(q1); + let h1 = textureSample(noise_tex, noise_sampler, uv1).r; + let d1 = get_dist(q1, obj_params) - disp_strength * h1; + + let q2 = p + k.yyx * eps; + let uv2 = spherical_uv(q2); + let h2 = textureSample(noise_tex, noise_sampler, uv2).r; + let d2 = get_dist(q2, obj_params) - disp_strength * h2; + + let q3 = p + k.yxy * eps; + let uv3 = spherical_uv(q3); + let h3 = textureSample(noise_tex, noise_sampler, uv3).r; + let d3 = get_dist(q3, obj_params) - disp_strength * h3; + + let q4 = p + k.xxx * eps; + let uv4 = spherical_uv(q4); + let h4 = textureSample(noise_tex, noise_sampler, uv4).r; + let d4 = get_dist(q4, obj_params) - disp_strength * h4; + + return normalize(k.xyy * d1 + k.yyx * d2 + k.yxy * d3 + k.xxx * d4); +} + +// Distance to an Axis-Aligned Bounding Box +fn aabb_sdf(p: vec3f, min_p: vec3f, max_p: vec3f) -> f32 { + let center = (min_p + max_p) * 0.5; + let extent = (max_p - min_p) * 0.5; + let q = abs(p - center) - extent; + return length(max(q, vec3f(0.0))) + min(max(q.x, max(q.y, q.z)), 0.0); +} diff --git a/src/shaders/math/utils.wgsl b/src/shaders/math/utils.wgsl new file mode 100644 index 0000000..c75cb66 --- /dev/null +++ b/src/shaders/math/utils.wgsl @@ -0,0 +1,14 @@ +// General-purpose math utility functions. + +// Returns a 2x2 rotation matrix. +fn rot(a: f32) -> mat2x2f { + let c = cos(a); + let s = sin(a); + return mat2x2f(c, s, -s, c); +} + +// Fast approximation of tanh. +fn tanh_approx(x: f32) -> f32 { + let x2 = x * x; + return clamp(x * (27.0 + x2) / (27.0 + 9.0 * x2), -1.0, 1.0); +} diff --git a/src/shaders/passthrough.wgsl b/src/shaders/passthrough.wgsl new file mode 100644 index 0000000..bce377c --- /dev/null +++ b/src/shaders/passthrough.wgsl @@ -0,0 +1,11 @@ +// Passthrough shader for Sequence v2 +#include "sequence_uniforms" +#include "render/fullscreen_uv_vs" // <- VertexOutput + vs_main + +@group(0) @binding(0) var input_sampler: sampler; +@group(0) @binding(1) var input_texture: texture_2d<f32>; +@group(0) @binding(2) var<uniform> uniforms: UniformsSequenceParams; + +@fragment fn fs_main(in: VertexOutput) -> @location(0) vec4f { + return textureSample(input_texture, input_sampler, in.uv); +} diff --git a/src/shaders/postprocess_inline.wgsl b/src/shaders/postprocess_inline.wgsl new file mode 100644 index 0000000..84ef3d3 --- /dev/null +++ b/src/shaders/postprocess_inline.wgsl @@ -0,0 +1,61 @@ +// Inline post-process functions for simple effects +// Use these instead of separate effect classes for v2 sequences + +// Vignette: darkens edges based on distance from center +fn apply_vignette(color: vec4f, uv: vec2f, radius: f32, softness: f32, intensity: f32) -> vec4f { + let d = distance(uv, vec2f(0.5, 0.5)); + let vignette = smoothstep(radius, radius - softness, d); + return vec4f(color.rgb * mix(1.0, vignette, intensity), color.a); +} + +// Flash: additive white flash +fn apply_flash(color: vec4f, flash_intensity: f32) -> vec4f { + return color + vec4f(flash_intensity, flash_intensity, flash_intensity, 0.0); +} + +// Fade: linear interpolation to target color +fn apply_fade(color: vec4f, fade_amount: f32, fade_color: vec3f) -> vec4f { + return vec4f(mix(color.rgb, fade_color, fade_amount), color.a); +} + +// Theme modulation: multiply by color tint +fn apply_theme(color: vec4f, theme_color: vec3f, strength: f32) -> vec4f { + return vec4f(mix(color.rgb, color.rgb * theme_color, strength), color.a); +} + +// Solarize: threshold-based color inversion +fn apply_solarize(color: vec4f, threshold: f32, strength: f32, time: f32) -> vec4f { + let pattern_num = u32(time / 2.0); + let is_even = (pattern_num % 2u) == 0u; + let thr = threshold + 0.15 * sin(time); + var col = color; + + if (is_even) { + if (col.r < thr) { col.r = mix(col.r, 1.0 - col.r, strength); } + if (col.g < thr) { col.g = mix(col.g, 1.0 - col.g * 0.7, strength * 0.7); } + if (col.b < thr) { col.b = mix(col.b, col.b * 0.5, strength); } + } else { + if (col.r < thr) { col.r = mix(col.r, col.r * 0.6, strength); } + if (col.g < thr) { col.g = mix(col.g, 1.0 - col.g * 0.8, strength * 0.8); } + if (col.b < thr) { col.b = mix(col.b, 1.0 - col.b, strength); } + } + return col; +} + +// Chroma aberration: RGB channel offset +fn apply_chroma_aberration(input_tex: texture_2d<f32>, input_sampler: sampler, + uv: vec2f, offset: f32, resolution: vec2f) -> vec4f { + let pixel_offset = offset / resolution; + let r = textureSample(input_tex, input_sampler, uv + vec2f(pixel_offset.x, 0.0)).r; + let g = textureSample(input_tex, input_sampler, uv).g; + let b = textureSample(input_tex, input_sampler, uv - vec2f(pixel_offset.x, 0.0)).b; + let a = textureSample(input_tex, input_sampler, uv).a; + return vec4f(r, g, b, a); +} + +// Distort: UV distortion based on time +fn apply_distort(uv: vec2f, time: f32, strength: f32) -> vec2f { + let distort_x = sin(uv.y * 10.0 + time * 2.0) * strength; + let distort_y = cos(uv.x * 10.0 + time * 2.0) * strength; + return uv + vec2f(distort_x, distort_y); +} diff --git a/src/shaders/ray_box.wgsl b/src/shaders/ray_box.wgsl new file mode 100644 index 0000000..37b9d6a --- /dev/null +++ b/src/shaders/ray_box.wgsl @@ -0,0 +1,16 @@ +struct RayBounds { + t_entry: f32, + t_exit: f32, + hit: bool, +}; + +fn ray_box_intersection(ro: vec3f, rd: vec3f, extent: vec3f) -> RayBounds { + let inv_rd = 1.0 / rd; + let t0 = (-extent - ro) * inv_rd; + let t1 = (extent - ro) * inv_rd; + let tmin_vec = min(t0, t1); + let tmax_vec = max(t0, t1); + let t_entry = max(0.0, max(tmin_vec.x, max(tmin_vec.y, tmin_vec.z))); + let t_exit = min(tmax_vec.x, min(tmax_vec.y, tmax_vec.z)); + return RayBounds(t_entry, t_exit, t_entry <= t_exit); +} diff --git a/src/shaders/ray_triangle.wgsl b/src/shaders/ray_triangle.wgsl new file mode 100644 index 0000000..ece823a --- /dev/null +++ b/src/shaders/ray_triangle.wgsl @@ -0,0 +1,30 @@ +// This file is part of the 64k demo project. +// Möller-Trumbore ray-triangle intersection algorithm. +// Reference: "Fast, Minimum Storage Ray-Triangle Intersection" + +struct TriangleHit { + uv: vec2f, + z: f32, + N: vec3f, + hit: bool, +}; + +fn ray_triangle_intersection( + orig: vec3f, + dir: vec3f, + p0: vec3f, + p1: vec3f, + p2: vec3f +) -> TriangleHit { + let d10 = p1 - p0; + let d20 = p2 - p0; + let N = cross(d10, d20); + let det = -dot(dir, N); + let invdet = 1.0 / det; + let d0 = orig - p0; + let nd = cross(d0, dir); + let uv = vec2f(dot(d20, nd), -dot(d10, nd)) * invdet; + let z = dot(d0, N) * invdet; + let hit = det > 0.0 && z >= 0.0 && uv.x >= 0.0 && uv.y >= 0.0 && (uv.x + uv.y) < 1.0; + return TriangleHit(uv, z, N, hit); +} diff --git a/src/shaders/render/fullscreen_uv_vs.wgsl b/src/shaders/render/fullscreen_uv_vs.wgsl new file mode 100644 index 0000000..f9ae427 --- /dev/null +++ b/src/shaders/render/fullscreen_uv_vs.wgsl @@ -0,0 +1,15 @@ +// Common vertex shader for fullscreen post-processing effects. +// Draws a single triangle that covers the entire screen, with uv +// coordinates in [0..1] +struct VertexOutput { + @builtin(position) position: vec4f, + @location(0) uv: vec2f, +}; + +@vertex fn vs_main(@builtin(vertex_index) i: u32) -> VertexOutput { + let pos = array<vec4f, 3>(vec4f(-1, -1, 0, 1.), vec4f(3, -1, 2., 1.), vec4f(-1, 3, 0, -1)); + var out: VertexOutput; + out.position = vec4f(pos[i].xy, 0.0, 1.0); + out.uv = pos[i].zw; + return out; +} diff --git a/src/shaders/render/fullscreen_vs.wgsl b/src/shaders/render/fullscreen_vs.wgsl new file mode 100644 index 0000000..507b892 --- /dev/null +++ b/src/shaders/render/fullscreen_vs.wgsl @@ -0,0 +1,10 @@ +// Common vertex shader for fullscreen post-processing effects. +// Draws a single triangle that covers the entire screen. +@vertex fn vs_main(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f { + var pos = array<vec2f, 3>( + vec2f(-1, -1), + vec2f( 3, -1), + vec2f(-1, 3) + ); + return vec4f(pos[i], 0.0, 1.0); +} diff --git a/src/shaders/render/lighting_utils.wgsl b/src/shaders/render/lighting_utils.wgsl new file mode 100644 index 0000000..f805860 --- /dev/null +++ b/src/shaders/render/lighting_utils.wgsl @@ -0,0 +1,6 @@ +fn calculate_lighting(color: vec3f, normal: vec3f, pos: vec3f, shadow: f32) -> vec3f { + let light_dir = normalize(vec3f(1.0, 1.0, 1.0)); + let diffuse = max(dot(normal, light_dir), 0.0); + let lighting = diffuse * (0.1 + 0.9 * shadow) + 0.1; // Ambient + Shadowed Diffuse + return color * lighting; +} diff --git a/src/shaders/render/raymarching.wgsl b/src/shaders/render/raymarching.wgsl new file mode 100644 index 0000000..2d6616d --- /dev/null +++ b/src/shaders/render/raymarching.wgsl @@ -0,0 +1,66 @@ +// Common functions for Signed Distance Field (SDF) raymarching. +// +// Required user-defined functions: +// - df(vec3f) -> f32 +// Distance field for single-pass rendering (rayMarch, normal, shadow) +// +// For two-pass rendering with object IDs, see raymarching_id.wgsl +// +// Provided constants: +// TOLERANCE, MAX_RAY_LENGTH, MAX_RAY_MARCHES, NORM_OFF + +const TOLERANCE: f32 = 0.0005; +const MAX_RAY_LENGTH: f32 = 20.0; +const MAX_RAY_MARCHES: i32 = 80; +const NORM_OFF: f32 = 0.005; + +// Computes the surface normal of the distance field at a point `pos`. +fn normal(pos: vec3f) -> vec3f { + let eps = vec2f(NORM_OFF, 0.0); + var nor: vec3f; + nor.x = df(pos + eps.xyy) - df(pos - eps.xyy); + nor.y = df(pos + eps.yxy) - df(pos - eps.yxy); + nor.z = df(pos + eps.yyx) - df(pos - eps.yyx); + return normalize(nor); +} + +// Performs the raymarching operation. +// Returns the distance along the ray to the surface, or MAX_RAY_LENGTH if no surface is hit. +fn rayMarch(ro: vec3f, rd: vec3f, tmin: f32) -> f32 { + var t = tmin; + for (var i = 0; i < MAX_RAY_MARCHES; i++) { + if (t > MAX_RAY_LENGTH) { + t = MAX_RAY_LENGTH; + break; + } + let d = df(ro + rd * t); + if (d < TOLERANCE) { + break; + } + t += d; + } + return t; +} + +// Computes a soft shadow for a given point. +fn shadow(lp: vec3f, ld: vec3f, mint: f32, maxt: f32) -> f32 { + let ds = 1.0 - 0.4; + var t = mint; + var nd = 1e6; + let soff = 0.05; + let smul = 1.5; + let MAX_SHD_MARCHES = 20; + + for (var i = 0; i < MAX_SHD_MARCHES; i++) { + let p = lp + ld * t; + let d = df(p); + if (d < TOLERANCE || t >= maxt) { + let sd = 1.0 - exp(-smul * max(t / maxt - soff, 0.0)); + return select(mix(sd, 1.0, smoothstep(0.0, 0.025, nd)), sd, t >= maxt); + } + nd = min(nd, d); + t += ds * d; + } + let sd = 1.0 - exp(-smul * max(t / maxt - soff, 0.0)); + return sd; +} diff --git a/src/shaders/render/raymarching_id.wgsl b/src/shaders/render/raymarching_id.wgsl new file mode 100644 index 0000000..d9f32b2 --- /dev/null +++ b/src/shaders/render/raymarching_id.wgsl @@ -0,0 +1,83 @@ +// Common functions for Signed Distance Field (SDF) raymarching with object ID. +// +// Required user-defined functions: +// - dfWithID(vec3f) -> RayMarchResult +// +// Requires constants from raymarching.wgsl: +// TOLERANCE, MAX_RAY_LENGTH, MAX_RAY_MARCHES, NORM_OFF +#include "render/raymarching" + +// ============================================================================ +// Two-Pass Raymarching Support +// ============================================================================ +// Design note: RayMarchResult is passed/returned by value (not pointer). +// At 12 bytes (3×f32), return value optimization makes this efficient. +// See doc/CODING_STYLE.md for rationale. + +struct RayMarchResult { + distance: f32, // Distance to surface (MAX_RAY_LENGTH if miss) + distance_max: f32, // Total distance marched (for fog/AO) + object_id: f32, // Object identifier (0.0 = background) +} + +// Raymarch with object ID tracking. +fn rayMarchWithID(ro: vec3f, rd: vec3f, init: RayMarchResult) -> RayMarchResult { + var t = init.distance; + var result = init; + + for (var i = 0; i < MAX_RAY_MARCHES; i++) { + if (t > MAX_RAY_LENGTH) { + result.distance = MAX_RAY_LENGTH; + result.distance_max = MAX_RAY_LENGTH; + break; + } + let sample = dfWithID(ro + rd * t); + if (sample.distance < TOLERANCE) { + result.distance = t; + result.distance_max = t; + result.object_id = sample.object_id; + break; + } + t += sample.distance; + } + + return result; +} + +// Reconstruct world position from stored result. +fn reconstructPosition(ray: Ray, result: RayMarchResult) -> vec3f { + return ray.origin + ray.direction * result.distance; +} + +// Normal calculation using dfWithID. +fn normalWithID(pos: vec3f) -> vec3f { + let eps = vec2f(NORM_OFF, 0.0); + var nor: vec3f; + nor.x = dfWithID(pos + eps.xyy).distance - dfWithID(pos - eps.xyy).distance; + nor.y = dfWithID(pos + eps.yxy).distance - dfWithID(pos - eps.yxy).distance; + nor.z = dfWithID(pos + eps.yyx).distance - dfWithID(pos - eps.yyx).distance; + return normalize(nor); +} + +// Shadow using stored intersection distance. +fn shadowWithStoredDistance(lp: vec3f, ld: vec3f, stored_dist: f32) -> f32 { + let ds = 1.0 - 0.4; + var t = 0.01; + var nd = 1e6; + let soff = 0.05; + let smul = 1.5; + let MAX_SHD_MARCHES = 20; + + for (var i = 0; i < MAX_SHD_MARCHES; i++) { + let p = lp + ld * t; + let d = dfWithID(p).distance; + if (d < TOLERANCE || t >= stored_dist) { + let sd = 1.0 - exp(-smul * max(t / stored_dist - soff, 0.0)); + return select(mix(sd, 1.0, smoothstep(0.0, 0.025, nd)), sd, t >= stored_dist); + } + nd = min(nd, d); + t += ds * d; + } + let sd = 1.0 - exp(-smul * max(t / stored_dist - soff, 0.0)); + return sd; +} diff --git a/src/shaders/render/scene_query_bvh.wgsl b/src/shaders/render/scene_query_bvh.wgsl new file mode 100644 index 0000000..cf2136b --- /dev/null +++ b/src/shaders/render/scene_query_bvh.wgsl @@ -0,0 +1,67 @@ +#include "math/sdf_shapes" +#include "math/sdf_utils" + +struct BVHNode { + min: vec3f, + left_idx: i32, + max: vec3f, + obj_idx_or_right: i32, +}; + +@group(0) @binding(2) var<storage, read> bvh_nodes: array<BVHNode>; + +fn get_dist(p: vec3f, obj_params: vec4f) -> f32 { + let obj_type = obj_params.x; + if (obj_type == 1.0) { return length(p) - 1.0; } // Unit Sphere + if (obj_type == 2.0) { return sdBox(p, vec3f(1.0)); } // Unit Box + if (obj_type == 3.0) { return sdTorus(p, vec2f(1.0, 0.4)); } // Unit Torus + if (obj_type == 4.0) { return sdPlane(p, vec3f(0.0, 1.0, 0.0), 0.0); } + if (obj_type == 5.0) { return sdBox(p, obj_params.yzw); } // MESH AABB + return 100.0; +} + +fn map_scene(p: vec3f, skip_idx: u32) -> f32 { + var d = 1000.0; + var stack: array<i32, 32>; + var stack_ptr = 0; + + if (arrayLength(&bvh_nodes) > 0u) { + stack[stack_ptr] = 0; + stack_ptr++; + } + + while (stack_ptr > 0) { + stack_ptr--; + let node_idx = stack[stack_ptr]; + let node = bvh_nodes[node_idx]; + + if (aabb_sdf(p, node.min, node.max) < d) { + if (node.left_idx < 0) { // Leaf + let obj_idx = u32(node.obj_idx_or_right); + if (obj_idx == skip_idx) { continue; } + let obj = object_data.objects[obj_idx]; + let q = (obj.inv_model * vec4f(p, 1.0)).xyz; + + // Extract scale factors from the model matrix + let sx = length(obj.model[0].xyz); + let sy = length(obj.model[1].xyz); + let sz = length(obj.model[2].xyz); + + var s = min(sx, min(sy, sz)); + if (obj.params.x == 4.0) { + s = sy; // Plane normal is (0,1,0) in local space + } + + d = min(d, get_dist(q, obj.params) * s); + } else { // Internal + if (stack_ptr < 31) { + stack[stack_ptr] = node.left_idx; + stack_ptr++; + stack[stack_ptr] = node.obj_idx_or_right; + stack_ptr++; + } + } + } + } + return d; +} diff --git a/src/shaders/render/scene_query_linear.wgsl b/src/shaders/render/scene_query_linear.wgsl new file mode 100644 index 0000000..5864b6f --- /dev/null +++ b/src/shaders/render/scene_query_linear.wgsl @@ -0,0 +1,56 @@ +#include "math/sdf_shapes" +#include "math/sdf_utils" + +fn get_dist(p: vec3f, obj_params: vec4f) -> f32 { + let obj_type = obj_params.x; + if (obj_type == 1.0) { return length(p) - 1.0; } // Unit Sphere + if (obj_type == 2.0) { return sdBox(p, vec3f(1.0)); } // Unit Box + if (obj_type == 3.0) { return sdTorus(p, vec2f(1.0, 0.4)); } // Unit Torus + if (obj_type == 4.0) { return sdPlane(p, vec3f(0.0, 1.0, 0.0), 0.0); } + if (obj_type == 5.0) { return sdBox(p, obj_params.yzw); } // MESH AABB + return 100.0; +} + +fn map_scene(p: vec3f, skip_idx: u32) -> f32 { + + var d = 1000.0; + + let num_objects = arrayLength(&object_data.objects); + + for (var i = 0u; i < num_objects; i++) { + + if (i == skip_idx) { continue; } + + let obj = object_data.objects[i]; + + let q = (obj.inv_model * vec4f(p, 1.0)).xyz; + + + + // Extract scale factors from the model matrix + + let sx = length(obj.model[0].xyz); + + let sy = length(obj.model[1].xyz); + + let sz = length(obj.model[2].xyz); + + + + var s = min(sx, min(sy, sz)); + + if (obj.params.x == 4.0) { + + s = sy; // Plane normal is (0,1,0) in local space + + } + + + + d = min(d, get_dist(q, obj.params) * s); + + } + + return d; + +} diff --git a/src/shaders/render/shadows.wgsl b/src/shaders/render/shadows.wgsl new file mode 100644 index 0000000..b71e073 --- /dev/null +++ b/src/shaders/render/shadows.wgsl @@ -0,0 +1,13 @@ +fn calc_shadow(ro: vec3f, rd: vec3f, tmin: f32, tmax: f32, skip_idx: u32) -> f32 { + var res = 1.0; + var t = tmin; + if (t < 0.05) { t = 0.05; } + for (var i = 0; i < 32; i = i + 1) { + let h = map_scene(ro + rd * t, skip_idx); + if (h < 0.001) { return 0.0; } + res = min(res, 16.0 * h / t); + t = t + clamp(h, 0.02, 0.4); + if (t > tmax) { break; } + } + return clamp(res, 0.0, 1.0); +} diff --git a/src/shaders/sequence_uniforms.wgsl b/src/shaders/sequence_uniforms.wgsl new file mode 100644 index 0000000..1aef34e --- /dev/null +++ b/src/shaders/sequence_uniforms.wgsl @@ -0,0 +1,12 @@ +// Sequence v2 uniform structure for WGSL shaders +// Matches UniformsSequenceParams in sequence.h + +struct UniformsSequenceParams { + resolution: vec2f, + aspect_ratio: f32, + time: f32, + beat_time: f32, + beat_phase: f32, + audio_intensity: f32, + noise: f32, +}; diff --git a/src/shaders/skybox.wgsl b/src/shaders/skybox.wgsl new file mode 100644 index 0000000..075eeb6 --- /dev/null +++ b/src/shaders/skybox.wgsl @@ -0,0 +1,24 @@ +#include "common_uniforms" +#include "math/common_utils" +#include "render/fullscreen_uv_vs" // <- VertexOutput + vs_main + +@group(0) @binding(0) var sky_tex: texture_2d<f32>; +@group(0) @binding(1) var sky_sampler: sampler; +@group(0) @binding(2) var<uniform> globals: GlobalUniforms; + +@fragment +fn fs_main(in: VertexOutput) -> @location(0) vec4f { + // Convert UV to NDC + let ndc_x = in.uv.x * 2.0 - 1.0; + let ndc_y = (1.0 - in.uv.y) * 2.0 - 1.0; // Un-flip Y for NDC (Y-up) + + // Unproject to find world direction + // We want the direction from camera to the far plane at this pixel + let clip_pos = vec4f(ndc_x, ndc_y, 1.0, 1.0); + let world_pos_h = globals.inv_view_proj * clip_pos; + let world_pos = world_pos_h.xyz / world_pos_h.w; + + let ray_dir = normalize(world_pos - globals.camera_pos_time.xyz); + let uv = spherical_uv_from_dir(ray_dir); + return textureSample(sky_tex, sky_sampler, uv); +}
\ No newline at end of file |
