Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"scripts": {
"build": "rolldown -c",
"dev": "vite preview/",
"dev:node": "concurrently -n build,server \"rolldown -c -w\" \"node --watch preview/node/sketch.mjs\"",
"dev:global": "concurrently -n build,server \"rolldown -c -w\" \"npx vite preview/global/\"",
"docs": "documentation build ./src/**/*.js ./src/**/**/*.js --shallow -o ./docs/data.json && node ./utils/convert.mjs",
"bench": "vitest bench",
Expand Down Expand Up @@ -64,6 +65,12 @@
},
"license": "LGPL-2.1",
"browser": "./lib/p5.min.js",
"imports": {
"#platform": {
"p5-node": "./src/core/platform/node.js",
"default": "./src/core/platform/browser.js"
}
},
"exports": {
".": {
"types": "./types/p5.d.ts",
Expand Down
13 changes: 13 additions & 0 deletions preview/node/sketch.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// import p5 from "../../dist/app.node.js";
// import p5 from "../../lib/p5.node.esm.js";
import webgpu from "../../dist/webgpu/index.js";

p5.registerAddon(webgpu);

const sketch = function (p) {
p.setup = function () {
p.createCanvas(800, 600, p.WEBGPU);
};
};

new p5(sketch);
13 changes: 13 additions & 0 deletions rolldown.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ export default defineConfig([
// })
]
},
//// Node build ////
{
input: 'src/app.js',
output: {
file: './lib/p5.node.esm.js',
format: 'esm',
banner
},
resolve: {
conditionNames: ['p5-node', 'import', 'default']
},
plugins
},
//// Addon module builds (e.g. WebGPU) ////
...['webgpu'].map(module => ({
input: `src/${module}/index.js`,
Expand Down
3 changes: 2 additions & 1 deletion src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ p5.registerAddon(strands);
import svg from './shape/svg/p5.svg';
p5.registerAddon(svg);

import { waitForDocumentReady, _globalInit } from './core/init';
import { _globalInit } from './core/init';
import { waitForDocumentReady } from '#platform';
Comment on lines +67 to +68

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea for is to use the app.node.js entry point instead of reusing this one. The other entry point simply don't have the global mode stuff. Would that solution work instead?

If some kind of global mode sketch is preferred, I think the experimental new instance mode p5.ni.js probably can fit in for it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that can work, but might not solve the whole problem, because currently the platform-specific calls are scattered kind of everywhere. Having one #platform file to import from works around that. An alternative could be to have app.node.js put an object on the p5 global with those, so that the references everywhere in p5 could grab it from e.g. p5.platform.handleUncaughtErrors?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can still use the #platform import idea with the app.node.js approach. The question is more around the intended usage pattern:

  1. What import would a node.js app use vs a browser. The idea for the app.node.js is to import p5 from "p5/node" and frontend apps import p5 from "p5" which bundlers can treeshake.
  2. The node.js build don't need to be bundled, just transformed where necessary, meaning app.node.esm.js won't be needed as node.js can import the transformed app.node.js from p5/node exports and resolve normally from there. Unless the idea is to support kinda Deno style URL import where a singled bundled file would be more straightforward?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh I see. remind me, how does it work currently if you import p5 from an environment that does tree shaking? iirc we still serve built files to some degree to have things like the GLSL imports work? If so, is that system flexible enough to be used for node too, possibly just through an alternate entrypoint if we think initialization would be easier?

If some kind of global mode sketch is preferred, I think the experimental new instance mode p5.ni.js probably can fit in for it?

I think supporting something something like that would be good. I also wonder how possible it is for "true" global mode to work in node. Does globalThis work similarly in node where if you make a function setup() {} it's accessible on globalThis like in the browser? If we hit any weirdness then a p5.ni approach sounds like the right call and we can move that into the core.

waitForDocumentReady().then(_globalInit);

export default p5;
16 changes: 0 additions & 16 deletions src/core/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,3 @@ export const _globalInit = () => {
}
}
};

// make a promise that resolves when the document is ready
export const waitForDocumentReady = () => {
if (typeof document !== 'undefined') {
return new Promise((resolve, reject) => {
// if the page is ready, initialize p5 immediately
if (document.readyState === 'complete') {
resolve();
// if the page is still loading, add an event listener
// and initialize p5 as soon as it finishes loading
} else {
window.addEventListener('load', resolve, false);
}
});
}
};
32 changes: 8 additions & 24 deletions src/core/p5.Renderer2D.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Element } from '../dom/p5.Element';
import { MediaElement } from '../dom/p5.MediaElement';
import { RGBP3 } from '../color/color_constants';
import FilterRenderer2D from '../image/filterRenderer2D';
import { markP5Canvas, setCanvasSize, attachCanvas } from '#platform';
import { Matrix } from '../math/p5.Matrix';
import { PrimitiveToPath2DConverter } from '../shape/custom_shapes';
import { DefaultFill, textCoreConstants } from '../type/textCore';
Expand All @@ -26,10 +27,10 @@ class Renderer2D extends Renderer {
this.canvas.style.display = 'none';
}

if (!this.elt.id) {
this.elt.id = `defaultCanvas${p5.sketchCount++}`;
}
this.elt.classList.add('p5Canvas');
markP5Canvas(
this.elt,
this.elt.id || `defaultCanvas${p5.sketchCount++}`
);

// Extend renderer with methods of p5.Element with getters
for (const p of Object.getOwnPropertyNames(Element.prototype)) {
Expand All @@ -43,24 +44,10 @@ class Renderer2D extends Renderer {
}

// Set canvas size
this.elt.width = w * this._pixelDensity;
this.elt.height = h * this._pixelDensity;
this.elt.style.width = `${w}px`;
this.elt.style.height = `${h}px`;
setCanvasSize(this.elt, w, h, this._pixelDensity);

// Attach canvas element to DOM
if (this._pInst._userNode) {
// user input node case
this._pInst._userNode.appendChild(this.elt);
} else {
//create main element
if (document.getElementsByTagName('main').length === 0) {
let m = document.createElement('main');
document.body.appendChild(m);
}
//append canvas to main
document.getElementsByTagName('main')[0].appendChild(this.elt);
}
attachCanvas(this.elt, this._pInst._userNode);

// Get and store drawing context
this.drawingContext = this.canvas.getContext('2d', attributes);
Expand Down Expand Up @@ -139,10 +126,7 @@ class Renderer2D extends Renderer {
}
}

this.canvas.width = w * this._pixelDensity;
this.canvas.height = h * this._pixelDensity;
this.canvas.style.width = `${w}px`;
this.canvas.style.height = `${h}px`;
setCanvasSize(this.canvas, w, h, this._pixelDensity);
this.drawingContext.scale(this._pixelDensity, this._pixelDensity);

// reset canvas properties
Expand Down
27 changes: 5 additions & 22 deletions src/core/p5.Renderer3D.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { Texture } from '../webgl/p5.Texture';
import { makeFilterShader } from '../core/filterShaders';
import { getStrokeDefs } from '../webgl/enums';
import { markExperimental } from '../core/experimental';
import { markP5Canvas, setCanvasSize, attachCanvas } from '#platform';

const { STROKE_CAP_ENUM, STROKE_JOIN_ENUM } = getStrokeDefs(() => '');

Expand All @@ -44,8 +45,7 @@ export class Renderer3D extends Renderer {
// hide if offscreen buffer by default
this.canvas.style.display = 'none';
}
this.elt.id = 'defaultCanvas0';
this.elt.classList.add('p5Canvas');
markP5Canvas(this.elt, 'defaultCanvas0');

// Set and return p5.Element
this.wrappedElt = new Element(this.elt, this._pInst);
Expand All @@ -69,25 +69,11 @@ export class Renderer3D extends Renderer {
this.height = h;

// Set canvas size
this.elt.width = w * this._pixelDensity;
this.elt.height = h * this._pixelDensity;
this.elt.style.width = `${w}px`;
this.elt.style.height = `${h}px`;
setCanvasSize(this.elt, w, h, this._pixelDensity);
this._updateViewport();

// Attach canvas element to DOM
if (this._pInst._userNode) {
// user input node case
this._pInst._userNode.appendChild(this.elt);
} else {
//create main element
if (document.getElementsByTagName('main').length === 0) {
let m = document.createElement('main');
document.body.appendChild(m);
}
//append canvas to main
document.getElementsByTagName('main')[0].appendChild(this.elt);
}
attachCanvas(this.elt, this._pInst._userNode);

this.isP3D = true; //lets us know we're in 3d mode

Expand Down Expand Up @@ -1315,10 +1301,7 @@ export class Renderer3D extends Renderer {
this.width = w;
this.height = h;

this.canvas.width = w * this._pixelDensity;
this.canvas.height = h * this._pixelDensity;
this.canvas.style.width = `${w}px`;
this.canvas.style.height = `${h}px`;
setCanvasSize(this.canvas, w, h, this._pixelDensity);
this._updateViewport();
this._updateSize();

Expand Down
75 changes: 75 additions & 0 deletions src/core/platform/browser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
Browser adapter. Everything p5 needs from its host environment should go
through this module, so that non-browser builds can swap in
alternate implementations instead.
*/

// make a promise that resolves when the document is ready
export const waitForDocumentReady = () => {
if (typeof document !== 'undefined') {
return new Promise((resolve, reject) => {
// if the page is ready, initialize p5 immediately
if (document.readyState === 'complete') {
resolve();
// if the page is still loading, add an event listener
// and initialize p5 as soon as it finishes loading
} else {
window.addEventListener('load', resolve, false);
}
});
}
};

export const handleUncaughtErrors = callback => {
const handler = e => {
let error;
if (e instanceof ErrorEvent) {
error = e.error;
} else if (e instanceof PromiseRejectionEvent) {
error = e.reason;
if (!(error instanceof Error)) return;
}
if (error) callback(error);
};
window.addEventListener('error', handler, false);
window.addEventListener('unhandledrejection', handler, false);
};

export const getUserScript = () => {
// TODO: think of a more robust way to get the user's code. Refer to
// https://github.com/processing/p5.js/pull/7293.
const scripts = document.querySelectorAll('script');
return scripts[scripts.length - 1];
};

export const isCanvasElement = data => data instanceof HTMLCanvasElement;

// TODO is this the right API?
export const markP5Canvas = (elt, id) => {
elt.id = id;
elt.classList.add('p5Canvas');
};

// TODO is this the right API?
export const setCanvasSize = (elt, w, h, density) => {
elt.width = w * density;
elt.height = h * density;
elt.style.width = `${w}px`;
elt.style.height = `${h}px`;
};

// TODO is this the right API?
export const attachCanvas = (elt, userNode) => {
if (userNode) {
// user input node case
userNode.appendChild(elt);
} else {
//create main element
if (document.getElementsByTagName('main').length === 0) {
let m = document.createElement('main');
document.body.appendChild(m);
}
//append canvas to main
document.getElementsByTagName('main')[0].appendChild(elt);
}
};
34 changes: 34 additions & 0 deletions src/core/platform/node.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Node adapter, used in place of `platform.js` by the p5.node build.
*/

// There is no document to wait for
export const waitForDocumentReady = () => Promise.resolve();

export const handleUncaughtErrors = callback => {
// Node rethrows unhandled promise rejections as uncaught exceptions, so they
// are caught here too
process.on('uncaughtExceptionMonitor', error => {
if (error instanceof Error) callback(error);
});
};

// TODO: maybe read process.argv[1]?
export const getUserScript = () => undefined;

// This prop is added in the wgpu code so we can identify it here
export const isCanvasElement = data => data?.isP5WGPUCanvas === true;

// TODO is this the right API?
export const markP5Canvas = () => {};

// TODO is this the right API?
// TODO resize the window and surface once ngpu supports it
export const setCanvasSize = (elt, w, h, density) => {
elt.width = w * density;
elt.height = h * density;
};

// TODO is this the right API?
// No page to attach to on desktop
export const attachCanvas = () => {};
14 changes: 9 additions & 5 deletions src/events/acceleration.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ function acceleration(p5, fn, lifecycles) {
lifecycles.presetup = function () {
const events = ['deviceorientation', 'devicemotion'];

for (const event of events) {
window.addEventListener(event, this[`_on${event}`].bind(this), {
passive: false,
signal: this._removeSignal
});
// TODO: maybe move to platform-dependent if there's a way to do this in
// node
if (typeof window !== 'undefined') {
for (const event of events) {
window.addEventListener(event, this[`_on${event}`].bind(this), {
passive: false,
signal: this._removeSignal
});
}
}

// Initialize device orientation value
Expand Down
14 changes: 9 additions & 5 deletions src/events/keyboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@ function keyboard(p5, fn, lifecycles) {
lifecycles.presetup = function () {
const events = ['keydown', 'keyup', 'keypress', 'blur'];

for (const event of events) {
window.addEventListener(event, this[`_on${event}`].bind(this), {
passive: false,
signal: this._removeSignal
});
// TODO: maybe move to platform-dependent once there is a way to receive
// keyboard events in node
if (typeof window !== 'undefined') {
for (const event of events) {
window.addEventListener(event, this[`_on${event}`].bind(this), {
passive: false,
signal: this._removeSignal
});
}
}
};

Expand Down
30 changes: 17 additions & 13 deletions src/events/pointer.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,24 @@ function pointer(p5, fn, lifecycles) {
'dblclick',
'wheel'
];
for (const event of events) {
window.addEventListener(event, this[`_on${event}`].bind(this), {
passive: false,
signal: this._removeSignal
});
}
// TODO: maybe move to platform-dependent once there is a way to receive
// pointer events in node
if (typeof window !== 'undefined') {
for (const event of events) {
window.addEventListener(event, this[`_on${event}`].bind(this), {
passive: false,
signal: this._removeSignal
});
}

window.addEventListener(
'blur',
() => {
this.mouseIsPressed = false;
},
{ signal: this._removeSignal }
);
window.addEventListener(
'blur',
() => {
this.mouseIsPressed = false;
},
{ signal: this._removeSignal }
);
}
};

/**
Expand Down
Loading
Loading