selfware 0.2.2

Your personal AI workshop — software you own, software that lasts
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
//! Particle System
//!
//! General purpose particle system for effects like:
//! - Sparkles
//! - Confetti
//! - Explosions
//! - Ambient effects

use std::sync::atomic::{AtomicU32, Ordering};

use super::{colors, Animation};
use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    widgets::Widget,
};

/// A single particle with position, velocity, and appearance
#[derive(Debug, Clone)]
pub struct Particle {
    /// X position
    pub x: f32,
    /// Y position
    pub y: f32,
    /// X velocity (units per second)
    pub vx: f32,
    /// Y velocity (units per second)
    pub vy: f32,
    /// Particle lifetime remaining (seconds)
    pub lifetime: f32,
    /// Maximum lifetime (for fade calculations)
    pub max_lifetime: f32,
    /// Display symbol
    pub symbol: char,
    /// Particle color
    pub color: Color,
    /// Gravity multiplier (0 = no gravity)
    pub gravity: f32,
}

impl Particle {
    pub fn new(x: f32, y: f32) -> Self {
        Self {
            x,
            y,
            vx: 0.0,
            vy: 0.0,
            lifetime: 1.0,
            max_lifetime: 1.0,
            symbol: '·',
            color: Color::White,
            gravity: 0.0,
        }
    }

    pub fn with_velocity(mut self, vx: f32, vy: f32) -> Self {
        self.vx = vx;
        self.vy = vy;
        self
    }

    pub fn with_lifetime(mut self, lifetime: f32) -> Self {
        self.lifetime = lifetime;
        self.max_lifetime = lifetime;
        self
    }

    pub fn with_symbol(mut self, symbol: char) -> Self {
        self.symbol = symbol;
        self
    }

    pub fn with_color(mut self, color: Color) -> Self {
        self.color = color;
        self
    }

    pub fn with_gravity(mut self, gravity: f32) -> Self {
        self.gravity = gravity;
        self
    }

    /// Check if particle is still alive
    pub fn is_alive(&self) -> bool {
        self.lifetime > 0.0
    }

    /// Get fade factor (0.0 to 1.0)
    pub fn fade(&self) -> f32 {
        (self.lifetime / self.max_lifetime).clamp(0.0, 1.0)
    }

    /// Update particle physics
    pub fn update(&mut self, delta_time: f32) {
        // Apply velocity
        self.x += self.vx * delta_time;
        self.y += self.vy * delta_time;

        // Apply gravity
        self.vy += self.gravity * delta_time;

        // Decrease lifetime
        self.lifetime -= delta_time;
    }
}

/// Particle system manager
pub struct ParticleSystem {
    /// Active particles
    particles: Vec<Particle>,
    /// Maximum particle count
    max_particles: usize,
    /// Bounds for particle rendering
    bounds: Option<Rect>,
}

impl ParticleSystem {
    pub fn new(max_particles: usize) -> Self {
        Self {
            particles: Vec::with_capacity(max_particles),
            max_particles,
            bounds: None,
        }
    }

    pub fn with_bounds(mut self, bounds: Rect) -> Self {
        self.bounds = Some(bounds);
        self
    }

    /// Add a particle to the system
    pub fn add(&mut self, particle: Particle) {
        if self.particles.len() < self.max_particles {
            self.particles.push(particle);
        }
    }

    /// Emit particles at a position with random velocities
    pub fn emit(&mut self, x: f32, y: f32, count: usize, config: EmitConfig) {
        for _ in 0..count {
            if self.particles.len() >= self.max_particles {
                break;
            }

            // Random angle
            let angle = config.angle_min + pseudo_random() * (config.angle_max - config.angle_min);
            let speed = config.speed_min + pseudo_random() * (config.speed_max - config.speed_min);

            let vx = angle.cos() * speed;
            let vy = angle.sin() * speed;

            let lifetime =
                config.lifetime_min + pseudo_random() * (config.lifetime_max - config.lifetime_min);

            let symbol = config.symbols[pseudo_random_index(config.symbols.len())];
            let color = config.colors[pseudo_random_index(config.colors.len())];

            self.add(
                Particle::new(x, y)
                    .with_velocity(vx, vy)
                    .with_lifetime(lifetime)
                    .with_symbol(symbol)
                    .with_color(color)
                    .with_gravity(config.gravity),
            );
        }
    }

    /// Create a sparkle effect
    pub fn sparkle(&mut self, x: f32, y: f32, count: usize) {
        self.emit(
            x,
            y,
            count,
            EmitConfig {
                speed_min: 2.0,
                speed_max: 8.0,
                angle_min: 0.0,
                angle_max: std::f32::consts::PI * 2.0,
                lifetime_min: 0.3,
                lifetime_max: 0.8,
                gravity: 0.0,
                symbols: &['', '', '·', ''],
                colors: &[colors::WARNING, colors::ACCENT, Color::White],
            },
        );
    }

    /// Create an explosion effect
    pub fn explode(&mut self, x: f32, y: f32, count: usize) {
        self.emit(
            x,
            y,
            count,
            EmitConfig {
                speed_min: 5.0,
                speed_max: 15.0,
                angle_min: 0.0,
                angle_max: std::f32::consts::PI * 2.0,
                lifetime_min: 0.5,
                lifetime_max: 1.5,
                gravity: 5.0,
                symbols: &['', '', '', ''],
                colors: &[colors::PRIMARY, colors::WARNING, colors::ERROR],
            },
        );
    }

    /// Create a success celebration
    pub fn celebrate(&mut self, x: f32, y: f32) {
        self.emit(
            x,
            y,
            20,
            EmitConfig {
                speed_min: 3.0,
                speed_max: 10.0,
                angle_min: -std::f32::consts::PI,
                angle_max: 0.0, // Upward
                lifetime_min: 1.0,
                lifetime_max: 2.0,
                gravity: 3.0,
                symbols: &['', '', '', ''],
                colors: &[
                    colors::SUCCESS,
                    colors::ACCENT,
                    colors::WARNING,
                    colors::SECONDARY,
                ],
            },
        );
    }

    /// Get particle count
    pub fn particle_count(&self) -> usize {
        self.particles.len()
    }

    /// Clear all particles
    pub fn clear(&mut self) {
        self.particles.clear();
    }
}

impl Animation for ParticleSystem {
    fn update(&mut self, delta_time: f32) {
        // Update all particles
        for particle in &mut self.particles {
            particle.update(delta_time);
        }

        // Remove dead particles
        self.particles.retain(|p| p.is_alive());

        // Remove particles outside bounds if set
        if let Some(bounds) = self.bounds {
            self.particles.retain(|p| {
                let x = p.x as u16;
                let y = p.y as u16;
                x >= bounds.x
                    && x < bounds.x + bounds.width
                    && y >= bounds.y
                    && y < bounds.y + bounds.height
            });
        }
    }

    fn is_complete(&self) -> bool {
        self.particles.is_empty()
    }
}

impl Widget for &ParticleSystem {
    fn render(self, area: Rect, buf: &mut Buffer) {
        for particle in &self.particles {
            let x = particle.x.round() as u16;
            let y = particle.y.round() as u16;

            if x >= area.x && x < area.x + area.width && y >= area.y && y < area.y + area.height {
                // Apply fade to color
                let fade = particle.fade();
                let color = if let Color::Rgb(r, g, b) = particle.color {
                    Color::Rgb(
                        (r as f32 * fade) as u8,
                        (g as f32 * fade) as u8,
                        (b as f32 * fade) as u8,
                    )
                } else {
                    particle.color
                };

                let mut style = Style::default().fg(color);
                if fade > 0.7 {
                    style = style.add_modifier(Modifier::BOLD);
                }

                buf[(x, y)]
                    .set_symbol(&particle.symbol.to_string())
                    .set_style(style);
            }
        }
    }
}

/// Configuration for particle emission
pub struct EmitConfig<'a> {
    pub speed_min: f32,
    pub speed_max: f32,
    pub angle_min: f32,
    pub angle_max: f32,
    pub lifetime_min: f32,
    pub lifetime_max: f32,
    pub gravity: f32,
    pub symbols: &'a [char],
    pub colors: &'a [Color],
}

// Simple pseudo-random number generator (deterministic for testing)
static RANDOM_SEED: AtomicU32 = AtomicU32::new(12345);

fn pseudo_random() -> f32 {
    let mut seed = RANDOM_SEED.load(Ordering::Relaxed);
    seed = seed.wrapping_mul(1103515245).wrapping_add(12345);
    RANDOM_SEED.store(seed, Ordering::Relaxed);
    ((seed >> 16) & 0x7FFF) as f32 / 32768.0
}

fn pseudo_random_index(max: usize) -> usize {
    (pseudo_random() * max as f32) as usize % max
}

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

    #[test]
    fn test_particle_new() {
        let p = Particle::new(10.0, 20.0);
        assert!((p.x - 10.0).abs() < 0.001);
        assert!((p.y - 20.0).abs() < 0.001);
        assert!(p.is_alive());
    }

    #[test]
    fn test_particle_update() {
        let mut p = Particle::new(0.0, 0.0)
            .with_velocity(10.0, 5.0)
            .with_lifetime(1.0);

        p.update(0.1);
        assert!((p.x - 1.0).abs() < 0.001);
        assert!((p.y - 0.5).abs() < 0.001);
        assert!((p.lifetime - 0.9).abs() < 0.001);
    }

    #[test]
    fn test_particle_gravity() {
        let mut p = Particle::new(0.0, 0.0)
            .with_velocity(0.0, 0.0)
            .with_gravity(10.0)
            .with_lifetime(1.0);

        p.update(0.1);
        assert!((p.vy - 1.0).abs() < 0.001); // Gravity accelerates vy
    }

    #[test]
    fn test_particle_system_new() {
        let ps = ParticleSystem::new(100);
        assert_eq!(ps.particle_count(), 0);
    }

    #[test]
    fn test_particle_system_add() {
        let mut ps = ParticleSystem::new(5);

        for i in 0..10 {
            ps.add(Particle::new(i as f32, 0.0));
        }

        // Should cap at max
        assert_eq!(ps.particle_count(), 5);
    }

    #[test]
    fn test_particle_system_update_removes_dead() {
        let mut ps = ParticleSystem::new(10);
        ps.add(Particle::new(0.0, 0.0).with_lifetime(0.1));

        assert_eq!(ps.particle_count(), 1);

        // Update past lifetime
        ps.update(0.2);
        assert_eq!(ps.particle_count(), 0);
    }

    #[test]
    fn test_particle_system_sparkle() {
        let mut ps = ParticleSystem::new(50);
        ps.sparkle(10.0, 10.0, 10);
        assert!(ps.particle_count() > 0);
    }
}