goldy 0.1.0

Goldy - Modern Graphics Library
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
//! Multi-window example - three simultaneous effects in separate windows.
//!
//! Each window runs its own demo and handles keyboard/mouse independently.
//! - Window 1: Plasma effect (press Space to pause)
//! - Window 2: Tunnel effect (press Space to reverse direction)
//! - Window 3: Starfield (press Space to toggle warp speed)
//!
//! Run with: cargo run --example multi_window

use goldy::{
    Buffer, BufferUsage, Color, CommandEncoder, DeviceType, Surface,
    Instance, RenderPipeline, RenderPipelineDesc, ShaderModule,
    VertexBufferLayout, VertexAttribute, VertexFormat,
    shaders,
};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Instant;
use winit::{
    application::ApplicationHandler,
    dpi::LogicalSize,
    event::{ElementState, MouseButton, WindowEvent},
    event_loop::{ActiveEventLoop, ControlFlow, EventLoop},
    keyboard::{Key, NamedKey},
    window::{Window, WindowAttributes, WindowId},
};

// ============================================================================
// Shared vertex type for fullscreen quads
// ============================================================================

#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct QuadVertex {
    position: [f32; 2],
    uv: [f32; 2],
    time: f32,
}

impl QuadVertex {
    fn layout() -> VertexBufferLayout {
        VertexBufferLayout {
            stride: std::mem::size_of::<Self>() as u32,
            attributes: vec![
                VertexAttribute { location: 0, format: VertexFormat::Float32x2, offset: 0 },
                VertexAttribute { location: 1, format: VertexFormat::Float32x2, offset: 8 },
                VertexAttribute { location: 2, format: VertexFormat::Float32, offset: 16 },
            ],
        }
    }
}

fn create_quad(time: f32) -> [QuadVertex; 6] {
    [
        QuadVertex { position: [-1.0, -1.0], uv: [0.0, 1.0], time },
        QuadVertex { position: [1.0, -1.0], uv: [1.0, 1.0], time },
        QuadVertex { position: [1.0, 1.0], uv: [1.0, 0.0], time },
        QuadVertex { position: [-1.0, -1.0], uv: [0.0, 1.0], time },
        QuadVertex { position: [1.0, 1.0], uv: [1.0, 0.0], time },
        QuadVertex { position: [-1.0, 1.0], uv: [0.0, 0.0], time },
    ]
}

// ============================================================================
// Effect types
// ============================================================================

#[derive(Clone, Copy, PartialEq)]
enum EffectType {
    Plasma,
    Tunnel,
    Starfield,
}

impl EffectType {
    fn title(&self) -> &'static str {
        match self {
            EffectType::Plasma => "Plasma [Space=pause, Click=reset]",
            EffectType::Tunnel => "Tunnel [Space=reverse, Click=reset]",
            EffectType::Starfield => "Starfield [Space=warp, Click=reset]",
        }
    }

    fn shader_source(&self) -> &'static str {
        match self {
            EffectType::Plasma => shaders::PLASMA,
            EffectType::Tunnel => shaders::TUNNEL,
            EffectType::Starfield => shaders::STARFIELD,
        }
    }
}

// ============================================================================
// Per-window state
// ============================================================================

struct WindowState {
    window: Arc<Window>,
    surface: Surface,
    pipeline: RenderPipeline,
    effect_type: EffectType,
    
    // Per-window animation state
    start_time: Instant,
    paused: bool,
    paused_at: f32,
    time_multiplier: f32,
    
    // Frame pipelining
    vertex_buffers: Vec<Buffer>,
    
    // For status display
    has_focus: bool,
}

const MAX_FRAMES_IN_FLIGHT: usize = 2;

impl WindowState {
    fn new(
        window: Arc<Window>,
        device: &Arc<goldy::Device>,
        effect_type: EffectType,
    ) -> anyhow::Result<Self> {
        let surface = Surface::new(&device, window.as_ref())?;
        let shader = ShaderModule::from_slang(device, effect_type.shader_source())?;
        let pipeline = RenderPipeline::new(device, &shader, &shader, &RenderPipelineDesc {
            vertex_layout: QuadVertex::layout(),
            target_format: surface.format(),
            ..Default::default()
        })?;
        
        Ok(Self {
            window,
            surface,
            pipeline,
            effect_type,
            start_time: Instant::now(),
            paused: false,
            paused_at: 0.0,
            time_multiplier: 1.0,
            vertex_buffers: Vec::with_capacity(MAX_FRAMES_IN_FLIGHT),
            has_focus: false,
        })
    }
    
    fn current_time(&self) -> f32 {
        if self.paused {
            self.paused_at
        } else {
            self.paused_at + self.start_time.elapsed().as_secs_f32() * self.time_multiplier
        }
    }
    
    fn toggle_pause(&mut self) {
        if self.paused {
            // Resuming - reset start time
            self.start_time = Instant::now();
            self.paused = false;
        } else {
            // Pausing - save current time
            self.paused_at = self.current_time();
            self.paused = true;
        }
    }
    
    fn toggle_effect_modifier(&mut self) {
        match self.effect_type {
            EffectType::Plasma => self.toggle_pause(),
            EffectType::Tunnel => {
                // Reverse direction
                self.paused_at = self.current_time();
                self.start_time = Instant::now();
                self.time_multiplier *= -1.0;
            }
            EffectType::Starfield => {
                // Toggle warp speed
                self.paused_at = self.current_time();
                self.start_time = Instant::now();
                self.time_multiplier = if self.time_multiplier > 2.0 { 1.0 } else { 5.0 };
            }
        }
    }
    
    fn reset(&mut self) {
        self.start_time = Instant::now();
        self.paused = false;
        self.paused_at = 0.0;
        self.time_multiplier = 1.0;
    }
    
    fn render(&mut self, device: &goldy::Device) -> anyhow::Result<()> {
        let size = self.window.inner_size();
        if size.width == 0 || size.height == 0 {
            return Ok(());
        }
        
        let time = self.current_time();
        let vertices = create_quad(time);
        let vertex_buffer = Buffer::with_data(device, &vertices, BufferUsage::VERTEX)?;
        
        // Acquire frame - this waits for oldest in-flight frame
        let frame = self.surface.acquire()?;
        
        // Safe to drop oldest buffer now
        if self.vertex_buffers.len() >= MAX_FRAMES_IN_FLIGHT {
            self.vertex_buffers.remove(0);
        }
        
        let mut encoder = CommandEncoder::new();
        {
            let mut pass = encoder.begin_render_pass();
            pass.clear(Color::BLACK);
            pass.set_pipeline(&self.pipeline);
            pass.set_vertex_buffer(0, &vertex_buffer);
            pass.draw(0..6, 0..1);
        }
        
        frame.render(encoder)?;
        self.surface.present(frame)?;
        
        self.vertex_buffers.push(vertex_buffer);
        Ok(())
    }
    
    fn handle_resize(&mut self, width: u32, height: u32) {
        if width > 0 && height > 0 {
            let _ = self.surface.resize(width, height);
        }
    }
}

// ============================================================================
// Main application
// ============================================================================

struct App {
    instance: Instance,
    device: Option<Arc<goldy::Device>>,
    windows: HashMap<WindowId, WindowState>,
    effects_to_create: Vec<EffectType>,
}

impl App {
    fn new() -> anyhow::Result<Self> {
        Ok(Self {
            instance: Instance::new()?,
            device: None,
            windows: HashMap::new(),
            effects_to_create: vec![EffectType::Plasma, EffectType::Tunnel, EffectType::Starfield],
        })
    }
    
    fn create_window(
        &mut self,
        event_loop: &ActiveEventLoop,
        effect_type: EffectType,
        position: (i32, i32),
    ) -> anyhow::Result<()> {
        let device = self.device.as_ref().unwrap().clone();
        
        let attrs = WindowAttributes::default()
            .with_title(format!("Goldy - {}", effect_type.title()))
            .with_inner_size(LogicalSize::new(500, 500))
            .with_position(winit::dpi::LogicalPosition::new(position.0, position.1));
        
        let window = Arc::new(event_loop.create_window(attrs)?);
        let window_id = window.id();
        
        let mut state = WindowState::new(window.clone(), &device, effect_type)?;
        
        // Render first frame immediately to avoid white/undefined swapchain content
        state.render(&device)?;
        window.request_redraw(); // Start animation loop
        
        self.windows.insert(window_id, state);
        
        Ok(())
    }
    
}

impl ApplicationHandler for App {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        // Initialize device if needed
        if self.device.is_none() {
            match self.instance.create_device(DeviceType::DiscreteGpu) {
                Ok(device) => self.device = Some(Arc::new(device)),
                Err(e) => {
                    eprintln!("Failed to create device: {}", e);
                    event_loop.exit();
                    return;
                }
            }
        }
        
        // Create windows for each effect (each window renders first frame immediately)
        let effects: Vec<_> = self.effects_to_create.drain(..).collect();
        for (i, effect) in effects.into_iter().enumerate() {
            // Position windows side by side
            let x = 50 + (i as i32) * 520;
            let y = 100;
            
            if let Err(e) = self.create_window(event_loop, effect, (x, y)) {
                eprintln!("Failed to create window for {:?}: {}", effect.title(), e);
            }
        }
    }
    
    fn window_event(&mut self, event_loop: &ActiveEventLoop, window_id: WindowId, event: WindowEvent) {
        // Get the specific window state
        let state = match self.windows.get_mut(&window_id) {
            Some(s) => s,
            None => return,
        };
        
        match event {
            WindowEvent::CloseRequested => {
                // Remove this window
                self.windows.remove(&window_id);
                
                // If all windows closed, exit
                if self.windows.is_empty() {
                    event_loop.exit();
                }
            }
            
            WindowEvent::Focused(focused) => {
                state.has_focus = focused;
                if focused {
                    println!("Focus: {} ({})", state.effect_type.title(), 
                        if state.paused { "paused" } else { "running" });
                }
            }
            
            WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => {
                match event.logical_key {
                    Key::Named(NamedKey::Escape) => {
                        // Close just this window
                        self.windows.remove(&window_id);
                        if self.windows.is_empty() {
                            event_loop.exit();
                        }
                    }
                    Key::Named(NamedKey::Space) => {
                        if let Some(s) = self.windows.get_mut(&window_id) {
                            s.toggle_effect_modifier();
                            println!("[{}] Modifier toggled", s.effect_type.title());
                        }
                    }
                    Key::Character(ref c) if c == "r" || c == "R" => {
                        if let Some(s) = self.windows.get_mut(&window_id) {
                            s.reset();
                            println!("[{}] Reset", s.effect_type.title());
                        }
                    }
                    _ => {}
                }
            }
            
            WindowEvent::MouseInput { state: ElementState::Pressed, button: MouseButton::Left, .. } => {
                if let Some(s) = self.windows.get_mut(&window_id) {
                    s.reset();
                    println!("[{}] Reset (click)", s.effect_type.title());
                }
            }
            
            WindowEvent::RedrawRequested => {
                // Rendering is handled in about_to_wait for all windows
            }
            
            WindowEvent::Resized(new_size) => {
                if let Some(s) = self.windows.get_mut(&window_id) {
                    s.handle_resize(new_size.width, new_size.height);
                }
            }
            
            _ => {}
        }
    }
    
    fn about_to_wait(&mut self, _event_loop: &ActiveEventLoop) {
        // Request redraw for ALL windows every frame, regardless of focus
        // This ensures unfocused windows continue animating
        let device = match &self.device {
            Some(d) => d.clone(),
            None => return,
        };
        
        for state in self.windows.values_mut() {
            if let Err(e) = state.render(&device) {
                eprintln!("[{}] Render error: {}", state.effect_type.title(), e);
            }
        }
    }
}

fn main() -> anyhow::Result<()> {
    tracing_subscriber::fmt().with_env_filter("info").init();
    
    println!("Goldy Multi-Window Example");
    println!("========================");
    println!("Three windows, three effects, independent controls:");
    println!();
    println!("  Plasma:    Space=pause     Click/R=reset");
    println!("  Tunnel:    Space=reverse   Click/R=reset");
    println!("  Starfield: Space=warp      Click/R=reset");
    println!();
    println!("Escape closes the focused window. Close all to exit.");
    println!();
    
    let event_loop = EventLoop::new()?;
    event_loop.set_control_flow(ControlFlow::Poll);
    event_loop.run_app(&mut App::new()?)?;
    
    Ok(())
}