Nonoku - SpriteKit Shader

A quick one because I was having trouble with this:

let node = SKShapeNode(rectOf: CGSize(width: 100, height: 100), cornerRadius: 5)
        let dashedShader = SKShader(source: "void main() {" +
            "float diff = u_path_length / 5.0;" +
            "float stripe = u_path_length / diff;" +
            "float distance = v_path_distance;" +
            "int h = int(mod(distance / stripe, 2.0));" +
            "gl_FragColor = vec4(h, h, h, h);" +
            "}")

        node.strokeShader = dashedShader

        node.fillColor = SKColor.clear
        node.lineWidth = 2

I've not done much with shaders before so when it didn't work I was short on tools to debug it. In the end it was a bunch of little things I had to solve, from converting the original version to one that would work against the iOS GL ES version, to making sure I converted to int before setting the colour.

Nonoku - Composition

Since I’m using the same background in a bunch of places I want to make it really easy to re-use. I could make a sub-class of UIViewController which implements the functionality. I’m not a fan of that, if it can be avoided. These things have tendency to grow. I could also create a static class method to return the background SKNode. That’s a little better but that’s just a form of composition and Swift actually gives us a nice way to implement this with Protcols and Extensions.

I start by moving declaring the function used for creating the background in a protocol. I’ll call it BackgroundProtocol because I’m awful at names. That’s easy to change later if I decide to add more functionality anyway.

protocol BackgroundProtocol {
    func createBackground(size: CGSize) -> SKNode
}

I can add that protocol to other classes and they’ll have the createBackground(size:) function available to them. Using an extension I can then create a default implementation (by striking coincidence, that’s the code I already had for this).

extension BackgroundProtocol {
    func createBackground(size: CGSize) -> SKNode {         
        let node = SKEffectNode()
        // snip ...
        return node
    }
}

Now I can add that to all the views in my app and they can just call it to get the functionality. And, of course, it can be overridden if needed.

class MainMenuViewController: UIViewController, BackgroundProtocol {
    override func viewDidLoad() {
        super.viewDidLoad()
        let spriteView = (view as? SKView)!
        let scene = SKScene(size: view.bounds.size)
        scene.addChild(createBackground(size: scene.size))
        spriteView.presentScene(scene)
    }
}

Nonoku - Creating a Background

So, I was getting bored of looking at a grey background and, as a break from cleaning up, refactoring, and adding the fiddly (nut necessary) UI code, I decided to run up a quick background.

The original version of Nonoku had a vertical gradient fill, light to dark, with subtle diagonal striping. I liked this so decided to reproduce it. However, it made sense to me to implement this in code. Since I’m using SpriteKit already, rendering to an SKEffectNode which rasterises the nodes made sense (the background is not animated so I can basically update once and be done).

There’s no native way, as far as I’m aware, to draw a gradient on a node, so the first thing would be to create an SKTexture. Again, since this is a one time deal, I’m not too worried. I’ve done something similar before so I already knew I could use a CIFilter to generate this. From that, I can get a CIImage. That can be passed to a CIContext to create a CGImage which can finally be passed to the SKTexture which I’ll pass into an SKSprite.

From reviewing the CIFilter documentation, I can get a list of available filters as follows:

class func filterNames(inCategory category: String?) -> [String]

Even better, under the list of category constants, there is kCICategoryGradient. For this kind of quick exploratory code, I usually start a Swift Playground to spike out the things I don’t know.

So, skipping a step, I have this:

print("\(CIFilter.filterNames(inCategory: kCICategoryGradient))")
let filter = CIFilter(name: "CILinearGradient")
print("\(filter?.attributes)")

The list of filterNames has a couple of likely contenders, CILinearGradient and CISmoothLinearGradient. They take the same attributes (two colours, and two vectors) so I ended up trying both. In my use case I couldn’t see any difference between the two so decided to stick with CILinearGradient. If it ever comes up as an issue, it’s a very simple change to make.

CIFilter.attributes() gives me a list of the supported attributes, and a brief description of them. That's enough to define how I'm going to use it so I can leave the playground and come back to my code.

Since I want to create a new SKTexture with this gradient it makes sense to do it as an extension on SKTexture. I need the size, the start colour, and the end colour. I could add additional logic here but, following YAGNI (You Ain’t Gonna Need It), I am only interested in a vertical gradient so that’s all I’ll support.

extension SKTexture {
    convenience init?(size: CGSize, color1: SKColor, color2: SKColor) {
        guard let filter = CIFilter(name: "CILinearGradient") else {
            return nil
        }
        let startVector = CIVector(x: 0, y: size.height)
        let endVector = CIVector(x: 0, y: 0)
        filter.setValue(startVector, forKey: "inputPoint0")
        filter.setValue(endVector, forKey: "inputPoint1")
        filter.setValue(CIColor(color: color1), forKey: "inputColor0")
        filter.setValue(CIColor(color: color2), forKey: "inputColor1")

        let context = CIContext(options: nil)
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        guard let filterImage = filter.outputImage,
            let image = context.createCGImage(filterImage, from: rect) else {
            return nil
        }

        self.init(cgImage: image)
    }
}

Interestingly, whilst I can just get a ciColor from a UIColor (SKColor aliases UIColor), I can’t use it in the CIFilter due to the following issue.

*** -CIColor not defined for the UIColor UIExtendedSRGBColorSpace 0.666667 0.223529 0.223529 1; need to first convert colorspace.

Instead, I had to create a new instance of CIColor with the UIColor. I’m not sure if there are any issues associated with this, but it’s working fine for me so far.

From there, I just created an SKSpriteNode with the generated texture. The lines were just stroked SKShapeNodes with a CGPath which just have a defined start and end point.

So here’s how it looks:

It’s still early so I’m not sure if this is the final version but it does make the game easier to play as it’s much easier to tell where the empty spaces are. Also, with this approach I can easily generate backgrounds with different colours so I hav…

It’s still early so I’m not sure if this is the final version but it does make the game easier to play as it’s much easier to tell where the empty spaces are. Also, with this approach I can easily generate backgrounds with different colours so I have a bunch of options.