Skip to content

Commit

Permalink
feat(mandelbrot): better coloring
Browse files Browse the repository at this point in the history
  • Loading branch information
boralg committed Feb 17, 2025
1 parent a55d9c7 commit cf893a8
Showing 1 changed file with 26 additions and 19 deletions.
45 changes: 26 additions & 19 deletions examples/src/mandelbrot/assets/shader.wgsl
Original file line number Diff line number Diff line change
Expand Up @@ -24,35 +24,42 @@ fn vs_main(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>) -> Vert
@fragment
fn fs_main(@location(0) fragUV: vec2<f32>) -> @location(0) vec4<f32> {
let max_iter: u32 = 100u;

// Calculate the coordinates in the complex plane
let centered_uv = (fragUV * 2.0 - vec2<f32>(1.0, 1.0)) * vec2<f32>(uniforms.aspect_ratio, 1.0); // Convert [0,1] range to [-1,1] and adjust for aspect ratio

// Adjust coordinates based on translation and scale, without affecting rotation
let c = uniforms.translation + vec2<f32>(
centered_uv.x * uniforms.scale,
centered_uv.y * uniforms.scale
);
let centered_uv = (fragUV * 2.0 - vec2<f32>(1.0, 1.0)) * vec2<f32>(uniforms.aspect_ratio, 1.0);
let c = uniforms.translation + centered_uv * uniforms.scale;

var z: vec2<f32> = vec2<f32>(0.0, 0.0);
var z = vec2<f32>(0.0, 0.0);
var iter: u32 = 0u;

// Iterate to determine if the point is in the Mandelbrot set
for (var i: u32 = 0u; i < max_iter; i = i + 1u) {
if (dot(z, z) > 4.0) {
break;
}
for (var i: u32 = 0u; i < max_iter; i++) {
if (dot(z, z) > 4.0) { break; }
z = vec2<f32>(
z.x * z.x - z.y * z.y + c.x,
2.0 * z.x * z.y + c.y
);
iter = iter + 1u;
iter++;
}

if (iter == max_iter) {
return vec4<f32>(0.0, 0.0, 0.0, 1.0); // Inside the Mandelbrot set
return vec4<f32>(0.0, 0.0, 0.0, 1.0);
} else {
let t: f32 = f32(iter) / f32(max_iter);
return vec4<f32>(t * 0.15, t * 0.35, t * 0.25, 1.0); // Gradient color for points outside
let modulus_squared = dot(z, z);
let log_zn = 0.5 * log2(modulus_squared);
let nu = log2(log_zn);
let smooth_iter = f32(iter) + 1.0 - nu;
let t = smooth_iter / f32(max_iter);

let speed = 2.0;
let brightness = 0.7;
let r = brightness * sin(t * speed * 6.2831);
let g = brightness * sin(t * speed * 6.2831 + 2.094);
let b = brightness * sin(t * speed * 6.2831 + 4.188);

return vec4<f32>(
0.5 + r * 0.5,
0.5 + g * 0.5,
0.5 + b * 0.5,
1.0
);
}
}
}

0 comments on commit cf893a8

Please sign in to comment.