wallswitch 0.61.0

randomly selects wallpapers for multiple monitors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Mandelbrot Set fractal generator overlay.
//!
//! Renders Mandelbrot Set overlays using the distance estimator colouring method
//! shared with the Julia generator via [`color_distance_estimator`]. The
//! `random` constructor runs a parallelised entropy sweep to find the zoom level
//! that maximises structural detail, then applies `dynamic_autofocus` to refine
//! the centre point and derive a level-of-detail iteration count.
//!
//! Generator function: `z(n+1) = z(n)^2 + c`, starting from `z = 0`,
//! where `c` varies over the viewport grid coordinates.

use crate::{
    ColorRGB, Complex, FractalConfig, FractalDescriptor, FractalPreset, MAX_ITERATIONS,
    MIN_ITERATIONS, Monitor, NEON_PALETTES, ProceduralEffect, ROTATION_STEPS, RandomExt, Viewport,
    ViewportSpecs, WallSwitchResult, color_distance_estimator, get_random_integer,
    mandelbrot_escape,
};
use rayon::prelude::*;
use std::cmp::Ordering;

// ============================================================================
// PRESET TABLE
// ============================================================================

/// All available Mandelbrot coordinate presets.
const MANDELBROT_PRESETS: &[FractalPreset] = &[
    FractalPreset {
        center: Complex {
            re: -0.8115,
            im: 0.2014,
        },
        fractal_name: "Tendril Valley Filaments",
        effect_name: ProceduralEffect::Mandelbrot,
    },
    FractalPreset {
        center: Complex {
            re: -0.156,
            im: 1.033,
        },
        fractal_name: "Dreadlock Valley Basin",
        effect_name: ProceduralEffect::Mandelbrot,
    },
    FractalPreset {
        center: Complex {
            re: -0.38,
            im: 0.66,
        },
        fractal_name: "Starburst Star Valley",
        effect_name: ProceduralEffect::Mandelbrot,
    },
    FractalPreset {
        center: Complex {
            re: -0.56226,
            im: 0.64273,
        },
        fractal_name: "Feathered Filament Cascades",
        effect_name: ProceduralEffect::Mandelbrot,
    },
    FractalPreset {
        center: Complex {
            re: -0.77568377,
            im: 0.13646737,
        },
        fractal_name: "Deep Seahorse Tail Spiral",
        effect_name: ProceduralEffect::Mandelbrot,
    },
    FractalPreset {
        center: Complex { re: -1.45, im: 0.0 },
        fractal_name: "West Needle Crown Filaments",
        effect_name: ProceduralEffect::Mandelbrot,
    },
    FractalPreset {
        center: Complex {
            re: -0.55,
            im: 0.62,
        },
        fractal_name: "Pentagonal Star Valley",
        effect_name: ProceduralEffect::Mandelbrot,
    },
    FractalPreset {
        center: Complex {
            re: -1.625,
            im: 0.0,
        },
        fractal_name: "Bi-Directional Filament",
        effect_name: ProceduralEffect::Mandelbrot,
    },
    FractalPreset {
        center: Complex {
            re: -0.70176,
            im: 0.35422,
        },
        fractal_name: "Peacock Tail Valley Plumes",
        effect_name: ProceduralEffect::Mandelbrot,
    },
    FractalPreset {
        center: Complex {
            re: -0.8113,
            im: 0.2015,
        },
        fractal_name: "Medusa Tendril Clusters",
        effect_name: ProceduralEffect::Mandelbrot,
    },
];

// ============================================================================
// GENERATOR
// ============================================================================

/// A procedural generator for rendering Mandelbrot Set fractals onto desktop backgrounds.
pub struct MandelbrotGenerator {
    /// The selected coordinate preset defining the viewport focus point.
    pub preset: FractalPreset,
    /// Shared viewport and rendering configuration.
    pub config: FractalConfig,
}

impl FractalDescriptor for MandelbrotGenerator {
    #[inline(always)]
    fn config(&self) -> &FractalConfig {
        &self.config
    }

    #[inline(always)]
    fn center(&self) -> Complex {
        self.preset.center
    }

    // Mandelbrot: `is_julia` defaults to `false` — the viewport maps `c`, not `z`.

    #[inline(always)]
    fn render_pixel(&self, c: Complex, scale: f64, _max_radius: f64) -> (ColorRGB, f64, f64) {
        let (i, z, dz) = mandelbrot_escape(c, self.config.scan_iterations);
        color_distance_estimator(
            i,
            self.config.scan_iterations,
            z,
            dz,
            scale,
            self.config.color_palette,
        )
    }

    fn info_text(&self) -> String {
        format!(
            "fractal [{}]\n\
             f(z) = z^2 + c, where c = {:8.5} {:+7.5}i (iter = {:4}, zoom = {:.5}), color: {}",
            self.preset.fractal_name,
            self.preset.center.re,
            self.preset.center.im,
            self.config.scan_iterations,
            self.config.zoom,
            self.config.color_palette
        )
    }
}

impl MandelbrotGenerator {
    /// Constructs a randomized, non-fitted Mandelbrot Generator.
    ///
    /// This acts as a base constructor, returning an error if
    /// the preset or color palette tables are empty.
    pub fn new() -> WallSwitchResult<Self> {
        let preset = MANDELBROT_PRESETS.get_random_sample()?;
        let color_palette = NEON_PALETTES.get_random_sample()?;

        Ok(Self {
            preset,
            config: FractalConfig {
                scan_iterations: MIN_ITERATIONS,
                color_palette,
                zoom: 0.0025,
                rotation: Complex::one(),
            },
        })
    }

    /// Constructs a randomised, monitor-fitted Mandelbrot generator.
    ///
    /// Reuses [`new`](Self::new) to construct the base randomized generator.
    /// Runs a parallelised entropy sweep over a geometric zoom sequence and
    /// `ROTATION_STEPS` rotation angles, selecting the combination that
    /// maximises information content. `dynamic_autofocus` then refines the
    /// centre and derives the level-of-detail iteration count.
    pub fn random(monitor: &Monitor) -> WallSwitchResult<Self> {
        let (width, height) = (
            monitor.resolution.width as u32,
            monitor.resolution.height as u32,
        );

        // 1. Initialize base randomized generator configuration
        let mut mandelbrot = Self::new()?;

        // 2. Perform parallelized entropy sweep to optimize zoom and rotation
        let rotation_phasors: Vec<Complex> = Complex::rotation_phasors(ROTATION_STEPS).collect();
        let zooms_count = get_random_integer(30, 50);
        let candidates = generate_zoom_candidates(zooms_count, ROTATION_STEPS);
        let preset_center = mandelbrot.preset.center;

        let (best_base_zoom, best_rotation, _) = candidates
            .par_iter()
            .map(|&(base_zoom, r_idx)| {
                let aspect_ratio = width as f64 / height as f64;
                let adjusted_zoom = if aspect_ratio > 1.0 {
                    base_zoom * aspect_ratio.sqrt()
                } else {
                    base_zoom
                };

                let rotation = rotation_phasors[r_idx];
                let entropy = calculate_entropy(
                    preset_center,
                    adjusted_zoom,
                    rotation,
                    MIN_ITERATIONS,
                    width,
                    height,
                );
                (base_zoom, rotation, entropy)
            })
            .max_by(|a, b| a.2.partial_cmp(&b.2).unwrap_or(Ordering::Equal))
            .unwrap_or((0.0002, Complex::one(), 0.0));

        mandelbrot.config.zoom = best_base_zoom;
        mandelbrot.config.rotation = best_rotation;

        // 3. Apply aspect ratio scaling and focus refinement
        mandelbrot.optimize_fit(width, height);
        mandelbrot.dynamic_autofocus(width, height);
        Ok(mandelbrot)
    }

    /// Scales the zoom for wide-aspect-ratio monitors.
    pub fn optimize_fit(&mut self, width: u32, height: u32) {
        let aspect_ratio = width as f64 / height as f64;
        if aspect_ratio > 1.0 {
            self.config.zoom *= aspect_ratio.sqrt();
        }
    }

    /// Refines the viewport centre and derives a level-of-detail iteration count.
    ///
    /// Uses a boundary-direction heuristic to align the centre with the nearest
    /// interior segment, then performs a local entropy-hill-climb across
    /// `ROTATION_STEPS` offsets to maximise structural detail. The iteration
    /// count is derived from the zoom level using a logarithmic LOD formula.
    pub fn dynamic_autofocus(&mut self, width: u32, height: u32) {
        let search_radius = self.config.zoom * 0.25;
        let branch_phasor = find_branch_phasor(
            self.preset.center,
            search_radius,
            self.config.scan_iterations,
        );

        let aligned_center = locked_interior_grid_alignment(
            self.preset.center,
            branch_phasor,
            search_radius,
            self.config.scan_iterations,
        );
        self.preset.center = aligned_center;

        let best_entropy = calculate_entropy(
            self.preset.center,
            self.config.zoom,
            self.config.rotation,
            self.config.scan_iterations,
            width,
            height,
        );

        let climb_radius = self.config.zoom * 0.05;
        let search_directions: Vec<Complex> = std::iter::once(Complex::zero())
            .chain(Complex::rotation_phasors(ROTATION_STEPS).map(|p| p * climb_radius))
            .collect();

        let (best_center, _) = search_directions
            .par_iter()
            .map(|&offset| {
                let candidate = self.preset.center + offset;
                let entropy = calculate_entropy(
                    candidate,
                    self.config.zoom,
                    self.config.rotation,
                    self.config.scan_iterations,
                    width,
                    height,
                );
                (candidate, entropy)
            })
            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal))
            .unwrap_or((self.preset.center, best_entropy));

        self.preset.center = best_center;

        // LOD: scale iterations logarithmically with zoom level.
        let scale = self.config.zoom / (width.min(height) as f64);
        let lod = (150.0 + 45.0 * (1.0 / scale).ln()) as u32;
        self.config.scan_iterations = lod.clamp(MIN_ITERATIONS, MAX_ITERATIONS);
    }
}

// ============================================================================
// PRIVATE PURE HELPERS
// ============================================================================

/// Identifies the phasor direction pointing toward the steepest boundary gradient.
fn find_branch_phasor(center: Complex, search_radius: f64, scan_iterations: u32) -> Complex {
    let mut best_phasor = Complex::one();
    let mut max_variation = -1.0_f64;

    for phasor in Complex::rotation_phasors(ROTATION_STEPS) {
        let mut total_variation = 0.0;
        let mut prev_i = 0;

        for k in 1..=4 {
            let sample = center + phasor * (search_radius * k as f64 * 0.25);
            let (i, _, _) = mandelbrot_escape(sample, scan_iterations);
            if k > 1 {
                total_variation += (i as f64 - prev_i as f64).abs();
            }
            prev_i = i;
        }

        if total_variation > max_variation {
            max_variation = total_variation;
            best_phasor = phasor;
        }
    }
    best_phasor
}

/// Locates the mid-point of the target interior segment along the branch direction.
fn locked_interior_grid_alignment(
    center: Complex,
    phasor: Complex,
    search_radius: f64,
    scan_iterations: u32,
) -> Complex {
    const STEPS: usize = 64;
    let mut interior_segments: Vec<(usize, usize)> = Vec::new();
    let mut in_interior = false;
    let mut segment_start = 0;

    for step in 0..STEPS {
        let t = -search_radius + (step as f64 / (STEPS - 1) as f64) * (2.0 * search_radius);
        let (i, _, _) = mandelbrot_escape(center + phasor * t, scan_iterations);
        let is_interior = i >= scan_iterations;

        match (is_interior, in_interior) {
            (true, false) => {
                in_interior = true;
                segment_start = step;
            }
            (false, true) => {
                in_interior = false;
                interior_segments.push((segment_start, step - 1));
            }
            _ => {}
        }
    }
    if in_interior {
        interior_segments.push((segment_start, STEPS - 1));
    }

    let target = if interior_segments.len() >= 4 {
        Some(interior_segments[3])
    } else {
        interior_segments.last().copied()
    };

    if let Some((start_idx, end_idx)) = target {
        let mid_step = (start_idx + end_idx) as f64 / 2.0;
        let t_mid = -search_radius + (mid_step / (STEPS - 1) as f64) * (2.0 * search_radius);
        center + phasor * t_mid
    } else {
        center
    }
}

/// Computes the Shannon entropy of the iteration histogram at a given viewport configuration.
///
/// Higher entropy indicates more varied iteration counts and therefore more structural
/// detail visible in the rendered image.
fn calculate_entropy(
    center: Complex,
    zoom: f64,
    rotation: Complex,
    scan_iterations: u32,
    width: u32,
    height: u32,
) -> f64 {
    const GRID: usize = 32;
    let mut histogram = vec![0u32; (scan_iterations + 1) as usize];

    let specs = ViewportSpecs {
        center,
        zoom,
        rotation,
        is_julia: false,
    };
    let viewport = Viewport::new(width as f64, height as f64, &specs);
    let (step_x, step_y) = (width as f64 / GRID as f64, height as f64 / GRID as f64);

    for gy in 0..GRID {
        let y_f = gy as f64 * step_y;
        for gx in 0..GRID {
            let (i, _, _) =
                mandelbrot_escape(viewport.map(gx as f64 * step_x, y_f), scan_iterations);
            histogram[i as usize] += 1;
        }
    }

    let total = (GRID * GRID) as f64;
    histogram.iter().filter(|&&c| c > 0).fold(0.0, |acc, &c| {
        let p = c as f64 / total;
        acc - p * p.ln()
    })
}

/// Generates a geometric (log-spaced) sequence of zoom candidates.
///
/// Samples `zooms_count * rotations_count` `(zoom, rotation_index)` pairs
/// uniformly distributed in log-space between `2e-6` (microscopic close-up)
/// and `9.0` (panoramic macro view).
///
/// For a pool of `N` zooms and index `i`:
///
/// ```text
/// zoom_i = min_zoom * (max_zoom / min_zoom)^(i / (N - 1))
/// ```
///
/// This guarantees exact boundary alignment and smooth spatial transitions
/// between candidates regardless of pool size.
pub fn generate_zoom_candidates(zooms_count: usize, rotations_count: usize) -> Vec<(f64, usize)> {
    if zooms_count == 0 || rotations_count == 0 {
        return Vec::new();
    }

    const MIN_ZOOM: f64 = 2e-6;
    const MAX_ZOOM: f64 = 9.0;
    let log_ratio = MAX_ZOOM / MIN_ZOOM;

    let mut candidates = Vec::with_capacity(zooms_count * rotations_count);

    for z_idx in 0..zooms_count {
        let t = if zooms_count > 1 {
            z_idx as f64 / (zooms_count - 1) as f64
        } else {
            0.0
        };
        let zoom = MIN_ZOOM * log_ratio.powf(t);
        for r_idx in 0..rotations_count {
            candidates.push((zoom, r_idx));
        }
    }
    candidates
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests_mandelbrot {
    use super::*;

    #[test]
    fn test_mandelbrot_new_sanity() -> WallSwitchResult<()> {
        let m = MandelbrotGenerator::new()?;
        assert!(m.config.zoom > 0.0, "zoom must be positive");
        assert_eq!(m.preset.effect_name, ProceduralEffect::Mandelbrot);
        Ok(())
    }

    #[test]
    fn test_random_generator_sanity() -> WallSwitchResult<()> {
        let monitor = Monitor::default();
        let m = MandelbrotGenerator::random(&monitor)?;
        assert!(m.config.zoom > 0.0, "zoom must be positive");
        assert_eq!(m.preset.effect_name, ProceduralEffect::Mandelbrot);
        assert!(m.config.scan_iterations >= MIN_ITERATIONS);
        assert!(m.config.scan_iterations <= MAX_ITERATIONS);
        Ok(())
    }

    #[test]
    fn test_all_presets_correct_effect_name() {
        for p in MANDELBROT_PRESETS {
            assert_eq!(
                p.effect_name,
                ProceduralEffect::Mandelbrot,
                "wrong effect_name for '{}'",
                p.fractal_name
            );
        }
    }

    #[test]
    fn test_zoom_candidates_boundaries() {
        let zooms_count = 50;
        let rotations_count = 16;
        let candidates = generate_zoom_candidates(zooms_count, rotations_count);

        assert_eq!(candidates.len(), zooms_count * rotations_count);

        // First candidate must equal MIN_ZOOM exactly (t = 0).
        assert!((candidates[0].0 - 2e-6).abs() < 1e-12, "min bound mismatch");

        // Last candidate must equal MAX_ZOOM exactly (t = 1).
        let last = candidates.last().unwrap().0;
        assert!((last - 9.0).abs() < 1e-12, "max bound mismatch: {last}");
    }

    #[test]
    fn test_zoom_candidates_monotonically_increasing() {
        let candidates = generate_zoom_candidates(20, 1);
        let zooms: Vec<f64> = candidates.iter().map(|&(z, _)| z).collect();
        for w in zooms.windows(2) {
            assert!(
                w[0] <= w[1],
                "zoom sequence not monotone: {} > {}",
                w[0],
                w[1]
            );
        }
    }

    #[test]
    fn test_zoom_candidates_empty_on_zero_count() {
        assert!(generate_zoom_candidates(0, 16).is_empty());
        assert!(generate_zoom_candidates(16, 0).is_empty());
    }
}