Self contained layers by extending PGraphics

Inspired by code I showed in Writing Processing in Kotlin I wrote two examples that might be interesting for someone. Maybe not :slight_smile:

1

fps

FPSLayer fpsLayer; // FPS

void settings() {
  size(640, 480, P2D);
}

void setup() {
  fpsLayer = new FPSLayer(this); // FPS
}

void draw() {
  stroke(random(255));
  line(random(width), random(height), random(width), random(height));
  image(fpsLayer.update(), 5, height - 25); // FPS
  
  // You could also separate the previous line in two:
  // fpsLayer.update(); 
  // image(fpsLayer, 5, height - 25);
}

public class FPSLayer extends PGraphics2D {
    private int frameCount;
    private long nextTime;
    FPSLayer(PApplet p5) {
        setParent(p5);
        setPrimary(false);
        setSize(30, 20);
        nextTime = System.currentTimeMillis() + 1000;
    }
    PGraphics2D update() {
        frameCount++;
        long now = System.currentTimeMillis();
        if(now >= nextTime) {
            beginDraw();
            background(0);
            fill(255);
            text(frameCount, 5, height - 5);
            endDraw();
            frameCount = 0;
            nextTime = now + 1000;
        }
        return this;
    }
}

The idea behind this is having a self contained reusable layer that extends PGraphics2D or PGraphics3D. You can use such component (in this example a FPS indicator) with just 3 lines in your main program: declaring an instance, initializing it, and drawing it.

It also shows a simplified way of drawing into a PGraphics because you don’t need to prepend each single call with pg. as you typically see (for example in https://processing.org/reference/createGraphics_.html)

2

3Dlayer
This example renders a rotating cube only once, then reuses that same rendering 7 times placing it rotated on the screen. Maybe useful if you wanted to reuse a complex rendered image many times.

CubeLayer layer;

void settings() {
  size(640, 480, P3D);
}

void setup() {
  layer = new CubeLayer(this);
}

void draw() {
  background(#0ABE00);
  translate(width/2, height/2);
  rotate(-frameCount * 0.003);
  layer.update();
  for (int i=0; i<7; i++) {    
    image(layer, 70, 0);
    rotate(TAU/7.0);
  }
}

public class CubeLayer extends PGraphics3D {
  CubeLayer(PApplet p5) {
    setParent(p5);
    setPrimary(false);
    setSize(200, 200);
  }
  void update() {
    beginDraw();
    clear();
    directionalLight(51, 102, 126, 1, 1, 1);
    directionalLight(255, 245, 235, -1, -1, -1);
    translate(width/2, height/2);
    rotateX(frameCount * 0.01);
    rotateY(1);
    box(100);
    endDraw();
  }
}
3 Likes