Issue with alpha in P2D Renderer

Hello Processing Community,

I’ve encountered a challenging issue while working with the P2D renderer in Processing, specifically when trying to layer semi-transparent shapes over a white background. The expected result is a lighter color where the semi-transparent shape overlays the background. However, the actual result is a greyish shape, suggesting an issue with how alpha blending is being handled in P2D (probably related to pre-multiplication?)

Here’s the minimal code that reproduces the problem:

PGraphics backgroundLayer;
PGraphics shapeLayer;

void setup() {
  size(400, 400, P2D);

  // Initialize the background layer with white opaque background
  backgroundLayer = createGraphics(width, height, P2D);
  backgroundLayer.beginDraw();
  backgroundLayer.background(255);
  backgroundLayer.endDraw();

  // Initialize the shape layer with a transparent background
  shapeLayer = createGraphics(width, height, P2D);
  shapeLayer.beginDraw();
  shapeLayer.clear();
  shapeLayer.endDraw();
}

void draw() {
  // Draw a semi-transparent rectangle on the shape layer
  shapeLayer.beginDraw();
  shapeLayer.clear(); // Clear previous frame
  shapeLayer.fill(255, 127); // Set color to white with half opacity
  shapeLayer.noStroke();
  shapeLayer.rectMode(CENTER);
  shapeLayer.rect(width/2, height/2, width/2, height/2);
  shapeLayer.endDraw();

  // Draw the background layer
  image(backgroundLayer, 0, 0);

  // Set the blend mode for drawing the shape layer
  blendMode(BLEND);

  // Draw the shape layer
  image(shapeLayer, 0, 0);
}

Here are the steps and attempts I have made to resolve this issue:

  1. Explicitly setting the blend mode to BLEND before drawing the shape layer.
  2. Clearing the shape layer with clear() to ensure no residual pixels from the previous frame.
  3. Using the default renderer, which resolved the issue but is not compatible with the Syphon library that I intend to use.

The goal is to work with the Syphon library, which requires P2D, and thus finding a solution with P2D is imperative.

I’m reaching out for help to understand if there’s something I’m missing or if there’s a known workaround for this issue. Any insight, suggestions, or guidance would be greatly appreciated.

Thank you for your time and assistance!

Yes, it’s almost certainly this Add support for pre-multiplied alpha · Issue #3391 · processing/processing · GitHub Processing has been broken here for a long time!

2 Likes

oops… sad to see this issue has been unattended for so long…