How to convert MTLTexture to SKTexture

Looking for info on the best way to convert a MTLTexture to SKTexture.

I am migrating a project where a SpriteKit scene is rendered in an SKView - and relies heavily on SKView.texture(from: SKNode) API

I am trying to migrate to an SKRenderer based SpriteKit scene - and wondering the best way to grab an SKTexture from an SKNode when rendered in a MTKView instead of SKView?

Answered by BlueFang in 788197022

I have figured out a solution. This post on StackOverflow helped out immensely:

The secret is to use an SKRenderer() in addition to the SKView renderer. They are not mutually exclusive.

The example referenced above uses a SceneKit view as the source, grabs a metal texture from the SceneKit scene, and then uses that metal texture as the texture of a second SceneKit scene that has a single plane object using the metal texture as its diffuse texture.

The same setup works with SpriteKit:

For my use case, I was able to implement using a single SKScene, rendered to both an SKView() and an SKRenderer() - just call the SKRenderer.render() method inside your SKScene.update() method. The SKRenderer is what is used to render the scene into a MTLTexture using a renderPassDescriptor. I found that I had to call SKRenderer.render() and commandBuffer.commit() prior to updating any SpriteKit nodes - but it works great.

That MTLTexture can then be used however is necessary. In my test setup, I also rendered it to a separate SCNView using a single plane node.

Accepted Answer

I have figured out a solution. This post on StackOverflow helped out immensely:

The secret is to use an SKRenderer() in addition to the SKView renderer. They are not mutually exclusive.

The example referenced above uses a SceneKit view as the source, grabs a metal texture from the SceneKit scene, and then uses that metal texture as the texture of a second SceneKit scene that has a single plane object using the metal texture as its diffuse texture.

The same setup works with SpriteKit:

For my use case, I was able to implement using a single SKScene, rendered to both an SKView() and an SKRenderer() - just call the SKRenderer.render() method inside your SKScene.update() method. The SKRenderer is what is used to render the scene into a MTLTexture using a renderPassDescriptor. I found that I had to call SKRenderer.render() and commandBuffer.commit() prior to updating any SpriteKit nodes - but it works great.

That MTLTexture can then be used however is necessary. In my test setup, I also rendered it to a separate SCNView using a single plane node.

How to convert MTLTexture to SKTexture
 
 
Q