wallswitch 0.60.5

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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! Nova Julia liquid fractal generator overlay.
//!
//! This module implements the Nova Julia fractal, a formula combining
//! Newton-Raphson root-finding loops with a dynamic Julia-like perturbation constant.
//! It produces fluid, organic, plume-like structures resembling liquid metal, glowing
//! plasma currents, and detailed biological lattices.

use crate::effects::{
    MAX_ITERATIONS, MIN_ITERATIONS, Viewport, ViewportSpecs, blend_and_vignette_pixel,
    get_rotation_steps, partition_rows, rotate_point,
};
use crate::{
    Complex, ImageEffect, NEON_PALETTES, NeonColor, WallSwitchError, WallSwitchResult,
    get_random_integer,
};
use image::RgbImage;
use std::{io::Error, path::Path, thread};

/// Valid operational range for randomized zoom viewport allocation.
const ZOOM_RANGE: [f64; 2] = [1.2, 3.2];

/// Structural parameters governing the Nova fluid dynamics.
///
/// These parameters define the polynomial power, the relaxation factor `r`,
/// and the perturbation constant `c` that shape the boundaries of the fractal.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NovaPreset {
    /// The integer exponent `p` in the polynomial formula $z^p - 1$.
    pub power: u32,
    /// The relaxation factor $R$ represented as a complex scalar or vector coordinate.
    pub r: Complex,
    /// The perturbation constant $c$ added at each iteration step.
    pub c: Complex,
    /// The user-friendly identifier name of the preset.
    pub name: &'static str,
}

impl ImageEffect for NovaGenerator {
    /// Applies the Nova Julia procedural overlay onto an in-memory image buffer.
    fn apply(&self, rgb_img: &mut RgbImage) {
        self.apply_effect_in_memory(rgb_img);
    }

    /// Returns formatting diagnostic information about the active generator.
    fn info(&self) -> String {
        format!(
            "fractal [{}]\n\
            f(z) = z^{} - 1 = 0, where c = {:6.3} {} {:5.3}i (iter = {:4}, zoom = {:.2}), color: {}",
            self.preset.name,
            self.preset.power,
            self.preset.c.re,
            if self.preset.c.im >= 0.0 { "+" } else { "-" },
            self.preset.c.im.abs(),
            self.scan_iterations,
            self.zoom,
            self.color_palette
        )
    }
}

/// A procedural generator for rendering Nova Julia fractals onto desktop backgrounds.
///
/// Groups coordinate presets, relaxation parameters, camera variables, and color tables
/// into a structured rendering pipeline.
pub struct NovaGenerator {
    /// The active parameters defining the shape and behavior of the fractal.
    pub preset: NovaPreset,
    /// The maximum iteration limit for escape-time calculations.
    pub scan_iterations: u32,
    /// The base color palette selected for the neon glow.
    pub color_palette: NeonColor,
    /// The viewport zoom level.
    pub zoom: f64,
    /// The cosine of the rotation angle.
    pub cos_angle: f64,
    /// The sine of the rotation angle.
    pub sin_angle: f64,
}

impl Default for NovaGenerator {
    /// Returns the default fallback instance of the Nova Julia generator.
    fn default() -> Self {
        Self {
            preset: NovaPreset {
                power: 3,
                r: Complex::new(1.0, 0.0),
                c: Complex::new(0.1, 0.15),
                name: "Liquid Mercury Flow",
            },
            scan_iterations: get_random_integer::<_, u32>(MIN_ITERATIONS / 12, MAX_ITERATIONS / 12)
                .max(50),
            color_palette: NEON_PALETTES[0],
            zoom: 1.8,
            cos_angle: 1.0,
            sin_angle: 0.0,
        }
    }
}

impl NovaGenerator {
    /// Generates a randomized Nova Julia configuration fitted to monitor proportions.
    ///
    /// Selects one of the built-in presets, assigns a neon color palette,
    /// rotates the coordinate system randomly, and optimizes the viewport fit.
    pub fn random(monitor: &crate::Monitor) -> Self {
        let width = monitor.resolution.width as u32;
        let height = monitor.resolution.height as u32;

        let presets = [
            // --- Classical Symmetric Presets ---
            NovaPreset {
                power: 3,
                r: Complex::new(1.0, 0.0),
                c: Complex::new(0.10, 0.15),
                name: "Liquid Mercury Flow",
            },
            NovaPreset {
                power: 3,
                r: Complex::new(1.0, 0.0),
                c: Complex::new(-0.20, 0.45),
                name: "Cosmic Plasma Flare",
            },
            NovaPreset {
                power: 4,
                r: Complex::new(1.0, 0.0),
                c: Complex::new(0.22, 0.10),
                name: "Ornate Coral Filigree",
            },
            NovaPreset {
                power: 3,
                r: Complex::new(0.9, 0.0),
                c: Complex::new(-0.35, 0.25),
                name: "Nebulous Dust Whispers",
            },
            NovaPreset {
                power: 4,
                r: Complex::new(1.0, 0.0),
                c: Complex::new(-0.10, 0.35),
                name: "Gilded Lace Tapestry",
            },
            NovaPreset {
                power: 5,
                r: Complex::new(1.0, 0.0),
                c: Complex::new(-0.05, 0.55),
                name: "Glacial Frost Lattice",
            },
            NovaPreset {
                power: 3,
                r: Complex::new(1.15, 0.0),
                c: Complex::new(0.0, 0.12),
                name: "Spiritual Mandala Ripple",
            },
            NovaPreset {
                power: 4,
                r: Complex::new(0.8, 0.0),
                c: Complex::new(0.30, -0.20),
                name: "Bioluminescent Spore Nest",
            },
            NovaPreset {
                power: 3,
                r: Complex::new(1.0, 0.0),
                c: Complex::new(0.18, -0.40),
                name: "Abyssal Trench Vines",
            },
            NovaPreset {
                power: 6,
                r: Complex::new(1.0, 0.0),
                c: Complex::new(-0.15, 0.15),
                name: "Hyperdimensional Loom",
            },
            // --- Asymmetric & Complex-Relaxed (Spiraling) Presets ---
            NovaPreset {
                power: 3,
                r: Complex::new(1.0, 0.15),
                c: Complex::new(-0.15, 0.35),
                name: "Gothic Cathedral Rose",
            },
            NovaPreset {
                power: 5,
                r: Complex::new(0.85, 0.25),
                c: Complex::new(0.25, 0.05),
                name: "Quantum Foam Fluctuation",
            },
            NovaPreset {
                power: 4,
                r: Complex::new(1.2, -0.10),
                c: Complex::new(-0.28, -0.28),
                name: "Stellar Nucleosynthesis",
            },
            NovaPreset {
                power: 6,
                r: Complex::new(0.95, 0.05),
                c: Complex::new(0.05, 0.42),
                name: "Emerald Moss Labyrinth",
            },
            NovaPreset {
                power: 7,
                r: Complex::new(1.0, 0.0),
                c: Complex::new(-0.08, 0.38),
                name: "Bismuth Crystal Citadel",
            },
            NovaPreset {
                power: 3,
                r: Complex::new(0.75, -0.30),
                c: Complex::new(0.32, 0.18),
                name: "Astral Jellyfish Canopy",
            },
            NovaPreset {
                power: 4,
                r: Complex::new(1.1, 0.15),
                c: Complex::new(-0.45, 0.10),
                name: "Solar Prominence Loops",
            },
            NovaPreset {
                power: 5,
                r: Complex::new(0.9, -0.20),
                c: Complex::new(-0.12, -0.32),
                name: "Aetheric Ley Line Matrix",
            },
            NovaPreset {
                power: 8,
                r: Complex::new(1.05, 0.10),
                c: Complex::new(0.15, 0.15),
                name: "Phytoplankton Radiance",
            },
            NovaPreset {
                power: 6,
                r: Complex::new(0.8, 0.40),
                c: Complex::new(-0.22, 0.22),
                name: "Chronos Vortex Gear",
            },
            NovaPreset {
                power: 5,
                r: Complex::new(1.0, 0.3),
                c: Complex::new(-0.18, 0.12),
                name: "Aeon Temple Portico",
            },
            NovaPreset {
                power: 8,
                r: Complex::new(0.9, -0.15),
                c: Complex::new(0.20, 0.35),
                name: "Hyperborean Crown",
            },
            NovaPreset {
                power: 3,
                r: Complex::new(1.1, 0.45),
                c: Complex::new(-0.33, -0.05),
                name: "Abyssal Nautilus Shell",
            },
            NovaPreset {
                power: 4,
                r: Complex::new(0.7, 0.5),
                c: Complex::new(0.15, -0.55),
                name: "Spectral Dragon Spine",
            },
            NovaPreset {
                power: 3,
                r: Complex::new(1.3, -0.2),
                c: Complex::new(0.25, 0.25),
                name: "Opalescent Silk Ribbons",
            },
            NovaPreset {
                power: 5,
                r: Complex::new(1.0, -0.4),
                c: Complex::new(-0.42, 0.18),
                name: "Phoenix Heart Nebula",
            },
            NovaPreset {
                power: 7,
                r: Complex::new(0.85, 0.1),
                c: Complex::new(0.30, -0.30),
                name: "Crystalline Geode Valley",
            },
            NovaPreset {
                power: 6,
                r: Complex::new(1.15, -0.3),
                c: Complex::new(-0.02, 0.48),
                name: "Eldritch Eye Lattice",
            },
            NovaPreset {
                power: 4,
                r: Complex::new(0.9, 0.35),
                c: Complex::new(-0.25, 0.30),
                name: "Prismatic Quantum Lattice",
            },
            NovaPreset {
                power: 9,
                r: Complex::new(1.0, 0.25),
                c: Complex::new(0.08, -0.28),
                name: "Void Weaver Spindle",
            },
        ];

        let p_idx: usize = get_random_integer(0, NEON_PALETTES.len() - 1);
        let color_palette = NEON_PALETTES[p_idx];

        let angle_degrees: f64 = get_random_integer(0, 359);
        let radians = angle_degrees.to_radians();

        let preset_idx: usize = get_random_integer(0, presets.len() - 1);
        let selected_preset = presets[preset_idx];

        let mut nova = Self {
            preset: selected_preset,
            scan_iterations: get_random_integer(40, 80),
            color_palette,
            zoom: 1.8,
            cos_angle: radians.cos(),
            sin_angle: radians.sin(),
        };

        nova.optimize_fit(width, height);
        nova
    }

    /// Automatically aligns viewport dimensions to frame the central fluid core.
    ///
    /// Scans a grid over the complex coordinates and finds a balanced zoom factor.
    pub fn optimize_fit(&mut self, width: u32, height: u32) {
        let w_f = width as f64;
        let h_f = height as f64;
        let min_dim = w_f.min(h_f);

        let search_limit = 1.6_f64;
        let steps = 64;
        let inv_steps_minus_1 = 1.0 / (steps - 1) as f64;
        let range = 2.0 * search_limit;

        let scan_iterations = self.scan_iterations;
        let mut active_points = Vec::with_capacity(steps * steps);

        for step_y in 0..steps {
            let ry = -search_limit + (step_y as f64 * inv_steps_minus_1) * range;
            for step_x in 0..steps {
                let rx = -search_limit + (step_x as f64 * inv_steps_minus_1) * range;

                let (i, _, _) = compute_nova_escape(
                    rx,
                    ry,
                    self.preset.power,
                    self.preset.r,
                    self.preset.c,
                    scan_iterations,
                );

                // Use a higher iteration threshold to filter out thin outer noise filaments
                if i > 6 && i < scan_iterations - 2 {
                    active_points.push((rx, ry));
                }
            }
        }

        if !active_points.is_empty() {
            let mut best_zoom = f64::MAX;
            let mut best_cos = self.cos_angle;
            let mut best_sin = self.sin_angle;

            for (_rad, cos_t, sin_t) in get_rotation_steps() {
                let mut max_cx_abs = 0.0_f64;
                let mut max_cy_abs = 0.0_f64;

                for &(rx, ry) in &active_points {
                    let (cx, cy) = rotate_point(rx, ry, cos_t, sin_t);
                    max_cx_abs = max_cx_abs.max(cx.abs());
                    max_cy_abs = max_cy_abs.max(cy.abs());
                }

                let zoom_x = 2.0 * max_cx_abs * min_dim / w_f;
                let zoom_y = 2.0 * max_cy_abs * min_dim / h_f;
                let required_zoom = zoom_x.max(zoom_y);

                if required_zoom < best_zoom {
                    best_zoom = required_zoom;
                    best_cos = cos_t;
                    best_sin = sin_t;
                }
            }

            // Introduce a randomized scaling multiplier between 90% and 135%
            let rand_factor = get_random_integer::<_, f64>(90, 135) / 100.0;
            self.zoom = (best_zoom * rand_factor).clamp(ZOOM_RANGE[0], ZOOM_RANGE[1]);
            self.cos_angle = best_cos;
            self.sin_angle = best_sin;
        } else {
            // Roll a flat random zoom within the bounded range if no points detected
            let flat_rand = get_random_integer::<_, f64>(130, 280) / 100.0;
            self.zoom = flat_rand.clamp(ZOOM_RANGE[0], ZOOM_RANGE[1]);
        }
    }

    /// Renders the Nova Julia Set in-place over the active background memory buffer.
    pub fn apply_effect_in_memory(&self, rgb_img: &mut RgbImage) {
        let (width, height) = rgb_img.dimensions();
        let w_f = width as f64;
        let h_f = height as f64;

        let specs = ViewportSpecs {
            center: Complex::new(0.0, 0.0),
            zoom: self.zoom,
            cos_angle: self.cos_angle,
            sin_angle: self.sin_angle,
            is_julia: true,
        };
        let viewport = Viewport::new(w_f, h_f, &specs);

        let scan_iterations = self.scan_iterations;
        let power = self.preset.power;
        let r = self.preset.r;
        let c = self.preset.c;

        let (mut rows, width_usize) = partition_rows(rgb_img);

        let cores = thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(4);
        let chunk_size = (rows.len() / cores).max(1);

        thread::scope(|scope| {
            let viewport_ref = &viewport;
            let color_palette = self.color_palette.to_array();
            for chunk in rows.chunks_mut(chunk_size) {
                scope.spawn(move || {
                    for (y, row_data) in chunk.iter_mut() {
                        let y_f = *y as f64;
                        for x in 0..width_usize {
                            let x_f = x as f64;
                            let z_init = viewport_ref.map(x_f, y_f);

                            let (i, diff_norm, z_final) = compute_nova_escape(
                                z_init.re,
                                z_init.im,
                                power,
                                r,
                                c,
                                scan_iterations,
                            );

                            let smooth_i = if i < scan_iterations {
                                i as f32
                                    + (diff_norm.ln() as f32 / (1e-5_f64).ln() as f32)
                                        .clamp(0.0, 1.0)
                            } else {
                                scan_iterations as f32
                            };

                            let (fractal_rgb, alpha, s_alpha) = if i < scan_iterations {
                                let rad_distance =
                                    (z_init.re * z_init.re + z_init.im * z_init.im).sqrt() as f32;
                                // Expanded active framing border to preserve delicate outer structures
                                let edge_fade =
                                    (1.0 - (rad_distance / 1.8)).clamp(0.0, 1.0).powf(1.2);

                                let ripple_frequency = 0.50_f32;
                                let raw_wave = (smooth_i * ripple_frequency * std::f32::consts::PI)
                                    .sin()
                                    .abs();

                                // Sharpen the wave scaling to narrow down ambient blur zones
                                let norm_dist = raw_wave.powf(2.5);

                                // Sharpen core alignment boundary thresholds
                                let core = if norm_dist > 0.92 {
                                    (norm_dist - 0.92) / 0.08
                                } else {
                                    0.0
                                };

                                // Restrict outer glow falloffs to eliminate muddy or hazy halo overlap
                                let glow = norm_dist.powi(6) * 0.52;
                                let profile = core * 0.78 + glow * 0.22;

                                // Sharpen background shadow depth projection
                                let shadow_profile = (1.0 - norm_dist).powi(3) * 0.48;

                                let angle = z_final.im.atan2(z_final.re) as f32;
                                let light = 0.75_f32 + 0.25_f32 * (angle * 4.0).cos().abs();

                                let t_cycled = (smooth_i * 0.08) % 1.0;
                                let secondary_color =
                                    [color_palette[1], color_palette[2], color_palette[0]];

                                // Interpolate color cycles using a non-linear cosine curve
                                // to completely avoid flat gray or muddy mid-tones
                                let t_cos = (t_cycled * std::f32::consts::PI).cos() * 0.5 + 0.5;

                                let r_grad =
                                    color_palette[0] * t_cos + secondary_color[0] * (1.0 - t_cos);
                                let g_grad =
                                    color_palette[1] * t_cos + secondary_color[1] * (1.0 - t_cos);
                                let b_grad =
                                    color_palette[2] * t_cos + secondary_color[2] * (1.0 - t_cos);

                                let core_color = [r_grad, g_grad, b_grad];

                                // Enforce high contrast complementary borders
                                let mut border_color = [1.0 - r_grad, 1.0 - g_grad, 1.0 - b_grad];
                                let max_val =
                                    border_color[0].max(border_color[1]).max(border_color[2]);
                                if max_val > 0.0 {
                                    border_color[0] /= max_val;
                                    border_color[1] /= max_val;
                                    border_color[2] /= max_val;
                                }

                                // Apply tightened mathematical blending borders
                                let color_blend = norm_dist.powf(3.0);
                                let r_blended = core_color[0] * color_blend
                                    + border_color[0] * (1.0 - color_blend);
                                let g_blended = core_color[1] * color_blend
                                    + border_color[1] * (1.0 - color_blend);
                                let b_blended = core_color[2] * color_blend
                                    + border_color[2] * (1.0 - color_blend);

                                // Raised brightness scaling to achieve bright, vivid neon results
                                let brightness_boost = 1.45_f32;

                                let rgb = [
                                    (r_blended * light * brightness_boost).clamp(0.0, 1.0),
                                    (g_blended * light * brightness_boost).clamp(0.0, 1.0),
                                    (b_blended * light * brightness_boost).clamp(0.0, 1.0),
                                ];

                                let iteration_fade = if i < 6 { i as f32 / 6.0 } else { 1.0 };

                                (
                                    rgb,
                                    profile * 0.95 * iteration_fade * edge_fade,
                                    shadow_profile * iteration_fade * edge_fade,
                                )
                            } else {
                                ([0.0, 0.0, 0.0], 0.0, 0.0)
                            };

                            let idx = x * 3;
                            blend_and_vignette_pixel(row_data, idx, fractal_rgb, alpha, s_alpha);
                        }
                    }
                });
            }
        });
    }

    /// Process, render, and write output files directly to system storage.
    pub fn apply_effect<P: AsRef<Path>>(
        &self,
        input_path: P,
        output_path: P,
    ) -> WallSwitchResult<()> {
        let img = image::open(&input_path)
            .map_err(|e| WallSwitchError::UnableToFind(format!("Failed to open image: {e}")))?;

        let mut rgb_img = img.to_rgb8();
        self.apply_effect_in_memory(&mut rgb_img);

        rgb_img
            .save(&output_path)
            .map_err(|e| WallSwitchError::Io(Error::other(e)))?;

        Ok(())
    }
}

// ==============================================================================
// MATH ENGINE: NOVA JULIA CONVERGENCE LOOP
// ==============================================================================

/// Evaluates fluid convergence under the Nova-Julia recurrence relation.
///
/// Recurrence: z(n+1) = z(n) - R * (z(n)^p - 1) / (p * z(n)^(p-1)) + c
#[inline(always)]
fn compute_nova_escape(
    rx: f64,
    ry: f64,
    power: u32,
    r: Complex,
    c: Complex,
    scan_iterations: u32,
) -> (u32, f64, Complex) {
    let mut z = Complex::new(rx, ry);
    let p_f = power as f64;

    let mut i = 0;
    let mut diff_norm = 1.0;

    while i < scan_iterations {
        let z_norm_sq = z.norm_sq();
        if z_norm_sq < 1e-6 {
            break;
        }
        if z_norm_sq > 100.0 {
            break;
        }

        let z_prev_p_minus_1 = z.pow(power - 1);
        let z_p = z_prev_p_minus_1 * z;

        // f(z) = z^p - 1
        let f_z = z_p - Complex::new(1.0, 0.0);

        // f'(z) = p * z^(p-1)
        let f_prime_z = z_prev_p_minus_1 * p_f;

        // step = R * f(z) / f'(z)
        let step = r * (f_z / f_prime_z);

        // z_{n+1} = z_n - step + c
        let z_next = z - step + c;

        // True Cauchy successive term distance: |z_{n+1} - z_n|^2
        let diff = z_next - z;
        diff_norm = diff.norm_sq();

        if diff_norm < 1e-5 {
            z = z_next;
            break;
        }

        z = z_next;
        i += 1;
    }

    (i, diff_norm, z)
}