0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【MetalKit】Drawable.texture assertion error

Posted at

MTKViewのtextureに画像が描画されない

以下が問題のコードです。

import UIKit
import MetalKit

class ViewController: UIViewController {
        
    @IBOutlet weak var metalView: MTKView!
    private let device = MTLCreateSystemDefaultDevice()!
    private var commandQueue: MTLCommandQueue!
    private var texture: MTLTexture!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpMetalView()
    }
    
    private  func setUpMetalView() {
        commandQueue = device.makeCommandQueue()
        metalView.device = device
        metalView.delegate = self
        texture = try! MTKTextureLoader(device: device).newTexture(
            name: "Image",
            scaleFactor: view.contentScaleFactor,
            bundle: nil)
        metalView.colorPixelFormat = texture.pixelFormat
    }


}

extension ViewController: MTKViewDelegate {
    func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {
    }
    
    func draw(in view: MTKView) {
        guard let currentDrawable = view.currentDrawable else {return}
        let commandBuffer = commandQueue.makeCommandBuffer()!
        let blitEncoder = commandBuffer.makeBlitCommandEncoder()!
        blitEncoder.copy(from: texture,
                         sourceSlice: 0,
                         sourceLevel: 0,
                         sourceOrigin: MTLOrigin(x: 0, y: 0, z: 0),
                         sourceSize: MTLSizeMake(w = min(texture.width, currentDrawable.texture.width), min(texture.height, currentDrawable.texture.height), texture.depth),
                         to: currentDrawable.texture,
                         destinationSlice: 0,
                         destinationLevel: 0,
                         destinationOrigin: MTLOrigin(x: 0, y: 0, z: 0))
        blitEncoder.endEncoding()
        commandBuffer.present(currentDrawable)
        commandBuffer.commit()
    }
}

解決策

以下のコードの通りframebufferOnlyの設定をfalseにしてあげる必要があるみたいです。
MTKViewのドローアブルのテクスチャに書き込みたい場合、フレームバッファのみでは描画できないらしく、レイヤーを構成する必要があるみたいです。そのためframebufferOnlyをfalseに指定し、レイヤーの構成が必要であることを伝える必要があるみたいです。

private  func setUpMetalView() {
    // 以上省略
    metalView.framebufferOnly = false
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?