Quantcast
Channel: FlexMonkey
Viewing all articles
Browse latest Browse all 257

Metal Performance Shaders & Fallback Copy Allocators

$
0
0

One of the options available when using Metal Performance Shaders is to filter textures in place. This is discussed in What's New in Metal Part 2, but the actual implementation is slightly glossed over. Worse than that, fallback copy allocators didn't actually work until the latest iOS 9 beta build, so if you've been struggling, here's a quick blog post to help.

When filtering a source texture and populating a destination texture, encodeToCommandBuffer() has this signature:

    encodeToCommandBuffer(commandBuffer, sourceTexture: srcTexture, destinationTexture: targetTexture)

However, with the following syntax, we can apply a filter to a texture in place:

    encodeToCommandBuffer(commandBuffer, inPlaceTexture: inPlaceTexture, fallbackCopyAllocator: copyAllocator)

Some filters, such as MPSImageMedian are unable to filter in place and in this situation, we need to create an instance of MPSCopyAllocator which will create a texture and ensure the in-place version of encodeToCommandBuffer will always succeed. There isn't actually a descriptorFromTexture() method available (as shown in the WWDC video), so the correct Swift definition of copyAllocator is:

    let copyAllocator: MPSCopyAllocator =
    {
        (kernel: MPSKernel, buffer: MTLCommandBuffer, sourceTexture: MTLTexture) -> MTLTexturein
        
        let descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat(sourceTexture.pixelFormat,
            width: sourceTexture.width,
            height: sourceTexture.height,
            mipmapped: false)
        
        let targetTexture: MTLTexture = buffer.device.newTextureWithDescriptor(descriptor)
     
        return targetTexture

    }

...and now the following will work:

    let median = MPSImageMedian(device: device!, kernelDiameter: 3)
    
    median.encodeToCommandBuffer(commandBuffer, inPlaceTexture: inPlaceTexture, fallbackCopyAllocator: copyAllocator)

Easy!

Viewing all articles
Browse latest Browse all 257

Trending Articles