summaryrefslogtreecommitdiff
path: root/metal_view.swift
diff options
context:
space:
mode:
Diffstat (limited to 'metal_view.swift')
-rw-r--r--metal_view.swift65
1 files changed, 58 insertions, 7 deletions
diff --git a/metal_view.swift b/metal_view.swift
index 7cc8d34..31c2ea8 100644
--- a/metal_view.swift
+++ b/metal_view.swift
@@ -1,8 +1,59 @@
-//
-// metal_view.swift
-// metal_test
-//
-// Created by Ian C on 02/12/2023.
-//
+import SwiftUI
+import MetalKit
-import Foundation
+struct MetalView: NSViewRepresentable {
+ func makeCoordinator() -> Coordinator {
+ Coordinator(self)
+ }
+ func makeNSView(context: NSViewRepresentableContext<MetalView>) -> MTKView {
+ let mtkView = MTKView()
+ mtkView.delegate = context.coordinator
+ mtkView.preferredFramesPerSecond = 60
+ mtkView.enableSetNeedsDisplay = true
+ if let metalDevice = MTLCreateSystemDefaultDevice() {
+ mtkView.device = metalDevice
+ }
+ mtkView.framebufferOnly = false
+ mtkView.clearColor = MTLClearColor(red: 0, green: 0, blue: 0, alpha: 0)
+ mtkView.drawableSize = mtkView.frame.size
+ mtkView.enableSetNeedsDisplay = true
+ mtkView.isPaused = false
+ return mtkView
+ }
+
+ func updateNSView(_ nsView: MTKView, context: NSViewRepresentableContext<MetalView>) {
+ }
+
+ class Coordinator : NSObject, MTKViewDelegate {
+ var parent: MetalView
+ var metalDevice: MTLDevice!
+ var metalCommandQueue: MTLCommandQueue!
+
+ init(_ parent: MetalView) {
+ self.parent = parent
+ if let metalDevice = MTLCreateSystemDefaultDevice() {
+ self.metalDevice = metalDevice
+ }
+ self.metalCommandQueue = metalDevice.makeCommandQueue()!
+ super.init()
+ }
+
+ func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
+ }
+
+ func draw(in view: MTKView) {
+ guard let drawable = view.currentDrawable else {
+ return
+ }
+ let commandBuffer = metalCommandQueue.makeCommandBuffer()
+ let rpd = view.currentRenderPassDescriptor
+ rpd?.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 1)
+ rpd?.colorAttachments[0].loadAction = .clear
+ rpd?.colorAttachments[0].storeAction = .store
+ let re = commandBuffer?.makeRenderCommandEncoder(descriptor: rpd!)
+ re?.endEncoding()
+ commandBuffer?.present(drawable)
+ commandBuffer?.commit()
+ }
+ }
+}