wallswitch 0.60.11

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
//! Mandelbrot Set fractal generator overlay.
//!
//! This module provides the implementation of the Mandelbrot Set fractal renderer,
//! using pre-tuned coordinate presets. It generates mathematical overlays
//! dynamically fitted to display proportions and blends them using high-definition
//! neon curves, chromatic dual-tone borders, and 3D parallax shadow depths.

use std::cmp::Ordering;

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

/// A procedural generator for rendering Mandelbrot Set fractals onto desktop backgrounds.
pub struct MandelbrotGenerator {
    pub preset: FractalPreset,
    pub config: FractalConfig,
}

impl Default for MandelbrotGenerator {
    fn default() -> Self {
        Self {
            preset: FractalPreset {
                center: Complex::new(-0.56226, 0.64273),
                fractal_name: "Feathered Filament Cascades",
                effect_name: ProceduralEffect::Mandelbrot,
            },
            config: FractalConfig {
                // Initialize directly with MIN_ITERATIONS since dynamic_autofocus
                // will calculate the optimized Level of Detail (LOD) anyway.
                scan_iterations: MIN_ITERATIONS,
                color_palette: NEON_PALETTES[5],
                zoom: 0.0025,
                rotation: Complex::one(),
            },
        }
    }
}

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

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

    #[inline(always)]
    fn is_julia(&self) -> bool {
        false
    }

    #[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 {
    fn find_branch_phasor(center: Complex, search_radius: f64, scan_iterations: u32) -> Complex {
        let mut best_phasor = Complex::one();
        let mut max_boundary_score = -1.0;

        for phasor in get_rotation_phasors(ROTATION_STEPS) {
            let mut total_variation = 0.0;
            let mut prev_i = 0;

            for k in 1..=4 {
                let sample_point = center + phasor * (search_radius * (k as f64) * 0.25);
                let (i, _, _) = mandelbrot_escape(sample_point, scan_iterations);

                if k > 1 {
                    total_variation += (i as f64 - prev_i as f64).abs();
                }
                prev_i = i;
            }

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

    fn locked_interior_grid_alignment(
        center: Complex,
        phasor: Complex,
        search_radius: f64,
        scan_iterations: u32,
    ) -> Complex {
        let steps = 64;
        let mut interior_segments = 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 test_point = center + phasor * t;
            let (i, _, _) = mandelbrot_escape(test_point, scan_iterations);

            let is_interior = i >= scan_iterations;

            if is_interior && !in_interior {
                in_interior = true;
                segment_start = step;
            } else if !is_interior && in_interior {
                in_interior = false;
                interior_segments.push((segment_start, step - 1));
            }
        }
        if in_interior {
            interior_segments.push((segment_start, steps - 1));
        }

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

        if let Some((start_idx, end_idx)) = target_segment {
            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
        }
    }

    fn calculate_entropy(
        center: Complex,
        zoom: f64,
        rotation: Complex,
        scan_iterations: u32,
        width: u32,
        height: u32,
    ) -> f64 {
        let grid_size = 32;
        let mut histogram = vec![0; scan_iterations as usize + 1];

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

        for gy in 0..grid_size {
            let y_f = (gy as f64) * step_y;
            for gx in 0..grid_size {
                let x_f = (gx as f64) * step_x;
                let c_init = viewport.map(x_f, y_f);

                let (i, _, _) = mandelbrot_escape(c_init, scan_iterations);
                if (i as usize) < histogram.len() {
                    histogram[i as usize] += 1;
                }
            }
        }

        let total_samples = (grid_size * grid_size) as f64;
        let mut entropy: f64 = 0.0;

        for &count in &histogram {
            if count > 0 {
                let p = (count as f64) / total_samples;
                entropy -= p * p.ln();
            }
        }
        entropy
    }

    pub fn random(monitor: &Monitor) -> Self {
        let width = monitor.resolution.width as u32;
        let height = monitor.resolution.height as u32;

        let presets = [
            FractalPreset {
                center: Complex::new(-0.8115, 0.2014),
                fractal_name: "Tendril Valley Filaments",
                effect_name: ProceduralEffect::Mandelbrot,
            },
            FractalPreset {
                center: Complex::new(-0.156, 1.033),
                fractal_name: "Dreadlock Valley Basin",
                effect_name: ProceduralEffect::Mandelbrot,
            },
            FractalPreset {
                center: Complex::new(-0.38, 0.66),
                fractal_name: "Starburst Star Valley",
                effect_name: ProceduralEffect::Mandelbrot,
            },
            FractalPreset {
                center: Complex::new(-0.56226, 0.64273),
                fractal_name: "Feathered Filament Cascades",
                effect_name: ProceduralEffect::Mandelbrot,
            },
            FractalPreset {
                center: Complex::new(-0.77568377, 0.13646737),
                fractal_name: "Deep Seahorse Tail Spiral",
                effect_name: ProceduralEffect::Mandelbrot,
            },
            FractalPreset {
                center: Complex::new(-1.45, 0.0),
                fractal_name: "West Needle Crown Filaments",
                effect_name: ProceduralEffect::Mandelbrot,
            },
            FractalPreset {
                center: Complex::new(-1.25, 0.05),
                fractal_name: "Gothic Archway Scepters",
                effect_name: ProceduralEffect::Mandelbrot,
            },
            FractalPreset {
                center: Complex::new(-0.55, 0.62),
                fractal_name: "Pentagonal Star Valley",
                effect_name: ProceduralEffect::Mandelbrot,
            },
            FractalPreset {
                center: Complex::new(-1.625, 0.0),
                fractal_name: "Bi-Directional Filament",
                effect_name: ProceduralEffect::Mandelbrot,
            },
        ];

        let selected_preset = presets.choose().copied().unwrap_or(presets[0]);
        let color_palette = NEON_PALETTES.choose().copied().unwrap_or(NEON_PALETTES[0]);

        // Use MIN_ITERATIONS as the safe baseline for candidate sampling
        let scan_iterations = MIN_ITERATIONS;

        let rotations_count = ROTATION_STEPS;
        let zooms_count = get_random_integer(30, 50);
        let rotation_phasors: Vec<Complex> = get_rotation_phasors(rotations_count).collect();
        let candidates = generate_zoom_candidates(zooms_count, rotations_count);

        let (best_base_zoom, best_rotation, _best_entropy) = 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 = Self::calculate_entropy(
                    selected_preset.center,
                    adjusted_zoom,
                    rotation,
                    scan_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));

        let mut mandelbrot = Self {
            preset: selected_preset,
            config: FractalConfig {
                scan_iterations,
                color_palette,
                zoom: best_base_zoom,
                rotation: best_rotation,
            },
        };

        mandelbrot.optimize_fit(width, height);
        mandelbrot.dynamic_autofocus(width, height);
        mandelbrot
    }

    pub fn dynamic_autofocus(&mut self, width: u32, height: u32) {
        let search_radius = self.config.zoom * 0.25;
        let branch_phasor = Self::find_branch_phasor(
            self.preset.center,
            search_radius,
            self.config.scan_iterations,
        );

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

        let best_entropy = Self::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(get_rotation_phasors(ROTATION_STEPS).map(|phasor| phasor * climb_radius))
            .collect();

        let (best_center, _) = search_directions
            .par_iter()
            .map(|&offset| {
                let candidate_center = self.preset.center + offset;
                let entropy = Self::calculate_entropy(
                    candidate_center,
                    self.config.zoom,
                    self.config.rotation,
                    self.config.scan_iterations,
                    width,
                    height,
                );
                (candidate_center, 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;

        let scale = self.config.zoom / (width.min(height) as f64);
        let lod_iterations = (150.0 + 45.0 * (1.0 / scale).ln()) as u32;
        self.config.scan_iterations = lod_iterations.clamp(MIN_ITERATIONS, MAX_ITERATIONS);
    }

    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();
        }
    }
}

/// Generates a geometric sequence of zoom candidates spaced logarithmically.
///
/// This pure, side-effect-free function isolates the coordinate scaling mathematics,
/// allowing for unit testing of the zoom intervals independently of the rendering loop.
///
/// # Mathematical Design
///
/// Rather than advancing in linear steps (which would spend too much time sampling wide
/// macro scales and completely miss close-up details), this function uses geometric
/// interpolation (exponential scaling) to map linear index steps evenly across a logarithmic space.
///
/// This provides uniform sampling across eight orders of magnitude:
/// - Minimum zoom limit: 2e-8 (microscopic close-up of intricate filament branches).
/// - Maximum zoom limit: 9.0 (panoramic macro view of the main cardioid).
///
/// For a candidate pool size N (zooms_count) and an index i (z_idx), the scale is computed as:
///
///   base_zoom = min_zoom * (max_zoom / min_zoom)^(i / (N - 1))
///
/// This mathematical approach guarantees:
/// 1. Exact Boundary Alignment: Zoom values are strictly bound to the limits (2e-8 and 9.0)
///    regardless of the randomized candidate pool size.
/// 2. Smooth Spatial Transitions: Eliminates large visual jumps between candidate frames.
pub fn generate_zoom_candidates(zooms_count: usize, rotations_count: usize) -> Vec<(f64, usize)> {
    if zooms_count == 0 || rotations_count == 0 {
        return Vec::new();
    }

    let min_zoom = 2e-8;
    let max_zoom = 9.0;

    let log_ratio: f64 = max_zoom / min_zoom;

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

    for z_idx in 0..zooms_count {
        // Calculate interpolation factor t from 0.0 to 1.0. Handle division by zero safely.
        let t = if zooms_count > 1 {
            (z_idx as f64) / ((zooms_count - 1) as f64)
        } else {
            0.0
        };

        // Logarithmic spacing calculation
        let base_zoom = min_zoom * log_ratio.powf(t);

        for r_idx in 0..rotations_count {
            candidates.push((base_zoom, r_idx));
        }
    }

    candidates
}

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

    #[test]
    fn test_mandelbrot_generation_random() {
        let monitor = Monitor::default();
        let mandelbrot = MandelbrotGenerator::random(&monitor);
        assert!(mandelbrot.config.zoom > 0.0);
        assert_eq!(mandelbrot.preset.effect_name, ProceduralEffect::Mandelbrot);
    }

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

        // Verify total candidates length matches (zooms * rotations)
        assert_eq!(candidates.len(), zooms_count * rotations_count);

        // Verify exact minimum bound (2e-8) at index 0
        let min_value = candidates[0].0;
        assert!((min_value - 2e-8).abs() < 1e-12);

        // Verify exact maximum bound (9.0) at the final index
        let last_idx = candidates.len() - 1;
        let max_value = candidates[last_idx].0;
        assert!((max_value - 9.0).abs() < 1e-12);
    }
}