[p5.js 2.0+ Bug Report]: `noLoop()` not working on WebGPU mode
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:
- Create a WebGPU sketch
- Run following snippet
- Canvas should be grey, but isn't
Snippet:
async function setup() {
await createCanvas(400, 400, WEBGPU);
noLoop();
}
function draw() {
background(128);
}
Canvas exists, but the draw doesn't seem to run. A workaround is using noLoop() when frameCount > 1
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.
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?
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 toclear()(viabackground()) triggers_promoteToFramebufferWithoutCopy()whenframeCount === 0, which invokesmainFramebuffer.begin(). - No corresponding call to unwind or close this promotion (e.g., an
end()or state reset) occurs before the first invocation ofdraw(). - Consequently, the first
draw()call begins execution already inside an active framebuffer render pass, while all subsequentdraw()calls begin from an unpromoted state. This produces inconsistent behavior for any logic — such asnoLoop()— 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:
-
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 firstdraw()invocation, so thatdraw()always begins from a consistent, unpromoted baseline regardless offrameCount. -
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 hownoLoop()(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 toclear().
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.
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 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.
Thanks for investigating! So that points us towards treating setup and first draw as one single pass.
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.
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!
Thanks @davepagurek, I'll take this one. My plan:
-
Fix: Keep the setup-time promotion carrying into the first
draw(), since setup and first draw are one synchronous pass. Make sure the promotedmainFramebufferis finalized and copied back to the canvas texture at the end of that first draw, instead of staying open. Right now_resetBuffersBeforeDraw()skips itsPENDINGreset whenframeCount === 0, so nothing closes it out. -
Tests: Add a
visualLifecycleTesthelper that lets the test callnew p5itself, so it can cover the full setup → draw lifecycle and still make a visual assertion. Then add these cases:background(128)indraw()withnoLoop()insetup()(the original report)- draw a shape in
setup(), callnoLoop(), thenfilter(BLUR)indraw()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.
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!
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.