Iterating Shader Application

This is a bit of an extension of the question asked here. I know that the GPU is good enough at stupidly parallel things, like Conway's game of life in the example below, to be able to run many iterations at interactive speeds (~60fps I'd think). As discussed in the thread above, I know that I am losing a lot of speed to shifting the texture to and from GPU memory, and that to do better than this I will need to access OpenGL directly. So my question is: how do I go about doing this?

PShader gol;

void setup() {
    size(512, 256, P2D);
    initGol();
    loadPixels();
    for (int i = 0; i < width; i++) {
      for (int j = 0; j < height; j++) {
        pixels[i+width*j] = color(255*int(random(2)));
      }
    }
    updatePixels();
}

void draw() {
  println(frameRate);
    for (int i = 0; i < 1000; i++) 
      filter(gol);
}

void initGol() {
    String[] vertSource = {
        "#version 410",

        "uniform mat4 transform;",

        "in vec4 vertex;",
        "in vec2 texCoord;",

        "out vec2 vertTexCoord;",

        "void main() {",
            "vertTexCoord = vec2(texCoord.x, 1.0 - texCoord.y);",
            "gl_Position = transform * vertex;",
        "}"
    };
    String[] fragSource = {
        "#version 410",

        "uniform sampler2D texture;",
        "uniform vec2 texOffset;",

        "in vec2 vertTexCoord;",

        "out vec4 fragColor;",

        "int get(int x, int y) {",
            "return int(texture(texture, vertTexCoord + vec2(x*texOffset.x, y*texOffset.y)));",
        "}",

        "void main() {",
            "int sum = get(-1, -1) +",
                      "get(-1,  0) +",
                      "get(-1,  1) +",
                      "get( 0, -1) +",
                      "get( 0,  1) +",
                      "get( 1, -1) +",
                      "get( 1,  0) +",
                      "get( 1,  1);",
            "if (sum == 3) {",
                "fragColor = vec4(1.0, 1.0, 1.0, 1.0);",
            "} else if (sum == 2) {",
                "float current = float(get(0, 0));",
                "fragColor = vec4(current, current, current, 1.0);",
            "} else {",
                "fragColor = vec4(0.0, 0.0, 0.0, 1.0);",
            "}",
        "}",
    };
    gol = new PShader(this, vertSource, fragSource);
}
Sign In or Register to comment.