wallswitch 0.60.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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
use crate::{WallSwitchError, WallSwitchResult, get_random_integer};
use clap::ValueEnum;
use image::RgbImage;
use serde::{Deserialize, Serialize};
use std::{io::Error, path::Path, thread};

/// Represents the supported procedural background overlay effects.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
#[serde(rename_all = "lowercase")]
#[derive(Default)]
pub enum ProceduralEffect {
    /// No overlay effect is applied; displays the raw wallpaper.
    #[value(name = "none")]
    #[default]
    None,

    /// Julia Set fractal overlay.
    /// Generator function: f(z) = z^2 + c, where c is a fixed constant and the initial z varies.
    #[value(name = "julia")]
    JuliaSet,

    /// Mandelbrot Set fractal overlay.
    /// Generator function: f(z) = z^2 + c, where the initial z is zero and c varies.
    #[value(name = "mandelbrot")]
    Mandelbrot,

    /// Procedural Starfield / Bokeh generator.
    /// Renders organic circular glowing stars using soft Gaussian falloffs.
    #[value(name = "star")]
    Starfield,

    /// Procedural Cosmic Aurora wave generator.
    /// Generates glowing atmospheric filaments using high-contrast wave math.
    #[value(name = "aurora")]
    CosmicAurora,

    /// Randomly selects between Julia Sets or Mandelbrot Set overlays.
    #[value(name = "fractal")]
    Fractal,

    /// Randomly selects one of the active procedural overlays independently.
    #[value(name = "random")]
    Random,
}

impl ProceduralEffect {
    /// Returns the user-friendly display name of the active effect.
    pub fn get_name(self) -> &'static str {
        match self {
            Self::None => "None",
            Self::JuliaSet => "Julia Sets",
            Self::Mandelbrot => "Mandelbrot",
            Self::Starfield => "Starfield",
            Self::CosmicAurora => "Cosmic Aurora",
            Self::Fractal => "Fractal",
            Self::Random => "Random",
        }
    }

    /// Resolves the effect to a concrete rendering variant (resolving Random or Fractal if selected).
    pub fn resolve(self) -> Self {
        match self {
            Self::Random => match get_random_integer(0, 3) {
                0 => Self::JuliaSet,
                1 => Self::Starfield,
                2 => Self::CosmicAurora,
                _ => Self::Mandelbrot,
            },
            Self::Fractal => match get_random_integer(0, 1) {
                0 => Self::JuliaSet,
                _ => Self::Mandelbrot,
            },
            concrete => concrete,
        }
    }
}

/// Represents the zoom behavior of the active preset coordinate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ZoomMode {
    /// Analytical zoom fitting the entire fractal structure dynamically on screen.
    Full,
    /// Deep-zoom magnification on a high-detail localized coordinate.
    Detail,
}

// ==============================================================================
// SHARED COLOR PALETTES & UTILITY FUNCTIONS (DRY IMPLEMENTATION)
// ==============================================================================

/// High-contrast neon color palettes shared between procedural fractal engines.
const SHARED_NEON_PALETTES: [[f32; 3]; 15] = [
    [1.0, 0.0, 0.8], // Hot Pink / Cyberpunk Magenta
    [0.0, 1.0, 1.0], // Electric Cyan
    [1.0, 0.6, 0.0], // Vivid Orange / Gold
    [0.0, 1.0, 0.2], // Laser Green
    [0.6, 0.0, 1.0], // Deep Neon Violet
    [1.0, 0.1, 0.1], // Vibrant Crimson Red
    [1.0, 1.0, 0.0], // Radioactive Yellow
    [0.0, 0.4, 1.0], // Cobalt Blue
    [0.5, 1.0, 0.0], // Lime Glow
    [1.0, 0.0, 0.4], // Electric Rose
    [0.0, 1.0, 0.6], // Mint Neon
    [1.0, 0.4, 0.4], // Soft Coral Flame
    [0.9, 0.9, 1.0], // Bright Starlight White
    [1.0, 0.8, 0.0], // Amber Glow
    [0.4, 0.0, 0.8], // Electric Indigo
];

/// Partitions an RGB image buffer into mutable row segments for thread-safe parallel processing.
fn partition_rows(rgb_img: &mut RgbImage) -> (Vec<(usize, &mut [u8])>, usize) {
    let (width, _) = rgb_img.dimensions();
    let width_usize = width as usize;
    let row_stride = width_usize * 3;
    let pixels_buffer = rgb_img.as_mut();

    let rows: Vec<(usize, &mut [u8])> = pixels_buffer
        .chunks_exact_mut(row_stride)
        .enumerate()
        .collect();

    (rows, width_usize)
}

/// Calculates the continuous potential (smooth coloring) value for quadratic escape-time fractals.
/// This interpolates colors continuously to prevent banding artifacts.
#[inline]
fn calculate_smooth_potential(i: u32, max_iterations: u32, z_re: f32, z_im: f32) -> f32 {
    if i < max_iterations {
        let mag2 = z_re * z_re + z_im * z_im;
        if mag2 > 4.0 {
            let log_zn = mag2.ln() * 0.5;
            let nu = (log_zn * std::f32::consts::LOG2_E).ln() * std::f32::consts::LOG2_E;
            let smooth_i = (i as f32 + 1.0 - nu).max(0.0);
            (smooth_i / max_iterations as f32).clamp(0.0, 1.0)
        } else {
            i as f32 / max_iterations as f32
        }
    } else {
        1.0
    }
}

/// Linearizes sRGB values to perform mathematically correct alpha-blending,
/// preventing the standard dark-boundary artifacts of linear byte blending.
#[inline]
fn blend_channels_gamma(bg: u8, fg: f32, alpha: f32) -> u8 {
    let bg_f = bg as f32 / 255.0;
    let bg_linear = bg_f * bg_f; // Fast gamma = 2.0 approximation

    let fg_f = fg / 255.0;
    let fg_linear = fg_f * fg_f;

    let blended_linear = bg_linear * (1.0 - alpha) + fg_linear * alpha;

    (blended_linear.sqrt() * 255.0).clamp(0.0, 255.0) as u8 // Re-encode to sRGB
}

/// Blends the computed fractal value and vignette shadow onto the active background pixel coordinates.
/// Incorporates contrast-preserving dynamic halo blending to prevent losing detail.
#[inline]
fn blend_and_vignette_pixel(
    row_data: &mut [u8],
    idx: usize,
    t: f32,
    color_palette: [f32; 3],
    dx_vignette: f32,
    dy_vignette_sq: f32,
) {
    let original_r = row_data[idx];
    let original_g = row_data[idx + 1];
    let original_b = row_data[idx + 2];

    // Contrast-Preserving Dynamic Halo Blending (drop shadow under threads)
    let shadow_factor = 1.0 - (t * 0.5);
    let background_r = original_r as f32 * shadow_factor;
    let background_g = original_g as f32 * shadow_factor;
    let background_b = original_b as f32 * shadow_factor;

    let r_fractal = color_palette[0] * t * 255.0;
    let g_fractal = color_palette[1] * t * 255.0;
    let b_fractal = color_palette[2] * t * 255.0;

    let alpha = t.sqrt() * 0.8;

    // Execute sRGB gamma-corrected blending
    let blended_r = blend_channels_gamma(background_r as u8, r_fractal, alpha);
    let blended_g = blend_channels_gamma(background_g as u8, g_fractal, alpha);
    let blended_b = blend_channels_gamma(background_b as u8, b_fractal, alpha);

    // Soft Vignette Calculation
    let dist = (dx_vignette * dx_vignette + dy_vignette_sq).sqrt();
    let vignette = (1.0 - dist * 0.4).clamp(0.1, 1.0);

    row_data[idx] = (blended_r as f32 * vignette).clamp(0.0, 255.0) as u8;
    row_data[idx + 1] = (blended_g as f32 * vignette).clamp(0.0, 255.0) as u8;
    row_data[idx + 2] = (blended_b as f32 * vignette).clamp(0.0, 255.0) as u8;
}

// ==============================================================================
// UNIFIED FRACTAL ITERATION STEPPER (INLINED WORKER)
// ==============================================================================

/// Executes a single mathematical iteration step f(z) based on the target fractal layout.
/// Fully inlined by the compiler for zero overhead in hot loops.
#[inline(always)]
fn iterate_fractal(
    fractal_type: ProceduralEffect,
    z_re: &mut f32,
    z_im: &mut f32,
    c_re: f32,
    c_im: f32,
) {
    let re2 = *z_re * *z_re;
    let im2 = *z_im * *z_im;

    match fractal_type {
        ProceduralEffect::JuliaSet | ProceduralEffect::Mandelbrot => {
            let next_im = 2.0 * *z_re * *z_im + c_im;
            *z_re = re2 - im2 + c_re;
            *z_im = next_im;
        }
        _ => {}
    }
}

// ==============================================================================
// UNIFIED FRACTAL GENERATION ENGINE (DRY MODEL)
// ==============================================================================

/// Unified Fractal Generator and Image Post-Processor.
/// Orchestrates parameters, enframe fittings, and multi-threaded rendering sweeps for Julia and Mandelbrot.
pub struct FractalGenerator {
    /// Active rendering model type.
    pub fractal_type: ProceduralEffect,
    /// Real component of complex center coordinate (c / viewport center).
    pub center_re: f32,
    /// Imaginary component of complex center coordinate (c / viewport center).
    pub center_im: f32,
    /// Minimum recursion iterations before determining convergence.
    pub min_iterations: u32,
    /// Maximum recursion iterations before determining convergence.
    pub max_iterations: u32,
    /// Precalculated random iteration threshold for the active render cycle.
    pub scan_iterations: u32,
    /// RGB multipliers to tint the fractal intensity.
    pub color_palette: [f32; 3],
    /// Scaling parameter representing the viewport width in complex coordinates.
    pub zoom: f32,
    /// Precalculated cosine of the random rotation angle.
    pub cos_angle: f32,
    /// Precalculated sine of the random rotation angle.
    pub sin_angle: f32,
    /// Scaling and centering mapping behavior.
    pub zoom_mode: ZoomMode,
}

impl Default for FractalGenerator {
    fn default() -> Self {
        let min_it = 250;
        let max_it = 500;
        Self {
            fractal_type: ProceduralEffect::JuliaSet,
            center_re: -0.7,
            center_im: 0.27015,
            min_iterations: min_it,
            max_iterations: max_it,
            scan_iterations: get_random_integer(min_it, max_it) as u32,
            color_palette: [0.0, 1.0, 1.0], // Default Neon Cyan
            zoom: 3.0,
            cos_angle: 1.0, // 0 degrees rotation
            sin_angle: 0.0,
            zoom_mode: ZoomMode::Full,
        }
    }
}

impl FractalGenerator {
    /// Creates a FractalGenerator with randomized aesthetic constants,
    /// target enframe behaviors, rotation parameters, and bounds matching the target configuration.
    pub fn random(effect: ProceduralEffect) -> Self {
        let fractal_type = match effect {
            ProceduralEffect::Random => match get_random_integer(0, 1) {
                0 => ProceduralEffect::JuliaSet,
                _ => ProceduralEffect::Mandelbrot,
            },
            concrete => concrete,
        };

        let mut center_re = 0.0_f32;
        let mut center_im = 0.0_f32;
        let mut min_iterations = 250;
        let mut max_iterations = 500;
        let mut zoom = 3.0_f32;
        let mut zoom_mode = ZoomMode::Detail;

        match fractal_type {
            ProceduralEffect::JuliaSet => {
                let presets = [
                    (-0.7, 0.27015),     // Classic dendrite
                    (-0.4, 0.6),         // Classic cloud swirls
                    (-0.8, 0.156),       // Detailed spirals
                    (-0.7269, 0.1889),   // Lace structures
                    (-0.75, 0.11),       // Feathery branches
                    (-0.1, 0.651),       // Cosmic dust style
                    (-0.70176, -0.3842), // Dragon-like curves (San Marco fractal boundary)
                    (0.355, 0.355),      // Spiral galaxy arms
                    (-0.4, -0.59),       // Swirling vortexes
                    (-0.54, 0.54),       // Ornamental lace borders
                    (-0.74543, 0.11301), // Dense filigree patterns
                    (-0.835, -0.2321),   // Lightning rods
                    (-0.77269, 0.12428), // Coral reefs
                    (-0.51251, 0.5213),  // Fine lace filaments
                    (0.4, 0.4),          // Symmetric stellar crowns (fine dust)
                    (-0.55, 0.55),       // Intricate leaf outlines
                    (-0.624, 0.435),     // Crystalline snowflake patterns
                    (-0.162, 1.04),      // Towering minarets
                    (-0.12, 0.85),       // Flowing plasma plumes
                    (-0.742, 0.1345),    // Intricate branching nodes
                    (-0.391, -0.587),    // Swirling storm clouds
                    (0.0, 0.8),          // Classic symmetric dendritic structure
                    (-0.73, 0.21),       // Feathery dendritic lace
                    (-0.81, 0.2),        // Spiral galaxy filaments
                    (-0.68, 0.34),       // Delicate coral spirals
                    (-0.11, 0.83),       // Plasma tendrils
                    (-0.76, 0.08),       // Lightning tree branches
                    (-0.72, 0.22),       // Dendritic pine branches
                ];
                let c_idx = get_random_integer(0, (presets.len() - 1) as u64) as usize;
                let (cre, cim) = presets[c_idx];
                center_re = cre;
                center_im = cim;
                zoom = get_random_integer(250, 400) as f32 / 100.0;
                zoom_mode = ZoomMode::Full;
            }
            ProceduralEffect::Mandelbrot => {
                // Highly aesthetic coordinates from Mandelbrot set
                let presets = [
                    (-0.5623, 0.6421, 450.0, ZoomMode::Detail), // Filament branch patterns
                    (-0.7756838, 0.13646737, 850.0, ZoomMode::Detail), // Seahorse tail section
                    (-1.25066, 0.02012, 900.0, ZoomMode::Detail), // Dendritic filaments and double branches
                    (-0.748, 0.124, 350.0, ZoomMode::Detail), // Extreme secondary branches of the Seahorse Valley
                    (-0.7436438, 0.1318259, 1200.0, ZoomMode::Detail), // Deep double spirals in Seahorse Valley
                    (-0.7431, 0.1319, 1000.0, ZoomMode::Detail),       // Seahorse Valley detail A
                    (-0.7432, 0.1320, 1000.0, ZoomMode::Detail),       // Seahorse Valley detail B
                    (-0.7433, 0.1321, 1000.0, ZoomMode::Detail),       // Seahorse Valley detail C
                    (-0.7434, 0.1322, 1000.0, ZoomMode::Detail),       // Seahorse Valley detail D
                    (-0.7434, 0.1323, 1000.0, ZoomMode::Detail),       // Seahorse Valley detail E
                    (-0.7435, 0.1324, 1000.0, ZoomMode::Detail),       // Seahorse Valley detail F
                    (-0.75, 0.10, 300.0, ZoomMode::Detail), // Main entrance of Seahorse Valley
                    (-0.088, 0.654, 650.0, ZoomMode::Detail), // Triple Spiral Valley
                    (0.275, 0.0, 300.0, ZoomMode::Detail),  // Elephant Valley
                ];
                let c_idx = get_random_integer(0, (presets.len() - 1) as u64) as usize;
                let (cre, cim, base_zoom, mode) = presets[c_idx];
                center_re = cre;
                center_im = cim;
                zoom_mode = mode;
                if mode == ZoomMode::Full {
                    zoom = base_zoom;
                } else {
                    // Apply subtle randomized variation to preserve precise details
                    zoom = base_zoom * (get_random_integer(85, 115) as f32 / 100.0);
                }
                min_iterations = 500;
                max_iterations = 900;
            }
            _ => {}
        }

        let p_idx = get_random_integer(0, (SHARED_NEON_PALETTES.len() - 1) as u64) as usize;
        let color_palette = SHARED_NEON_PALETTES[p_idx];

        let scan_iterations = get_random_integer(min_iterations, max_iterations) as u32;
        let angle_degrees = get_random_integer(0, 359) as f32;
        let radians = angle_degrees.to_radians();

        Self {
            fractal_type,
            center_re,
            center_im,
            min_iterations,
            max_iterations,
            scan_iterations,
            color_palette,
            zoom,
            cos_angle: radians.cos(),
            sin_angle: radians.sin(),
            zoom_mode,
        }
    }

    /// Dynamically determines the optimal 45-degree rotation step and zoom factor
    /// to maximize the visual area occupied by the fractal within the target aspect ratio.
    pub fn optimize_fit(&mut self, width: u32, height: u32) {
        let w_f = width as f32;
        let h_f = height as f32;
        let min_dim = w_f.min(h_f);

        // Calculate the theoretical bounding radius based on the mapped coordinates
        let c_abs = (self.center_re * self.center_re + self.center_im * self.center_im).sqrt();
        let r_bound = (1.0 + (1.0 + 4.0 * c_abs).sqrt()) / 2.0;
        let search_limit = r_bound * 1.2;

        // Perform a single lightweight pre-scan in unrotated complex space
        let steps = 40; // 40x40 grid is highly efficient and sufficient for fitting
        let inv_steps_minus_1 = 1.0 / (steps - 1) as f32;
        let range = 2.0 * search_limit;

        let scan_iterations = self.scan_iterations;

        let mut active_points = Vec::with_capacity(steps * steps / 2);

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

                // Configure start state depending on whether the fractal is Julia (fixed c) or Mandelbrot-based (varying c)
                let (mut z_re, mut z_im, c_re, c_im) = match self.fractal_type {
                    ProceduralEffect::JuliaSet => (rx, ry, self.center_re, self.center_im),
                    ProceduralEffect::Mandelbrot => (0.0, 0.0, rx, ry),
                    ProceduralEffect::None
                    | ProceduralEffect::Starfield
                    | ProceduralEffect::CosmicAurora
                    | ProceduralEffect::Fractal
                    | ProceduralEffect::Random => (0.0, 0.0, 0.0, 0.0),
                };

                let mut i = 0;
                while i < scan_iterations {
                    let re2 = z_re * z_re;
                    let im2 = z_im * z_im;
                    if re2 + im2 > 4.0 {
                        break;
                    }
                    iterate_fractal(self.fractal_type, &mut z_re, &mut z_im, c_re, c_im);
                    i += 1;
                }

                // Collect points that lie on the active boundary of the fractal
                if i > 3 && i < scan_iterations {
                    active_points.push((rx, ry));
                }
            }
        }

        // Find the rotation step (from 0 to 315 deg) that maximizes visual coverage
        if !active_points.is_empty() {
            let mut best_zoom = f32::MAX;
            let mut best_cos = self.cos_angle;
            let mut best_sin = self.sin_angle;

            // Check 8 structural rotation angles (45-degree increments)
            for angle_step in 0..8 {
                let angle_deg = (angle_step * 45) as f32;
                let rad = angle_deg.to_radians();
                let cos_t = rad.cos();
                let sin_t = rad.sin();

                let mut max_cx_abs = 0.0_f32;
                let mut max_cy_abs = 0.0_f32;

                // Project pre-scanned points back to screen space using inverse rotation
                for &(rx, ry) in &active_points {
                    let cx = rx * cos_t + ry * sin_t;
                    let cy = -rx * sin_t + ry * cos_t;

                    max_cx_abs = max_cx_abs.max(cx.abs());
                    max_cy_abs = max_cy_abs.max(cy.abs());
                }

                // Find zoom bounds for both dimensions
                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);

                // A smaller zoom scale means the camera can get closer, maximizing screen coverage
                if required_zoom < best_zoom {
                    best_zoom = required_zoom;
                    best_cos = cos_t;
                    best_sin = sin_t;
                }
            }

            self.zoom = best_zoom * 1.10; // 10% padding margin to prevent edge clipping
            self.cos_angle = best_cos;
            self.sin_angle = best_sin;
        } else {
            // Fallback to safe default bounds if no active structure is scanned
            self.zoom = 2.0 * r_bound * 1.10;
        }
    }

    /// Applies the chosen fractal pattern and vignette blending directly on an in-memory RgbImage in parallel.
    pub fn apply_effect_in_memory(&mut self, rgb_img: &mut RgbImage) {
        let (width, height) = rgb_img.dimensions();

        // Analytical bounding-box fitting for full/macro views
        if self.zoom_mode == ZoomMode::Full {
            self.optimize_fit(width, height);
        }

        let w_f = width as f32;
        let h_f = height as f32;
        let min_dim = w_f.min(h_f);

        // Calculate scaling factor depending on ZoomMode
        let scale = match self.zoom_mode {
            ZoomMode::Full => self.zoom / min_dim,
            ZoomMode::Detail => (3.0 / self.zoom) / min_dim,
        };

        let cos_angle = self.cos_angle;
        let sin_angle = self.sin_angle;
        let center_re = self.center_re;
        let center_im = self.center_im;

        let scan_iterations = self.scan_iterations;
        let color_palette = self.color_palette;
        let fractal_type = self.fractal_type;

        // Partition flat pixel data into a structured vector of mutable row references
        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);

        // Precalculate coordinate scaling & rotation steps
        let cx_off = w_f / 2.0;
        let cy_off = h_f / 2.0;

        let dx_re = scale * cos_angle;
        let dx_im = scale * sin_angle;
        let dy_re = -scale * sin_angle;
        let dy_im = scale * cos_angle;

        // Map viewport center depending on the ZoomMode
        let (v_center_re, v_center_im) = match self.zoom_mode {
            ZoomMode::Full => (0.0, 0.0),
            ZoomMode::Detail => (center_re, center_im),
        };

        // Incorporate the center offsets into the initial coordinate bounds
        let start_re = v_center_re - cx_off * dx_re - cy_off * dy_re;
        let start_im = v_center_im - cx_off * dx_im - cy_off * dy_im;

        // Precalculate vignette and math constants
        let inv_half_w = 2.0 / w_f;
        let inv_half_h = 2.0 / h_f;

        thread::scope(|scope| {
            for chunk in rows.chunks_mut(chunk_size) {
                scope.spawn(|| {
                    for (y, row_data) in chunk.iter_mut() {
                        let y_f = *y as f32;

                        let rx_row = start_re + y_f * dy_re;
                        let ry_row = start_im + y_f * dy_im;

                        let dy_vignette = y_f * inv_half_h - 1.0;
                        let dy_vignette_sq = dy_vignette * dy_vignette;

                        for x in 0..width_usize {
                            let x_f = x as f32;

                            // Direct coordinate mapping with precalculated rotation & scale steps
                            let rx = rx_row + x_f * dx_re;
                            let ry = ry_row + x_f * dx_im;

                            // Configure start state depending on whether the fractal is Julia (fixed c) or Mandelbrot-based (varying c)
                            let (mut z_re, mut z_im, c_re, c_im) = match fractal_type {
                                ProceduralEffect::JuliaSet => (rx, ry, center_re, center_im),
                                ProceduralEffect::Mandelbrot => (0.0, 0.0, rx, ry),
                                ProceduralEffect::None
                                | ProceduralEffect::Starfield
                                | ProceduralEffect::CosmicAurora
                                | ProceduralEffect::Fractal
                                | ProceduralEffect::Random => (0.0, 0.0, 0.0, 0.0),
                            };

                            let mut i = 0;
                            while i < scan_iterations {
                                let re2 = z_re * z_re;
                                let im2 = z_im * z_im;
                                if re2 + im2 > 4.0 {
                                    break;
                                }
                                iterate_fractal(fractal_type, &mut z_re, &mut z_im, c_re, c_im);
                                i += 1;
                            }

                            // Continuous potential smooth coloring formula across selected iteration range
                            let t = calculate_smooth_potential(i, scan_iterations, z_re, z_im);

                            let idx = x * 3;
                            let dx_vignette = x_f * inv_half_w - 1.0;

                            // Apply dynamic halo blending and soft vignette
                            blend_and_vignette_pixel(
                                row_data,
                                idx,
                                t,
                                color_palette,
                                dx_vignette,
                                dy_vignette_sq,
                            );
                        }
                    }
                });
            }
        });
    }

    /// Reads an input image, applies the chosen fractal in parallel, and saves to the output path.
    pub fn apply_effect<P: AsRef<Path>>(
        &mut 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(())
    }
}

// ==============================================================================
// ALTERNATIVE PROCEDURAL OVERLAYS
// ==============================================================================

/// Helper representation of individual stars in a Starfield.
pub struct Star {
    /// Horizontal position.
    pub x: f32,
    /// Vertical position.
    pub y: f32,
    /// Radius of the star.
    pub radius: f32,
    /// RGB color.
    pub color: [f32; 3],
    /// Glow intensity factor.
    pub intensity: f32,
}

/// Cyberpunk Starfield / Bokeh effect generator.
pub struct StarfieldGenerator {
    /// Active star collection.
    pub stars: Vec<Star>,
}

impl StarfieldGenerator {
    /// Generates a randomized list of glowing stars based on target monitor dimension limits.
    pub fn new(count: usize, width: u32, height: u32) -> Self {
        let mut stars = Vec::with_capacity(count);

        let palettes = [
            [1.0, 1.0, 1.0], // White
            [0.6, 0.8, 1.0], // Electric Ice Blue
            [1.0, 0.8, 0.4], // Cosmic Gold
            [1.0, 0.4, 0.8], // Ultraviolet Pink
        ];

        for _ in 0..count {
            let x = get_random_integer(0, width as u64) as f32;
            let y = get_random_integer(0, height as u64) as f32;
            let radius = get_random_integer(5, 45) as f32;
            let intensity = get_random_integer(30, 95) as f32 / 100.0;

            let p_idx = get_random_integer(0, (palettes.len() - 1) as u64) as usize;
            let color = palettes[p_idx];

            stars.push(Star {
                x,
                y,
                radius,
                color,
                intensity,
            });
        }

        Self { stars }
    }

    /// Appends smooth glowing star circles directly onto the image in parallel.
    pub fn apply_effect_in_memory(&self, rgb_img: &mut RgbImage) {
        // Using a soft pastel blue-gray default color for blending to simplify code
        let contrast_color = [0.64, 0.75, 0.85];

        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| {
            for chunk in rows.chunks_mut(chunk_size) {
                let stars = &self.stars;
                scope.spawn(move || {
                    for (y, row_data) in chunk.iter_mut() {
                        let y_f = *y as f32;

                        // Gather active stars vertically overlapping with this row to optimize calculations
                        let mut active_stars = Vec::with_capacity(16);
                        for star in stars {
                            let dy = star.y - y_f;
                            let limit = star.radius * 2.0;
                            if dy.abs() < limit {
                                let dy_sq = dy * dy;
                                let star_radius_sq = star.radius * star.radius;
                                active_stars.push((star, dy_sq, star_radius_sq));
                            }
                        }

                        for x in 0..width_usize {
                            let x_f = x as f32;

                            let mut r_contrib = 0.0;
                            let mut g_contrib = 0.0;
                            let mut b_contrib = 0.0;
                            let mut total_alpha = 0.0;

                            for &(star, dy_sq, star_radius_sq) in &active_stars {
                                let dx = star.x - x_f;
                                let dist_sq = dx * dx + dy_sq;

                                if dist_sq < star_radius_sq * 4.0 {
                                    let factor = (-dist_sq / (2.0 * star_radius_sq)).exp();
                                    let alpha = factor * star.intensity;

                                    let r_star =
                                        (star.color[0] * 0.25 + contrast_color[0] * 0.75) * alpha;
                                    let g_star =
                                        (star.color[1] * 0.25 + contrast_color[1] * 0.75) * alpha;
                                    let b_star =
                                        (star.color[2] * 0.25 + contrast_color[2] * 0.75) * alpha;

                                    r_contrib += r_star;
                                    g_contrib += g_star;
                                    b_contrib += b_star;
                                    total_alpha += alpha;
                                }
                            }

                            if total_alpha > 0.001 {
                                let idx = x * 3;
                                let original_r = row_data[idx] as f32;
                                let original_g = row_data[idx + 1] as f32;
                                let original_b = row_data[idx + 2] as f32;

                                let alpha_clamp = total_alpha.min(0.95);

                                let blended_r = (original_r * (1.0 - alpha_clamp))
                                    + (r_contrib * 255.0 / total_alpha * alpha_clamp);
                                let blended_g = (original_g * (1.0 - alpha_clamp))
                                    + (g_contrib * 255.0 / total_alpha * alpha_clamp);
                                let blended_b = (original_b * (1.0 - alpha_clamp))
                                    + (b_contrib * 255.0 / total_alpha * alpha_clamp);

                                row_data[idx] = blended_r.clamp(0.0, 255.0) as u8;
                                row_data[idx + 1] = blended_g.clamp(0.0, 255.0) as u8;
                                row_data[idx + 2] = blended_b.clamp(0.0, 255.0) as u8;
                            }
                        }
                    }
                });
            }
        });
    }
}

/// Cosmic Aurora overlay generator.
pub struct AuroraGenerator {
    /// Base neon color palette.
    pub color_palette: [f32; 3],
    /// Cosmic wave density factor.
    pub density: f32,
}

impl AuroraGenerator {
    /// Generates a randomized cosmic wave density and color palette configuration.
    pub fn random() -> Self {
        let palettes = [
            [0.2, 1.0, 0.5], // Emerald Green / Aurora Classic
            [0.6, 0.0, 1.0], // Deep Cosmic Violet
            [0.0, 0.8, 1.0], // Neon Ice Teal
            [1.0, 0.0, 0.6], // Solar Flare Pink
        ];
        let idx = get_random_integer(0, (palettes.len() - 1) as u64) as usize;
        let density = get_random_integer(4, 8) as f32;

        Self {
            color_palette: palettes[idx],
            density,
        }
    }

    /// Appends smooth cosmic waves directly onto the image in parallel.
    pub fn apply_effect_in_memory(&self, rgb_img: &mut RgbImage) {
        let (width, height) = rgb_img.dimensions();
        let w_f = width as f32;
        let h_f = height as f32;

        // Using the generator's selected color palette directly to simplify code
        let contrast_color = self.color_palette;

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

        // Precalculate scaling coefficients and row factors to optimize performance
        let inv_w = 1.0 / w_f;
        let inv_h = 1.0 / h_f;
        let density_u = self.density * 1.5 * inv_w;
        let density_v_coeff = self.density * 2.0;
        let density_w_coeff = self.density * inv_w;
        let density_w4_coeff = self.density * 1.2;

        thread::scope(|scope| {
            for chunk in rows.chunks_mut(chunk_size) {
                scope.spawn(move || {
                    for (y, row_data) in chunk.iter_mut() {
                        let y_f = *y as f32;

                        let v = y_f * inv_h;
                        let w2 = (v * density_v_coeff).cos();
                        let v_density = v * self.density;
                        let v_sq = v * v;

                        for x in 0..width_usize {
                            let x_f = x as f32;

                            let u = x_f * inv_w;

                            let w1 = (x_f * density_u).sin();
                            let w3 = (x_f * density_w_coeff + v_density).sin();
                            let w4 = ((u * u + v_sq).sqrt() * density_w4_coeff).cos();

                            let val = (w1 + w2 + w3 + w4) * 0.25;

                            // High-contrast cos-pow3 wave function to generate distinct glow filaments
                            let intensity = (val * std::f32::consts::PI).cos().abs().powf(3.0);

                            let dx = (u - 0.5) * 2.0;
                            let dy = (v - 0.5) * 2.0;
                            let edge_fade =
                                (1.0 - (dx * dx + dy * dy).sqrt() * 0.5).clamp(0.0, 1.0);

                            // Opacity increased to 0.75 to make waves clearly visible
                            let alpha = intensity * edge_fade * 0.75;

                            if alpha > 0.01 {
                                let idx = x * 3;
                                let original_r = row_data[idx] as f32;
                                let original_g = row_data[idx + 1] as f32;
                                let original_b = row_data[idx + 2] as f32;

                                let r_aurora = contrast_color[0] * 255.0;
                                let g_aurora = contrast_color[1] * 255.0;
                                let b_aurora = contrast_color[2] * 255.0;

                                row_data[idx] =
                                    ((original_r * (1.0 - alpha)) + (r_aurora * alpha)) as u8;
                                row_data[idx + 1] =
                                    ((original_g * (1.0 - alpha)) + (g_aurora * alpha)) as u8;
                                row_data[idx + 2] =
                                    ((original_b * (1.0 - alpha)) + (b_aurora * alpha)) as u8;
                            }
                        }
                    }
                });
            }
        });
    }
}