互操作 MTKView (MetalKit) 和 SceneKit

Sum*_*mon 1 scenekit metal metalkit scnscene mtkview

我正在使用 MetalKit 并且有一个复杂的渲染管道。结果呈现为MTKView.

现在我想将 的内容提供MTKView给 aSCNScene并使用 aSCNCamera来执行 HDR 等后期处理效果。

这怎么可能?

我不需要一般性的指导。如果可能的话,我想要具体的电话。

Osk*_*kar 5

理想情况下,您应该将后处理作为 Metal 渲染管道的一部分来执行。您建议的过程需要不必要的资源,因为您将在 SceneKit 中以 3D 形式渲染 2D 平面,只是为了应用一些 HDR 效果。

不过,您可以通过将 Metal 管道输出渲染到纹理,然后简单地将其应用到 SceneKit 中的平面来实现您想要的效果。

首先分配你的纹理:

plane.materials.first?.diffuse.contents = offscreenTexture

然后将 SceneKit 渲染覆盖到 Metal 渲染循环:

func renderer(_ renderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: TimeInterval) {
    doRender()
}
Run Code Online (Sandbox Code Playgroud)

然后以纹理为目标执行 Metal 渲染,完成后即可渲染 SceneKit 场景:

func doRender() {
    //rendering to a MTLTexture, so the viewport is the size of this texture
    let viewport = CGRect(x: 0, y: 0, width: CGFloat(textureSizeX), height: CGFloat(textureSizeY))

    //write to offscreenTexture, clear the texture before rendering using green, store the result
    let renderPassDescriptor = MTLRenderPassDescriptor()
    renderPassDescriptor.colorAttachments[0].texture = offscreenTexture
    renderPassDescriptor.colorAttachments[0].loadAction = .clear
    renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0, 1, 0, 1.0); //green
    renderPassDescriptor.colorAttachments[0].storeAction = .store

    let commandBuffer = commandQueue.makeCommandBuffer()

    // reuse scene1 and the current point of view
    renderer.scene = scene1
    renderer.pointOfView = scnView1.pointOfView
    renderer.render(atTime: 0, viewport: viewport, commandBuffer: commandBuffer, passDescriptor: renderPassDescriptor)

    commandBuffer.commit()
}`
Run Code Online (Sandbox Code Playgroud)

完整的示例项目:

https://github.com/lachlanhurst/SceneKitOffscreenRendering