p5.js icon indicating copy to clipboard operation
p5.js copied to clipboard

[p5.js 2.0+ Bug Report]: `noLoop()` not working on WebGPU mode

Open eupthere opened this issue 5 months ago • 11 comments

Most appropriate sub-area of p5.js?

  • [ ] Accessibility
  • [ ] Color
  • [ ] Core/Environment/Rendering
  • [ ] Data
  • [ ] DOM
  • [ ] Events
  • [ ] Image
  • [ ] IO
  • [ ] Math
  • [ ] Typography
  • [ ] Utilities
  • [ ] WebGL
  • [x] WebGPU
  • [ ] p5.strands
  • [ ] Build process
  • [ ] Unit testing
  • [ ] Internationalization
  • [ ] Friendly errors
  • [ ] Other (specify if possible)

p5.js version

2.3.0

Web browser and version

Firefox 151.0.4

Operating system

MacOSX 26.5.1

Steps to reproduce this

Steps:

  1. Create a WebGPU sketch
  2. Run following snippet
  3. Canvas should be grey, but isn't

Snippet:


async function setup() {
  await createCanvas(400, 400, WEBGPU);
  noLoop();
}

function draw() {
  background(128);
}

Image

Canvas exists, but the draw doesn't seem to run. A workaround is using noLoop() when frameCount > 1

eupthere avatar Jun 16 '26 15:06 eupthere

I think this issue has something to do with promotion to the frame buffer.

https://github.com/processing/p5.js/blob/a350bb39e1463e8e68c86e414b0e00663ec84545/src/webgpu/p5.RendererWebGPU.js#L632-L654

      if (this._frameState !== FRAME_STATE.PROMOTED && !this.activeFramebuffer()) {
        // if (this._pInst.frameCount > 0) {
          this._frameState = FRAME_STATE.UNPROMOTED;
        // } else {
          // this._promoteToFramebufferWithoutCopy();
          // clear() then targets mainFramebuffer via activeFramebuffer()
        // }
      }

I tried commenting out the promotion part, and the visuals showed up on the canvas. I am not too familiar with the WebGPU renderer codebase yet, but I suspect something wrong happens when this._pInst.frameCount === 0.

eupthere avatar Jun 17 '26 14:06 eupthere

Code Snippet
<!DOCTYPE html>
<html>

<head>
  <title>P5 test</title>
  <meta http-equiv="pragma" content="no-cache" />
  <meta http-equiv="cache-control" content="no-cache" />
  <meta charset="utf-8">

  <style>
    body {
      margin: 0;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <script type="module">
    import p5 from '../src/app.js';
    import rendererWebGPU from '../src/webgpu/p5.RendererWebGPU.js';

    p5.registerAddon(rendererWebGPU);

    const sketch = function (p) {
      p.setup = async function () {
        await p.createCanvas(400, 400, p.WEBGPU);
        // p.noLoop();
      }
      p.draw = function () {
        console.log(p._renderer.activeFramebuffers.length);
        console.log(p._renderer.activeFramebuffer() === p._renderer.mainFramebuffer);
        p.background(200);
        p.fill('red');
        p.noStroke();
        p.circle(200, 200, 100);
      }
    };

    new p5(sketch);
  </script>
</body>

</html>

It looks like the first draw() starts with the renderer already in the promoted framebuffer state.

// check if framebuffers are active at the start of user draw function
console.log(p._renderer.activeFramebuffers.length);
console.log(p._renderer.activeFramebuffer() === p._renderer.mainFramebuffer);

// first draw
1
true
// second draw
0
false
// third draw
0
false

It seems like setup-time clear() is pushing framebuffer with mainFramebuffer.begin() and that's not unwound before the first draw(). So the first frame begins as if it were already in the framebuffer pass. That would explain why noLoop() worked from the frameCount > 1.

Maybe the intent was to render the setup and first draw together in a framebuffer?

eupthere avatar Jun 17 '26 15:06 eupthere

Thank you for the detailed root-cause analysis. The instrumentation output showing activeFramebuffer() === mainFramebuffer evaluating to true during the first draw() call and false on subsequent calls provides clear evidence that the framebuffer promotion state is not being reset between the setup phase and the first draw cycle.

Analysis

Based on the code excerpt and findings, the issue appears to stem from an asymmetry in the framebuffer promotion lifecycle:

  • During setup(), a call to clear() (via background()) triggers _promoteToFramebufferWithoutCopy() when frameCount === 0, which invokes mainFramebuffer.begin().
  • No corresponding call to unwind or close this promotion (e.g., an end() or state reset) occurs before the first invocation of draw().
  • Consequently, the first draw() call begins execution already inside an active framebuffer render pass, while all subsequent draw() calls begin from an unpromoted state. This produces inconsistent behavior for any logic — such as noLoop() — that assumes a uniform starting state across frames.

There appear to be two plausible directions for a fix, and the correct one depends on the original design intent:

  1. Setup and first draw are intended to be independent passes. Under this interpretation, the fix should ensure the setup-time promotion is properly unwound (e.g., via an explicit end()/reset call) prior to the first draw() invocation, so that draw() always begins from a consistent, unpromoted baseline regardless of frameCount.

  2. Setup and first draw are intended to share a single continuous framebuffer pass. Under this interpretation, the framebuffer promotion behavior in clear() is not itself incorrect. Instead, the issue lies in how noLoop() (and potentially other setup-time state mutations) interact with a renderer that is already mid-pass. The fix would then be scoped to draw-loop scheduling logic rather than to clear().

Note on the Proposed Workaround

Removing the frameCount > 0 conditional (as tested) does resolve the reported visual symptom. However, this changes promotion behavior for every setup-time clear() call, not only the case described here. The existing inline comment — noting that "a mid-draw-loop transition from UNPROMOTED back to PROMOTED... will still lose intermediate UNPROMOTED frame content" — suggests this state machine was already designed around other edge cases that this change could inadvertently affect. A more targeted fix, scoped specifically to the setup→first-draw transition, may be preferable to a blanket removal of the conditional.

Request

Could a maintainer confirm which of the two interpretations above reflects the intended design? Once the correct direction is clarified, I'd be glad to help implement and test the fix.

manju2810 avatar Jul 06 '26 10:07 manju2810

I think maybe the thing to check next is whether the first draw is executed within the same animation frame or not. If setup and the first draw happen synchronously in the same frame, then we can treat them as one pass. However, if the first draw is spawned only after an animation frame, then we need to treat them as different frames (we can't promote to a framebuffer and have access to the previous data, e.g. if you drew a shape in setup and then apply filter(BLUR) in draw, if they happen across frames, as the reference to the previous frame's canvas texture will be invalidated.

It's been a while since I've taken a look at that part of the lifecycle. It's also possible that if you call noLoop() in setup, draw is called synchronously outside of the usual animation loop, differently than how it would normally be called. I haven't taken a look yet but if anyone is interested in finding the relevant sections of the source code, that'd help us make a decision!

davepagurek avatar Jul 13 '26 22:07 davepagurek

@davepagurek Checked this in src/core/main.js. The first draw() is not gated by requestAnimationFrame - #_start() calls this._draw() directly right after await this.#_setup() resolves:

async #_start() {
  ...
  await this.#_setup();
  if (this.hitCriticalError) return;
  if (!this._recording) {
    this._draw();
  }
}

It's only from the second _draw() call onward that requestAnimationFrame/setImmediate is used to schedule the next frame, at the end of _draw():

if (this._loop) {
  const boundDraw = this._draw.bind(this);
  this._requestAnimId = typeof window !== 'undefined' ?
    window.requestAnimationFrame(boundDraw) :
    setImmediate(boundDraw);
}

noLoop() itself (src/core/structure.js) just sets this._loop = false:

fn.noLoop = function() {
  this._loop = false;
};

It doesn't change how the first draw is scheduled either way -calling noLoop() in setup() has no bearing on this bug, since the first draw() is already synchronous relative to setup() regardless.

So there's no browser-paint/animation-frame boundary between setup() and the first draw() - they run in the same continuous flow, and it's only the second draw call that's genuinely separated by a real animation frame. That seems to support treating setup + first draw as one continuous pass, which would mean clear()'s promotion during setup() isn't wrong per se - it just needs to be properly unwound before the second draw call (the first genuinely requestAnimationFrame-scheduled one), rather than being special-cased purely on frameCount.

Happy to dig further into _promoteToFramebufferWithoutCopy() / activeFramebuffer() to help scope a concrete fix if that's useful.

manju2810 avatar Jul 15 '26 18:07 manju2810

Thanks for investigating! So that points us towards treating setup and first draw as one single pass.

davepagurek avatar Jul 15 '26 20:07 davepagurek

I found the exact spot this asymmetry comes from , _resetBuffersBeforeDraw() in src/webgpu/p5.RendererWebGPU.js:

_resetBuffersBeforeDraw() {
  this._finishActiveRenderPass();

  // Set state to PENDING - we'll decide on first draw
  if (this._pInst.frameCount > 0) {
    this._frameState = FRAME_STATE.PENDING;
  }
  ...
}

This runs before every draw cycle, but the frameCount > 0 guard means it's skipped entirely before the first draw ,so _frameState is left exactly as setup()'s clear() call set it (PROMOTED, via _promoteToFramebufferWithoutCopy()), and nothing finalizes/demotes that before draw() runs. This lines up exactly with @eupthere's earlier instrumentation (true on first draw, false from the second draw onward).

Given we've confirmed setup + first draw are one continuous pass (no animation-frame boundary between them), I think the fix is: keep letting setup's promotion carry into the first draw (that part's correct), but make sure it gets properly finalized/copied back to the canvas texture at the end of that first draw, instead of silently persisting unresolved. Will look into what "finalizing" should look like here (presumably wiring it through _finishActiveRenderPass() or wherever mainFramebuffer normally gets blitted back) if that's a useful direction ,let me know if you'd rather take it from here.

manju2810 avatar Jul 16 '26 00:07 manju2810

That sounds good so far! I'm happy to have you keep looking into this if you're up for it, it's good to have more people having context on all this! But let's also get add some tests if we can where it tries to test some of those cases, e.g. in setup it draws something and calls noLoop(), and then in draw it calls filter(BLUR) without clearing. We have some existing tests that wrap the setup lifecycle, e.g.: https://github.com/processing/p5.js/blob/5743cb5ba5aef0e1cbe01259dd1d4c17910164c4/test/unit/webgpu/p5.RendererWebGPU.js#L142-L164

...but we currently (I think?) don't have one that includes draw, and also we don't currently have anything that does that in the visual tests since they generally have already called new p5 before giving you the reference. So it'd be great to make something like visualLifecycleTest that lets you call new p5 yourself to be able to handle lifecycles and still let you do a visual test to assert that it looks correct at the end!

davepagurek avatar Jul 16 '26 19:07 davepagurek

Thanks @davepagurek, I'll take this one. My plan:

  1. Fix: Keep the setup-time promotion carrying into the first draw(), since setup and first draw are one synchronous pass. Make sure the promoted mainFramebuffer is finalized and copied back to the canvas texture at the end of that first draw, instead of staying open. Right now _resetBuffersBeforeDraw() skips its PENDING reset when frameCount === 0, so nothing closes it out.

  2. Tests: Add a visualLifecycleTest helper that lets the test call new p5 itself, so it can cover the full setup → draw lifecycle and still make a visual assertion. Then add these cases:

    • background(128) in draw() with noLoop() in setup() (the original report)
    • draw a shape in setup(), call noLoop(), then filter(BLUR) in draw() without clearing (your case)
    • a normal looping sketch, to make sure frames 2+ behave as before

One question: when noLoop() is called in setup(), would you rather finalize at the end of _draw() (always, when still PROMOTED), or inside _finishActiveRenderPass()? I'm leaning toward the end of the draw cycle so it's independent of which call triggered the promotion, but I'd like your take before I open a PR.

manju2810 avatar Oct 06 '26 18:10 manju2810

My initial intuition is also to do it at the end of _draw but let me know if you notice that causing any design complications or runtime issues!

davepagurek avatar Oct 08 '26 18:10 davepagurek

Thanks @davepagurek! I’ll finalize at the end of _draw() and add the three tests (including the visualLifecycleTest helper). I’ve set up my branch and will open a PR once it’s ready, and I’ll flag anything I run into along the way.

manju2810 avatar Oct 08 '26 21:10 manju2810