Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SpriteKit, put a process on another core?

Tags:

Imagine in your

 class NattyScene: SKScene {

you have perhaps a custom Field for the nodes, or something else that happens every frame. Now imagine you have some calculation, a nice example might be center of gravity ...

var globalCOG: CGPoint
func updateCOG() {
   .. say, get all the .position of all Spaceship ..
   globalCOG = .. some point
}

It would make great sense to put that on another thread, assuming issues like

  • it's threadsafe / fast to read the .positions
  • this other putative thread on another core, knows about SpriteKit frames (so that you can calculate until giveup time in the usual manner, etc, perhaps you may prefer to skip frame or whatever - the usual panoply of threaded game programming)
  • you can threadsafe/blahblah write the COG global back to the rest of SpriteKit

What's the deal on this?

  • What really is the modern idiom for this in Swift4 / SpriteKit
  • How do you force it to go on another whole physical core?

Any ideas?


override func update(_ currentTime: TimeInterval) {

    let x = safely get info from a thread on another physical core on the device
    print("now that's cool")
}

on the other core ...

 func loopy() {

    let x = safely look at info on NattyScene
    let globalCOG = calculation
}

Note, KOD has pointed to DispatchQueue, which is great - but is there any way to ensure it's really on another core?

like image 344
Fattie Avatar asked Nov 08 '17 23:11

Fattie


1 Answers

Nice question, unfortunately I don't think this is possible for 2 main reasons.

Reason 1

You don't have this kind of low level access in iOS.

The OS is the one who decides which thread runs on which core. It also has the capability of turning on and off the cores depending on several conditions beyond the scope of your app.

E.g. When in Grand Central Dispatch you write

DispatchQueue.global(qos: .background).async { }

You have no guarantee the closure will be executed on a different core.

Reason 2

The Game Run Loop of SpriteKit does execute a bunch of stuff

  1. call update
  2. evaluates actions
  3. simulates physics
  4. applies constraints

Your idea does imply the execution of the following steps within the call update phase

  1. move on a "background" thread
  2. perform some heavy computations
  3. bring the result back to the main thread

But at this point you have no guarantee the Game Run Loop is still in the call update phase. It could be in the evaluates actions or it could even be working at the next frame. On the other hand you have no more than 16 milliseconds to render each frame.

Possible Solution

Instead of targeting another CPU core you could take full advantage of the 64 bits allowed by the current core. Look at this Q/A about SceneKit where are listed the benefits of SIMD.

like image 142
Luca Angeletti Avatar answered Sep 23 '22 12:09

Luca Angeletti