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
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
//! GPU device management.
//!
//! # Thread Safety
//!
//! Goldy uses a single-threaded command submission model with lock-free command recording:
//!
//! - **Command Recording**: [`CommandEncoder`](crate::CommandEncoder) is completely lock-free.
//!   You can create and record commands on any thread without any synchronization.
//!   
//! - **Resource Creation**: Creating resources ([`Buffer`](crate::Buffer),
//!   [`RenderPipeline`](crate::RenderPipeline), etc.) acquires the backend lock.
//!   These operations are safe from any thread but serialize internally.
//!
//! - **Command Submission**: Submitting commands via [`RenderTarget::render()`](crate::RenderTarget::render)
//!   or [`SurfaceFrame::render()`](crate::SurfaceFrame::render) acquires the backend lock.
//!
//! ## Best Practices
//!
//! For optimal performance:
//! 1. Create resources during initialization, not per-frame
//! 2. Record commands lock-free using `CommandEncoder` on any thread
//! 3. Submit commands from a single thread (typically the main/render thread)
//!
//! This model is sufficient for most applications. Future versions may add
//! multi-queue support for parallel command submission if needed.

use crate::backend::{self, AdapterInfo, DeviceHandle, GpuBackend};
use crate::shader_library::ShaderLibrary;
use crate::types::*;
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

/// Unique ID generator for temp directories
static REGISTRY_COUNTER: AtomicU64 = AtomicU64::new(0);

/// GPU instance - entry point for Goldy.
///
/// Create an instance to enumerate adapters and create devices.
pub struct Instance {
    backend: Arc<Mutex<Box<dyn GpuBackend>>>,
}

impl Instance {
    /// Create a new Goldy instance.
    pub fn new() -> Result<Self> {
        let backend = backend::create_default_backend()?;
        Ok(Self {
            backend: Arc::new(Mutex::new(backend)),
        })
    }

    /// Enumerate available GPU adapters.
    pub fn enumerate_adapters(&self) -> Vec<Adapter> {
        let backend = self.backend.lock().unwrap();
        backend
            .enumerate_adapters()
            .into_iter()
            .map(|info| Adapter { info })
            .collect()
    }

    /// Create a device on the first adapter matching the given type.
    pub fn create_device(&self, preferred_type: DeviceType) -> Result<Device> {
        let adapters = self.enumerate_adapters();
        
        // Find preferred adapter
        let adapter = adapters
            .iter()
            .find(|a| a.info.device_type == preferred_type)
            .or_else(|| adapters.first())
            .context("No GPU adapters available")?;

        self.create_device_for_adapter(adapter.info.id)
    }

    /// Create a device on a specific adapter by ID.
    ///
    /// The device is automatically configured with the built-in `goldy_exp`
    /// (experimental) shader library registered. You can register additional
    /// libraries using [`Device::register_library`].
    pub fn create_device_for_adapter(&self, adapter_id: u32) -> Result<Device> {
        let mut backend = self.backend.lock().unwrap();
        let handle = backend.create_device(adapter_id)?;
        
        // Create registry with built-in goldy_exp library
        let mut registry = ShaderLibraryRegistry::new();
        registry.register(ShaderLibrary::goldy_experimental())?;
        
        Ok(Device {
            backend: Arc::clone(&self.backend),
            handle,
            adapter_id,
            library_registry: Arc::new(Mutex::new(registry)),
        })
    }

    /// Get the backend type (Vulkan, Metal, DX12).
    pub fn backend_type(&self) -> BackendType {
        self.backend.lock().unwrap().backend_type()
    }
}

/// Information about a GPU adapter.
#[derive(Debug, Clone)]
pub struct Adapter {
    pub info: AdapterInfo,
}

impl Adapter {
    /// Get the adapter ID.
    pub fn id(&self) -> u32 {
        self.info.id
    }

    /// Get the adapter name.
    pub fn name(&self) -> &str {
        &self.info.name
    }

    /// Get the device type.
    pub fn device_type(&self) -> DeviceType {
        self.info.device_type
    }

    /// Get the vendor name.
    pub fn vendor(&self) -> &str {
        &self.info.vendor
    }
}

/// Device capabilities and format preferences.
///
/// Use this to query the optimal formats and limits for your use case.
#[derive(Debug, Clone)]
pub struct DeviceCapabilities {
    /// Preferred format for window surfaces (swapchains).
    /// For windowed apps, use this for `RenderPipelineDesc::target_format`.
    pub preferred_surface_format: TextureFormat,
    
    /// Preferred format for off-screen render targets.
    /// For headless rendering (video encoding, CPU readback), use this format.
    pub preferred_render_target_format: TextureFormat,
    
    /// Formats supported for window surfaces.
    pub supported_surface_formats: Vec<TextureFormat>,
    
    /// Formats supported for render targets.
    pub supported_render_target_formats: Vec<TextureFormat>,
}

impl Default for DeviceCapabilities {
    fn default() -> Self {
        Self {
            preferred_surface_format: TextureFormat::Bgra8UnormSrgb,
            preferred_render_target_format: TextureFormat::Rgba8Unorm,
            supported_surface_formats: vec![
                TextureFormat::Bgra8UnormSrgb,
                TextureFormat::Bgra8Unorm,
            ],
            supported_render_target_formats: vec![
                TextureFormat::Rgba8Unorm,
                TextureFormat::Rgba8UnormSrgb,
                TextureFormat::Bgra8Unorm,
                TextureFormat::Bgra8UnormSrgb,
                TextureFormat::Rgba16Float,
                TextureFormat::Rgba32Float,
            ],
        }
    }
}

/// A GPU device - used to create resources and render.
///
/// The `Device` is the primary interface for GPU operations. It is `Send + Sync`,
/// so it can be safely shared across threads (typically via `Arc<Device>`).
///
/// # Thread Safety
///
/// Internally, `Device` uses a `Mutex` to serialize backend operations. This means:
/// - Resource creation is thread-safe but serializes internally
/// - Command recording via [`CommandEncoder`](crate::CommandEncoder) is lock-free
/// - Command submission acquires the lock
///
/// See the [module documentation](self) for best practices.
///
/// # Shader Libraries
///
/// The device maintains a registry of shader libraries that are automatically
/// available to all shaders compiled for this device. The built-in `goldy`
/// library is registered by default.
///
/// ```rust,ignore
/// use goldy::ShaderLibrary;
///
/// // Register a custom library
/// device.register_library(ShaderLibrary::from_source("mylib", "module mylib;"))?;
///
/// // Check if a library is registered
/// assert!(device.has_library("goldy"));
/// ```
pub struct Device {
    pub(crate) backend: Arc<Mutex<Box<dyn GpuBackend>>>,
    pub(crate) handle: DeviceHandle,
    adapter_id: u32,
    /// Shader library registry
    library_registry: Arc<Mutex<ShaderLibraryRegistry>>,
}

/// Internal registry for shader libraries.
struct ShaderLibraryRegistry {
    libraries: HashMap<String, ShaderLibrary>,
    /// Temp directory for library sources (lazily created)
    temp_dir: Option<PathBuf>,
    /// Whether temp files are out of sync with libraries
    dirty: bool,
}

impl ShaderLibraryRegistry {
    fn new() -> Self {
        Self {
            libraries: HashMap::new(),
            temp_dir: None,
            dirty: true,
        }
    }
    
    fn register(&mut self, library: ShaderLibrary) -> Result<()> {
        let name = library.name().to_string();
        if self.libraries.contains_key(&name) {
            anyhow::bail!("Library '{}' is already registered", name);
        }
        self.libraries.insert(name, library);
        self.dirty = true;
        Ok(())
    }
    
    fn unregister(&mut self, name: &str) -> bool {
        if self.libraries.remove(name).is_some() {
            self.dirty = true;
            true
        } else {
            false
        }
    }
    
    fn has(&self, name: &str) -> bool {
        self.libraries.contains_key(name)
    }
    
    fn list(&self) -> Vec<&str> {
        self.libraries.keys().map(|s| s.as_str()).collect()
    }
    
    /// Ensure temp files are written and return search paths.
    fn get_search_paths(&mut self) -> Result<Vec<PathBuf>> {
        if self.libraries.is_empty() {
            return Ok(vec![]);
        }
        
        // Create temp directory if needed
        if self.temp_dir.is_none() {
            let unique_id = REGISTRY_COUNTER.fetch_add(1, Ordering::Relaxed);
            let temp_dir = std::env::temp_dir().join(format!(
                "goldy-shaders-{}-{}", 
                std::process::id(),
                unique_id
            ));
            std::fs::create_dir_all(&temp_dir)
                .context("Failed to create shader library temp directory")?;
            self.temp_dir = Some(temp_dir);
        }
        
        // Write library files if dirty
        if self.dirty {
            let temp_dir = self.temp_dir.as_ref().unwrap();
            
            for library in self.libraries.values() {
                for (module_path, source) in library.modules() {
                    // Convert module path (with forward slashes) to OS-appropriate file path
                    let mut file_path = temp_dir.clone();
                    for component in module_path.split('/') {
                        file_path = file_path.join(component);
                    }
                    file_path.set_extension("slang");
                    
                    // Ensure parent directories exist
                    if let Some(parent) = file_path.parent() {
                        std::fs::create_dir_all(parent)
                            .context("Failed to create module directory")?;
                    }
                    
                    std::fs::write(&file_path, source)
                        .with_context(|| format!("Failed to write module: {}", module_path))?;
                }
            }
            
            self.dirty = false;
        }
        
        Ok(vec![self.temp_dir.clone().unwrap()])
    }
}

impl Drop for ShaderLibraryRegistry {
    fn drop(&mut self) {
        // Clean up temp directory
        if let Some(temp_dir) = self.temp_dir.take() {
            let _ = std::fs::remove_dir_all(temp_dir);
        }
    }
}

impl Device {
    /// Get the adapter ID this device was created on.
    pub fn adapter_id(&self) -> u32 {
        self.adapter_id
    }

    /// Check if the device is still valid.
    pub fn is_valid(&self) -> bool {
        self.backend.lock().unwrap().is_device_valid(self.handle)
    }

    /// Get device capabilities and format preferences.
    ///
    /// Use this to query optimal formats for your use case:
    /// - Windowed apps: use `preferred_surface_format` for pipelines
    /// - Headless/streaming: use `preferred_render_target_format` for RenderTarget
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use goldy::{Instance, DeviceType};
    ///
    /// let instance = Instance::new()?;
    /// let device = instance.create_device(DeviceType::DiscreteGpu)?;
    /// let caps = device.capabilities();
    /// 
    /// println!("Surface format: {:?}", caps.preferred_surface_format);
    /// println!("RenderTarget format: {:?}", caps.preferred_render_target_format);
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn capabilities(&self) -> DeviceCapabilities {
        // For now, return sensible defaults
        // Future: query actual device limits and capabilities
        DeviceCapabilities::default()
    }
    
    // --- Shader Library Management ---
    
    /// Register a shader library for use in shader imports.
    ///
    /// After registration, shaders can use `import <library_name>;` to access
    /// the library's modules.
    ///
    /// # Errors
    ///
    /// Returns an error if a library with the same name is already registered.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use goldy::ShaderLibrary;
    ///
    /// let my_lib = ShaderLibrary::from_source("myutils", r#"
    ///     module myutils;
    ///     public float3 custom_color() { return float3(1, 0, 0); }
    /// "#);
    ///
    /// device.register_library(my_lib)?;
    ///
    /// // Now shaders can use: import myutils;
    /// ```
    pub fn register_library(&self, library: ShaderLibrary) -> Result<()> {
        self.library_registry.lock().unwrap().register(library)
    }
    
    /// Unregister a shader library.
    ///
    /// Returns `true` if the library was found and removed, `false` if it
    /// wasn't registered.
    ///
    /// # Note
    ///
    /// Unregistering the built-in `goldy` library is allowed but not recommended,
    /// as many shader utilities depend on it.
    pub fn unregister_library(&self, name: &str) -> bool {
        self.library_registry.lock().unwrap().unregister(name)
    }
    
    /// Check if a shader library is registered.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // The goldy library is registered by default
    /// assert!(device.has_library("goldy"));
    /// ```
    pub fn has_library(&self, name: &str) -> bool {
        self.library_registry.lock().unwrap().has(name)
    }
    
    /// List all registered shader libraries.
    ///
    /// Returns the names of all currently registered libraries.
    pub fn list_libraries(&self) -> Vec<String> {
        self.library_registry
            .lock()
            .unwrap()
            .list()
            .iter()
            .map(|s| s.to_string())
            .collect()
    }
    
    /// Get search paths for shader compilation (internal use).
    pub(crate) fn get_shader_search_paths(&self) -> Result<Vec<PathBuf>> {
        self.library_registry.lock().unwrap().get_search_paths()
    }

    /// Create a device from a backend for testing purposes.
    #[cfg(test)]
    pub(crate) fn from_backend(backend: Box<dyn GpuBackend>) -> anyhow::Result<Self> {
        let backend = Arc::new(Mutex::new(backend));
        let handle = {
            let mut b = backend.lock().unwrap();
            b.create_device(0)?
        };
        
        // Create registry with built-in goldy_exp library
        let mut registry = ShaderLibraryRegistry::new();
        registry.register(ShaderLibrary::goldy_experimental())?;
        
        Ok(Self {
            backend,
            handle,
            adapter_id: 0,
            library_registry: Arc::new(Mutex::new(registry)),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::mock::MockBackend;
    
    fn test_device() -> Device {
        Device::from_backend(Box::new(MockBackend::new())).unwrap()
    }
    
    #[test]
    fn test_goldy_library_registered_by_default() {
        let device = test_device();
        assert!(device.has_library("goldy_exp"));
    }
    
    #[test]
    fn test_register_custom_library() {
        let device = test_device();
        
        let lib = ShaderLibrary::from_source("custom", "module custom;");
        device.register_library(lib).unwrap();
        
        assert!(device.has_library("custom"));
    }
    
    #[test]
    fn test_register_duplicate_fails() {
        let device = test_device();
        
        let lib1 = ShaderLibrary::from_source("mylib", "module mylib;");
        let lib2 = ShaderLibrary::from_source("mylib", "module mylib;");
        
        device.register_library(lib1).unwrap();
        let result = device.register_library(lib2);
        
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("already registered"));
    }
    
    #[test]
    fn test_unregister_library() {
        let device = test_device();
        
        let lib = ShaderLibrary::from_source("temp", "module temp;");
        device.register_library(lib).unwrap();
        assert!(device.has_library("temp"));
        
        assert!(device.unregister_library("temp"));
        assert!(!device.has_library("temp"));
    }
    
    #[test]
    fn test_unregister_nonexistent_returns_false() {
        let device = test_device();
        assert!(!device.unregister_library("nonexistent"));
    }
    
    #[test]
    fn test_list_libraries() {
        let device = test_device();
        
        let libs = device.list_libraries();
        assert!(libs.contains(&"goldy_exp".to_string()));
        
        device.register_library(ShaderLibrary::from_source("extra", "module extra;")).unwrap();
        let libs = device.list_libraries();
        assert!(libs.contains(&"goldy_exp".to_string()));
        assert!(libs.contains(&"extra".to_string()));
    }
    
    #[test]
    fn test_search_paths_writes_files() {
        let device = test_device();
        
        let paths = device.get_shader_search_paths().unwrap();
        assert_eq!(paths.len(), 1);
        
        // Verify goldy_exp files were written
        let goldy_file = paths[0].join("goldy_exp.slang");
        assert!(goldy_file.exists(), "goldy_exp.slang should exist at {:?}", goldy_file);
        
        let math_file = paths[0].join("goldy_exp/math.slang");
        assert!(math_file.exists(), "goldy_exp/math.slang should exist at {:?}", math_file);
    }
}

impl Drop for Device {
    fn drop(&mut self) {
        let mut backend = self.backend.lock().unwrap();
        backend.destroy_device(self.handle);
    }
}