Reputation: 41
Recently I decided to learn how to use the Metal framework with Swift. I read some turorials, watched videos, did a few things and finally I got to part where I have to use Depth Testing to make things look good.
I haven't done such low level graphics programming before, so I looked around the whole Internet on how Depth Testing works and how to implemented it using CAMetalLayer and Metal.
However all examples of Depth Testing, which I found, were done using Open GL and I couldn't find such functions in Metal.
How do I implement Depth Testing with CAMetalLayer using Metal and Swift?
Thank you in advance!
Upvotes: 4
Views: 2857
Reputation: 103
The question of this Stackoverflow post contains your answer, although it's written in Obj-C. But basically, like what Dong Feng has pointed out, you need to create and manage the depth texture by yourself.
Here's a Swift 4 snippet for how to create a depth texture
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)!
}
And here's how you need to attach it to a 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.
Upvotes: 1
Reputation: 61
This is a good example. http://metalbyexample.com/up-and-running-3/
The key is that CAMetalLayer
does not maintain the depth map for you. You need to create and manage explicitly the depth texture. And attach the depth texture to the depth-stencil descriptor which you use to create the render-encoder.
Upvotes: 3