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
//! Metal backend implementation for macOS.
//!
//! This is a native Metal backend (not MoltenVK) for optimal macOS performance.
//! Uses CAMetalLayer for surface presentation and MSL shaders compiled from Slang.

use super::*;
use crate::types::*;
use anyhow::{Context, Result};
use std::collections::HashMap;

// Note: These imports would be used in actual Metal implementation
// use metal::{Device as MTLDevice, CommandQueue, RenderPipelineState};
// use raw_window_handle::{RawWindowHandle, HasWindowHandle, HasDisplayHandle};

/// Metal backend for macOS.
/// 
/// Provides native Metal API access without MoltenVK translation layer.
pub struct MetalBackend {
    // Metal device and command queue
    // device: MTLDevice,
    // command_queue: CommandQueue,
    
    // Resource tracking
    devices: HashMap<DeviceHandle, MetalDevice>,
    next_device_handle: DeviceHandle,
    buffers: HashMap<BufferHandle, MetalBuffer>,
    next_buffer_handle: BufferHandle,
    shaders: HashMap<ShaderHandle, MetalShader>,
    next_shader_handle: ShaderHandle,
    pipelines: HashMap<PipelineHandle, MetalPipeline>,
    next_pipeline_handle: PipelineHandle,
    bind_group_layouts: HashMap<BindGroupLayoutHandle, MetalBindGroupLayout>,
    next_bind_group_layout_handle: BindGroupLayoutHandle,
    bind_groups: HashMap<BindGroupHandle, MetalBindGroup>,
    next_bind_group_handle: BindGroupHandle,
    render_targets: HashMap<RenderTargetHandle, MetalRenderTarget>,
    next_render_target_handle: RenderTargetHandle,
    surfaces: HashMap<SurfaceHandle, MetalSurface>,
    next_surface_handle: SurfaceHandle,
}

struct MetalDevice {
    adapter_id: u32,
    // device: MTLDevice,
    // command_queue: CommandQueue,
}

struct MetalBuffer {
    device_handle: DeviceHandle,
    size: u64,
    // buffer: metal::Buffer,
}

struct MetalShader {
    device_handle: DeviceHandle,
    source: String,
    // Compiled MSL library
    // library: metal::Library,
}

struct MetalPipeline {
    device_handle: DeviceHandle,
    // state: RenderPipelineState,
}

struct MetalBindGroupLayout {
    device_handle: DeviceHandle,
}

struct MetalBindGroup {
    device_handle: DeviceHandle,
}

struct MetalRenderTarget {
    device_handle: DeviceHandle,
    width: u32,
    height: u32,
    format: TextureFormat,
    has_rendered: bool,
    // texture: metal::Texture,
}

struct MetalSurface {
    device_handle: DeviceHandle,
    width: u32,
    height: u32,
    // layer: CAMetalLayer,
    // current_drawable: Option<metal::MetalDrawable>,
}

impl MetalBackend {
    /// Create a new Metal backend.
    /// 
    /// # Errors
    /// 
    /// Returns an error if Metal is not available on this system.
    pub fn new() -> Result<Self> {
        // In actual implementation:
        // let device = MTLDevice::system_default()
        //     .context("No Metal device available")?;
        // let command_queue = device.new_command_queue();
        
        tracing::info!("Initializing Metal backend");
        
        Ok(Self {
            devices: HashMap::new(),
            next_device_handle: 1,
            buffers: HashMap::new(),
            next_buffer_handle: 1,
            shaders: HashMap::new(),
            next_shader_handle: 1,
            pipelines: HashMap::new(),
            next_pipeline_handle: 1,
            bind_group_layouts: HashMap::new(),
            next_bind_group_layout_handle: 1,
            bind_groups: HashMap::new(),
            next_bind_group_handle: 1,
            render_targets: HashMap::new(),
            next_render_target_handle: 1,
            surfaces: HashMap::new(),
            next_surface_handle: 1,
        })
    }
}

impl GpuBackend for MetalBackend {
    fn backend_type(&self) -> BackendType {
        BackendType::Metal
    }

    fn enumerate_adapters(&self) -> Vec<AdapterInfo> {
        // In actual implementation, use MTLCopyAllDevices()
        vec![
            AdapterInfo {
                id: 0,
                name: "Metal GPU".to_string(),
                vendor: "Apple".to_string(),
                backend: BackendType::Metal,
                device_type: DeviceType::IntegratedGpu,
            }
        ]
    }

    fn create_device(&mut self, adapter_id: u32) -> Result<DeviceHandle> {
        let handle = self.next_device_handle;
        self.next_device_handle += 1;

        self.devices.insert(handle, MetalDevice { adapter_id });
        Ok(handle)
    }

    fn destroy_device(&mut self, device: DeviceHandle) {
        self.devices.remove(&device);
        self.buffers.retain(|_, b| b.device_handle != device);
        self.shaders.retain(|_, s| s.device_handle != device);
        self.pipelines.retain(|_, p| p.device_handle != device);
        self.render_targets.retain(|_, t| t.device_handle != device);
        self.surfaces.retain(|_, s| s.device_handle != device);
    }

    fn is_device_valid(&self, device: DeviceHandle) -> bool {
        self.devices.contains_key(&device)
    }

    fn create_buffer(&mut self, device: DeviceHandle, size: u64, _usage: BufferUsage) -> Result<BufferHandle> {
        if !self.devices.contains_key(&device) {
            anyhow::bail!("Invalid device handle");
        }

        let handle = self.next_buffer_handle;
        self.next_buffer_handle += 1;

        self.buffers.insert(handle, MetalBuffer {
            device_handle: device,
            size,
        });

        Ok(handle)
    }

    fn destroy_buffer(&mut self, buffer: BufferHandle) {
        self.buffers.remove(&buffer);
    }

    fn write_buffer(&mut self, buffer: BufferHandle, _offset: u64, _data: &[u8]) -> Result<()> {
        if !self.buffers.contains_key(&buffer) {
            anyhow::bail!("Invalid buffer handle");
        }
        // In actual implementation: copy data to Metal buffer
        Ok(())
    }

    fn buffer_size(&self, buffer: BufferHandle) -> u64 {
        self.buffers.get(&buffer).map(|b| b.size).unwrap_or(0)
    }

    fn create_shader(&mut self, device: DeviceHandle, slang_source: &str) -> Result<ShaderHandle> {
        self.create_shader_with_paths(device, slang_source, &[])
    }

    fn create_shader_with_paths(&mut self, device: DeviceHandle, slang_source: &str, _search_paths: &[&str]) -> Result<ShaderHandle> {
        if !self.devices.contains_key(&device) {
            anyhow::bail!("Invalid device handle");
        }

        // In actual implementation:
        // 1. Compile Slang to MSL using slang::compile(source, Target::Metal)
        // 2. Create MTLLibrary from MSL source

        let handle = self.next_shader_handle;
        self.next_shader_handle += 1;

        self.shaders.insert(handle, MetalShader {
            device_handle: device,
            source: slang_source.to_string(),
        });

        Ok(handle)
    }

    fn destroy_shader(&mut self, shader: ShaderHandle) {
        self.shaders.remove(&shader);
    }

    fn create_bind_group_layout(&mut self, device: DeviceHandle, _entries: &[BindGroupLayoutEntry]) -> Result<BindGroupLayoutHandle> {
        if !self.devices.contains_key(&device) {
            anyhow::bail!("Invalid device handle");
        }

        let handle = self.next_bind_group_layout_handle;
        self.next_bind_group_layout_handle += 1;

        self.bind_group_layouts.insert(handle, MetalBindGroupLayout {
            device_handle: device,
        });

        Ok(handle)
    }

    fn create_bind_group(&mut self, device: DeviceHandle, _layout: BindGroupLayoutHandle, _entries: &[BindGroupEntry]) -> Result<BindGroupHandle> {
        if !self.devices.contains_key(&device) {
            anyhow::bail!("Invalid device handle");
        }

        let handle = self.next_bind_group_handle;
        self.next_bind_group_handle += 1;

        self.bind_groups.insert(handle, MetalBindGroup {
            device_handle: device,
        });

        Ok(handle)
    }

    fn destroy_bind_group(&mut self, bind_group: BindGroupHandle) {
        self.bind_groups.remove(&bind_group);
    }

    fn create_pipeline(
        &mut self,
        device: DeviceHandle,
        _vertex_shader: ShaderHandle,
        _fragment_shader: ShaderHandle,
        _vertex_layout: &VertexBufferLayout,
        _topology: PrimitiveTopology,
        _target_format: TextureFormat,
    ) -> Result<PipelineHandle> {
        if !self.devices.contains_key(&device) {
            anyhow::bail!("Invalid device handle");
        }

        // In actual implementation:
        // 1. Get vertex/fragment functions from shader libraries
        // 2. Create MTLRenderPipelineDescriptor
        // 3. Create RenderPipelineState

        let handle = self.next_pipeline_handle;
        self.next_pipeline_handle += 1;

        self.pipelines.insert(handle, MetalPipeline {
            device_handle: device,
        });

        Ok(handle)
    }

    fn create_pipeline_with_layout(
        &mut self,
        device: DeviceHandle,
        vertex_shader: ShaderHandle,
        fragment_shader: ShaderHandle,
        vertex_layout: &VertexBufferLayout,
        topology: PrimitiveTopology,
        target_format: TextureFormat,
        _bind_group_layouts: &[BindGroupLayoutHandle],
    ) -> Result<PipelineHandle> {
        self.create_pipeline(device, vertex_shader, fragment_shader, vertex_layout, topology, target_format)
    }

    fn destroy_pipeline(&mut self, pipeline: PipelineHandle) {
        self.pipelines.remove(&pipeline);
    }

    fn create_render_target(&mut self, device: DeviceHandle, width: u32, height: u32, format: TextureFormat) -> Result<RenderTargetHandle> {
        if !self.devices.contains_key(&device) {
            anyhow::bail!("Invalid device handle");
        }

        // In actual implementation: create MTLTexture with renderTarget usage

        let handle = self.next_render_target_handle;
        self.next_render_target_handle += 1;

        self.render_targets.insert(handle, MetalRenderTarget {
            device_handle: device,
            width,
            height,
            format,
            has_rendered: false,
        });

        Ok(handle)
    }

    fn destroy_render_target(&mut self, target: RenderTargetHandle) {
        self.render_targets.remove(&target);
    }

    fn render_to_target(&mut self, device: DeviceHandle, target: RenderTargetHandle, _commands: &[RenderCommand]) -> Result<()> {
        if !self.devices.contains_key(&device) {
            anyhow::bail!("Invalid device handle");
        }

        let render_target = self.render_targets.get_mut(&target)
            .context("Invalid render target handle")?;

        // In actual implementation:
        // 1. Create MTLCommandBuffer
        // 2. Create MTLRenderPassDescriptor with target texture
        // 3. Encode render commands
        // 4. Commit command buffer

        render_target.has_rendered = true;
        Ok(())
    }

    fn read_target_to_cpu(&mut self, target: RenderTargetHandle, output: &mut [u8]) -> Result<()> {
        let render_target = self.render_targets.get(&target)
            .context("Invalid render target handle")?;

        if !render_target.has_rendered {
            anyhow::bail!("Cannot read from render target that hasn't been rendered to");
        }

        // In actual implementation:
        // 1. Create blit command to copy texture to shared buffer
        // 2. Synchronize and read buffer contents

        // Fill with test pattern for now
        for byte in output.iter_mut() {
            *byte = 128;
        }
        Ok(())
    }

    // Surface API for Metal
    fn create_surface(
        &mut self,
        device: DeviceHandle,
        _window: &dyn raw_window_handle::HasWindowHandle,
        _display: &dyn raw_window_handle::HasDisplayHandle,
    ) -> Result<SurfaceHandle> {
        if !self.devices.contains_key(&device) {
            anyhow::bail!("Invalid device handle");
        }

        // In actual implementation:
        // 1. Get RawWindowHandle::AppKit(h)
        // 2. Create CAMetalLayer
        // 3. Set layer.device = MTLDevice
        // 4. Set layer.pixelFormat = MTLPixelFormatBGRA8Unorm
        // 5. Attach layer to NSView via setLayer/setWantsLayer

        let handle = self.next_surface_handle;
        self.next_surface_handle += 1;

        self.surfaces.insert(handle, MetalSurface {
            device_handle: device,
            width: 800,
            height: 600,
        });

        tracing::info!("Created Metal surface {}", handle);
        Ok(handle)
    }

    fn destroy_surface(&mut self, surface: SurfaceHandle) {
        self.surfaces.remove(&surface);
    }

    fn surface_acquire(&mut self, surface: SurfaceHandle) -> Result<SwapchainImageHandle> {
        if !self.surfaces.contains_key(&surface) {
            anyhow::bail!("Invalid surface handle");
        }

        // In actual implementation:
        // let drawable = layer.next_drawable()?;
        // Store drawable for present

        Ok(1) // Return dummy image handle
    }

    fn surface_render(&mut self, surface: SurfaceHandle, _image: SwapchainImageHandle, _commands: &[RenderCommand]) -> Result<()> {
        if !self.surfaces.contains_key(&surface) {
            anyhow::bail!("Invalid surface handle");
        }

        // In actual implementation:
        // 1. Get drawable's texture
        // 2. Create render pass with drawable texture
        // 3. Encode commands
        // 4. Commit

        Ok(())
    }

    fn surface_present(&mut self, surface: SurfaceHandle, _image: SwapchainImageHandle) -> Result<()> {
        if !self.surfaces.contains_key(&surface) {
            anyhow::bail!("Invalid surface handle");
        }

        // In actual implementation:
        // drawable.present();
        // or: commandBuffer.present(drawable);

        Ok(())
    }

    fn surface_resize(&mut self, surface: SurfaceHandle, width: u32, height: u32) -> Result<()> {
        let surf = self.surfaces.get_mut(&surface)
            .context("Invalid surface handle")?;

        // In actual implementation:
        // layer.drawableSize = CGSize(width, height)

        surf.width = width;
        surf.height = height;
        Ok(())
    }

    fn surface_size(&self, surface: SurfaceHandle) -> (u32, u32) {
        self.surfaces.get(&surface)
            .map(|s| (s.width, s.height))
            .unwrap_or((0, 0))
    }
}

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

    #[test]
    fn test_metal_backend_creation() {
        let backend = MetalBackend::new().unwrap();
        assert_eq!(backend.backend_type(), BackendType::Metal);
    }

    #[test]
    fn test_metal_adapters() {
        let backend = MetalBackend::new().unwrap();
        let adapters = backend.enumerate_adapters();
        assert!(!adapters.is_empty());
    }
}