Getting started with Metal in PixelKit

Start by reading Getting started with PixelKit to get the PixelsKit framework up and running.

Here’s the basic setup for custom Metal shader code:

let metal = MetalPIX(res: .fullscreen, uniforms: [], code:
    """
    pix = float4(u, v, 0.0, 1.0);
    """
)

let final: PIX = metal
final.view.frame = view.bounds
view.addSubview(final.view)

The following code will display a uv map. The float4 represents red, green, blue & alpha.


Now lets a live uniform value:

let uniforms: [MetalUniform] = [
    MetalUniform(name: "t", value: .touch),
]
let metal = MetalPIX(res: .fullscreen, uniforms: uniforms, code:
    """
    pix = float4(u, v, in.t, 1.0);
    """
)

Don’t forget to add the uniforms to the MetalPIX.


Now let’s add a custom live uniform value:

let date = Date()
let uniforms: [MetalUniform] = [
    MetalUniform(name: "t", value: .touch),
    MetalUniform(name: "d", value: LiveFloat({ () -> (CGFloat) in
        return CGFloat(-date.timeIntervalSinceNow)
    })),
]
let metal = MetalPIX(res: .fullscreen, uniforms: uniforms, code:
    """
    pix = float4(u, v, in.t, cos(in.d) / 2 + 0.5);
    """
)

Here’s another setup, with touch position:

let uniforms: [MetalUniform] = [
    MetalUniform(name: "x", value: .touchX),
    MetalUniform(name: "y", value: .touchY)
]
let metal = MetalPIX(res: .fullscreen, uniforms: uniforms, code:
    """
    float x = u - in.x - 0.5;
    float y = v - in.y - 0.5;
    float a = abs(x) * abs(y);
    float c = pow(1.0 - a, 10.0);
    pix = float4(c, c, c, 1.0);
    """
)

So far we’ve been creating textures, now it’s time to merge textures.

Here’s a way to merge PIXs:

let circle = CirclePIX(res: .fullscreen)
let polygon = PolygonPIX(res: .fullscreen)
let metalMerger = MetalMergerEffectPIX(uniforms: [], code:
    """
    pix = float4(0.0, inPixA[0], inPixB[0], 1.0);
    """
)
metalMerger.inPixA = circle
metalMerger.inPixB = polygon

Learn more on GitHub.

Lämna en kommentar

E-postadressen publiceras inte. Obligatoriska fält är märkta *