【问题标题】:How to use Depth Testing with CAMetalLayer using Metal and Swift?如何使用 Metal 和 Swift 对 CAMetalLayer 进行深度测试?
【发布时间】:2017-07-28 18:25:48
【问题描述】:

最近我决定学习如何在 Swift 中使用 Metal 框架。我阅读了一些教程,观看了视频,做了一些事情,最后我不得不使用深度测试来让事情看起来更好。

我以前没有做过这么低级的图形编程,所以我环顾整个互联网,了解深度测试的工作原理以及如何使用 CAMetalLayer 和 Metal 实现它。

但是,我发现的所有深度测试示例都是使用 Open GL 完成的,而我在 Metal 中找不到这样的功能。

如何使用 Metal 和 Swift 使用 CAMetalLayer 实现深度测试?

提前谢谢你!

【问题讨论】:

    标签: swift metal depth-testing


    【解决方案1】:

    这是一个很好的例子。 http://metalbyexample.com/up-and-running-3/

    关键是CAMetalLayer 不会为你维护深度图。您需要明确地创建和管理深度纹理。并将深度纹理附加到用于创建渲染编码器的深度模板描述符。

    【讨论】:

    • 你能告诉我如何从一个通道创建深度纹理吗?
    【解决方案2】:

    this Stackoverflow post 的问题包含您的答案,尽管它是用 Obj-C 编写的。但基本上,正如东风所指出的,您需要自己创建和管理深度纹理。

    这是一个关于如何创建深度纹理的 Swift 4 sn-p

    func buildDepthTexture(_ device: MTLDevice, _ size: CGSize) -> MTLTexture {
        let desc = MTLTextureDescriptor.texture2DDescriptor(
            pixelFormat: .depth32Float_stencil8,
            width: Int(size.width), height: Int(size.height), mipmapped: false)
        desc.storageMode = .private
        desc.usage = .renderTarget
        return device.makeTexture(descriptor: desc)!
    }
    

    下面是您需要如何将其附加到MTLRenderPassDescriptor

    let renderPassDesc = MTLRenderPassDescriptor()
    
    let depthAttachment = renderPassDesc.depthAttachment!
    // depthTexture is created using the above function
    depthAttachment.texture = depthTexture
    depthAttachment.clearDepth = 1.0
    depthAttachment.storeAction = .dontCare
    
    // Maybe set up color attachment, etc.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      相关资源
      最近更新 更多