From 6e27c6615e8da9343266f8f50d4251a7260393ae Mon Sep 17 00:00:00 2001 From: wouterlucas Date: Wed, 25 Nov 2026 23:07:36 +0100 Subject: [PATCH 1/3] feat: rectangle FPS benchmark with 4k/8k/16k counts and a 16k cap for L2/L3 Adds the moving-rectangle FPS benchmark (node index.js --rectangles / npm run rectangles): shared seeded scene + FPS sampler, per-framework adapters, a runner that isolates every framework/count slice in a fresh browser process under 6x CPU throttling, RAF cross-check for L2, and JSON/HTML reporting alongside the existing results. Default counts are now 4,000 / 8,000 / 16,000 (override with RECTANGLE_COUNTS). The Lightning 2 variants and the L3 renderer variants reject counts above 16,000 before creating elements (16-bit quad indices wrap past 16,384 slots); such slices are reported as unsupported 0-FPS failures instead of measuring wrapped geometry. --- .env | 10 +- frameworks/blits/src/App.js | 2 + frameworks/blits/src/index.js | 10 +- frameworks/blits/src/pages/Rectangles.js | 101 +++++++++++ frameworks/ftl-canvas-bitmap/index.js | 12 +- frameworks/ftl-canvas/index.js | 12 +- frameworks/ftl-webgl-bitmap/index.js | 21 ++- frameworks/ftl/index.js | 21 ++- frameworks/lightning2-core/index.js | 68 ++++++- frameworks/lightning2/index.js | 68 ++++++- frameworks/renderer-canvasfonts/index.js | 12 +- frameworks/renderer/index.js | 18 +- index.js | 23 ++- package.json | 3 +- readme.md | 82 ++++++++- shared/rectangleBenchmark.js | 214 +++++++++++++++++++++++ shared/rectanglePlatformAdapters.js | 158 +++++++++++++++++ testrunner/processResults.js | 10 +- testrunner/rectangleResults.js | 33 ++++ testrunner/runRectangles.js | 137 +++++++++++++++ testrunner/writeResults.js | 9 +- tests/rectangleBenchmark.test.js | 67 +++++++ tests/rectangleResults.test.js | 65 +++++++ 23 files changed, 1111 insertions(+), 45 deletions(-) create mode 100644 frameworks/blits/src/pages/Rectangles.js create mode 100644 shared/rectangleBenchmark.js create mode 100644 shared/rectanglePlatformAdapters.js create mode 100644 testrunner/rectangleResults.js create mode 100644 testrunner/runRectangles.js create mode 100644 tests/rectangleBenchmark.test.js create mode 100644 tests/rectangleResults.test.js diff --git a/.env b/.env index ed834d0..6d8d6bc 100644 --- a/.env +++ b/.env @@ -1,9 +1,9 @@ blits=true ftl=true -ftl-canvas=true -ftl-canvas-bitmap=true -ftl-webgl-bitmap=true +ftl-canvas=false +ftl-canvas-bitmap=false +ftl-webgl-bitmap=false lightning2=true -lightning2-core=true +lightning2-core=false renderer=true -renderer-canvasfonts=true +renderer-canvasfonts=false diff --git a/frameworks/blits/src/App.js b/frameworks/blits/src/App.js index 77ec37a..dc87d01 100644 --- a/frameworks/blits/src/App.js +++ b/frameworks/blits/src/App.js @@ -19,6 +19,7 @@ import Blits from '@lightningjs/blits' import Benchmark from './pages/Benchmark.js' import Memory from './pages/Memory.js' +import Rectangles from './pages/Rectangles.js' import symbols from '@lightningjs/blits/symbols' import { setRenderer } from './perf.js' @@ -35,6 +36,7 @@ export default Blits.Application({ // mounts Memory). Benchmark.ready branches on the hash and runs the // cold-startup measurement instead of the throughput sequence. { path: '/startup', component: Benchmark }, + { path: '/rectangles', component: Rectangles }, ], hooks: { async ready() { diff --git a/frameworks/blits/src/index.js b/frameworks/blits/src/index.js index b9edcba..f60ba06 100644 --- a/frameworks/blits/src/index.js +++ b/frameworks/blits/src/index.js @@ -19,8 +19,14 @@ import Blits from '@lightningjs/blits' import App from './App.js' Blits.Launch(App, 'app', { - w: 1920, - h: 1080, + w: window.location.hash.includes('rectangles') ? 1000 : 1920, + h: window.location.hash.includes('rectangles') ? 540 : 1080, + ...(window.location.hash.includes('rectangles') ? { + pixelRatio: 1, + renderQuality: 1, + canvasColor: 'white', + advanced: { quadBufferSize: 16 * 1024 * 1024 }, + } : {}), multithreaded: false, debugLevel: 1, fonts: [ diff --git a/frameworks/blits/src/pages/Rectangles.js b/frameworks/blits/src/pages/Rectangles.js new file mode 100644 index 0000000..92d371f --- /dev/null +++ b/frameworks/blits/src/pages/Rectangles.js @@ -0,0 +1,101 @@ +import Blits from '@lightningjs/blits' +import symbols from '@lightningjs/blits/symbols' +import { runRectangleBenchmark } from '../../../../shared/rectangleBenchmark.js' + +export default Blits.Component('Rectangles', { + template: ` + + + + `, + state() { + return { rectangles: [] } + }, + hooks: { + ready() { + const app = document.querySelector('#app') + if (app) { + app.style.width = '1000px' + app.style.height = '540px' + app.style.overflow = 'hidden' + } + const renderer = this[symbols['renderer']]() + runRectangleBenchmark({ + subscribeFrame: (callback) => { + renderer.on('frameTick', callback) + return () => renderer.off('frameTick', callback) + }, + drawScene: async (scene) => { + this.rectangles = Array.from({ length: scene.count }, (_, i) => ({ + id: `rect-${i}`, + x: scene.x[i], + y: scene.y[i], + size: scene.size[i], + })) + + // Build the keyed list once. This benchmark intentionally uses Blits' + // documented Element refs, not whole-list reconciliation, for motion. + await new Promise((resolve) => requestAnimationFrame(resolve)) + // $select() scans the loop collection on each first lookup. Doing + // that N times is quadratic. Enumerate Blits' exported children + // collection once and index the documented refs instead. + const elements = new Array(scene.count) + for (const child of this[symbols.children]) { + if (!child) continue + const collection = Array.isArray(child) + ? child + : Object.getPrototypeOf(child) === Object.prototype + ? Object.values(child) + : [child] + for (const element of collection) { + const match = element?.ref?.match(/^rect(\d+)$/) + if (match) elements[Number(match[1])] = element + } + } + for (let i = 0; i < scene.count; i++) { + if (!elements[i]) throw new Error(`Missing Blits rectangle ref rect${i}`) + } + const countNodes = () => { + const stack = [renderer.root] + let count = 0 + while (stack.length) { + const node = stack.pop() + count++ + for (const child of node.children) stack.push(child) + } + return count + } + const nodesBefore = countNodes() + const identities = elements.map((element) => element.node) + + const drawFrame = (frameScene) => { + for (let i = 0; i < elements.length; i++) { + elements[i].set('x', frameScene.x[i]) + } + } + // Check outside the timing samples that movement did not allocate or + // replace nodes. Do not instrument createNode inside measured frames. + drawFrame.validateScene = () => { + const nodesAfter = countNodes() + if (nodesAfter !== nodesBefore || elements.some((element, i) => element.node !== identities[i])) { + throw new Error(`Blits node population changed during motion: ${nodesBefore} -> ${nodesAfter}`) + } + return { rectangles: scene.count, nodesBefore, nodesAfter, stable: true } + } + return drawFrame + }, + }).catch((error) => console.error('Rectangle benchmark failed:', error)) + }, + }, +}) diff --git a/frameworks/ftl-canvas-bitmap/index.js b/frameworks/ftl-canvas-bitmap/index.js index 384ed49..ce1e8e5 100644 --- a/frameworks/ftl-canvas-bitmap/index.js +++ b/frameworks/ftl-canvas-bitmap/index.js @@ -7,12 +7,19 @@ import { adjectives, nouns } from '../../shared/data.js'; import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; +import { runFtlRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; const canvas = document.querySelector('canvas') +if (window.location.hash === '#rectangles') { + canvas.width = 1000; + canvas.height = 540; + canvas.style.width = '1000px'; + canvas.style.height = '540px'; +} // const ctx = canvas.getContext('2d'); -const { root, createElement, createText, signals, loadFont } = renderer({ +const app = renderer({ platform: browserPlatform, renderer: canvasRenderer(canvas, { sortChildrenByZ: false, @@ -29,6 +36,7 @@ const { root, createElement, createText, signals, loadFont } = renderer({ numImageWorkers: 0, } }); +const { root, createElement, createText, signals, loadFont } = app; const fontLoadedPromise = loadFont('bitmap', { family: 'ArialBMF', @@ -369,6 +377,8 @@ fontLoadedPromise.then(() => { createMemoryBenchmark(); } else if (hash === 'startup') { runStartupBenchmark(); + } else if (hash === 'rectangles') { + runFtlRectangleBenchmark({ app, root: rootNode, signals, createElement }); } else { runBenchmark(); } diff --git a/frameworks/ftl-canvas/index.js b/frameworks/ftl-canvas/index.js index d96a979..e9f5254 100644 --- a/frameworks/ftl-canvas/index.js +++ b/frameworks/ftl-canvas/index.js @@ -7,11 +7,18 @@ import { adjectives, nouns } from '../../shared/data.js'; import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; +import { runFtlRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; const canvas = document.querySelector('canvas') +if (window.location.hash === '#rectangles') { + canvas.width = 1000; + canvas.height = 540; + canvas.style.width = '1000px'; + canvas.style.height = '540px'; +} // const ctx = canvas.getContext('2d'); -const { root, createElement, createText, signals } = renderer({ +const app = renderer({ platform: browserPlatform, renderer: canvasRenderer(canvas, { sortChildrenByZ: false, @@ -27,6 +34,7 @@ const { root, createElement, createText, signals } = renderer({ maxTextureCount: 4096, } }); +const { root, createElement, createText, signals } = app; const colours = [ [1.0, 0.0, 0.0, 1.0], // red @@ -356,6 +364,8 @@ if (hash === 'memory') { createMemoryBenchmark(); } else if (hash === 'startup') { runStartupBenchmark(); +} else if (hash === 'rectangles') { + runFtlRectangleBenchmark({ app, root: rootNode, signals, createElement }); } else { runBenchmark(); } diff --git a/frameworks/ftl-webgl-bitmap/index.js b/frameworks/ftl-webgl-bitmap/index.js index 946e6ca..dc44af5 100644 --- a/frameworks/ftl-webgl-bitmap/index.js +++ b/frameworks/ftl-webgl-bitmap/index.js @@ -2,23 +2,35 @@ import renderer from 'ftl'; import browser from 'ftl/platform/browser'; import webgl from 'ftl/renderer/webgl'; import bitmapTextEngine from 'ftl/text/bitmap'; -import { DefaultRectShader, DefaultTextureShader, BitmapTextShader } from 'ftl/shaders'; +import { BorderShader, DefaultRectShader, DefaultTextureShader, BitmapTextShader } from 'ftl/shaders'; import { createShader } from 'ftl/shaders/create'; import { adjectives, nouns } from '../../shared/data.js'; import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; +import { runFtlRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; + +const borderShader = createShader(BorderShader); +borderShader.width = 1; +borderShader.color = [0, 0, 0, 1]; +borderShader.align = 0.5; const shaders = { rectangleShader: createShader(DefaultRectShader), textureShader: createShader(DefaultTextureShader), bmfTextShader: createShader(BitmapTextShader), - additionalShaders: [], + additionalShaders: [borderShader], } const canvas = document.querySelector('canvas') -const { root, createElement, createText, signals, loadFont } = renderer({ +if (window.location.hash === '#rectangles') { + canvas.width = 1000; + canvas.height = 540; + canvas.style.width = '1000px'; + canvas.style.height = '540px'; +} +const app = renderer({ platform: browser, renderer: webgl(canvas, shaders), text: { @@ -33,6 +45,7 @@ const { root, createElement, createText, signals, loadFont } = renderer({ numImageWorkers: 0, } }); +const { root, createElement, createText, signals, loadFont } = app; const fontLoadedPromise = loadFont('bitmap', { family: 'ArialBMF', @@ -373,6 +386,8 @@ fontLoadedPromise.then(() => { createMemoryBenchmark(); } else if (hash === 'startup') { runStartupBenchmark(); + } else if (hash === 'rectangles') { + runFtlRectangleBenchmark({ app, root: rootNode, signals, createElement, BorderShader, createShader, borderShader }); } else { runBenchmark(); } diff --git a/frameworks/ftl/index.js b/frameworks/ftl/index.js index b5cde10..f88c566 100644 --- a/frameworks/ftl/index.js +++ b/frameworks/ftl/index.js @@ -2,25 +2,37 @@ import renderer from 'ftl'; import browser from 'ftl/platform/browser'; import webgl from 'ftl/renderer/webgl'; import msdfTextEngine from 'ftl/text/msdf'; -import { DefaultRectShader, DefaultTextureShader, MsdfTextShader } from 'ftl/shaders'; +import { BorderShader, DefaultRectShader, DefaultTextureShader, MsdfTextShader } from 'ftl/shaders'; import { createShader } from 'ftl/shaders/create'; import { adjectives, nouns } from '../../shared/data.js'; import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; +import { runFtlRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; + +const borderShader = createShader(BorderShader); +borderShader.width = 1; +borderShader.color = [0, 0, 0, 1]; +borderShader.align = 0.5; const shaders = { rectangleShader: createShader(DefaultRectShader), textureShader: createShader(DefaultTextureShader), msdfTextShader: createShader(MsdfTextShader), bmfTextShader: null, - additionalShaders: [], + additionalShaders: [borderShader], } //DefaultBatchShader.setMaxTextures(16) const canvas = document.querySelector('canvas') -const { root, createElement, createText, signals, loadFont } = renderer({ +if (window.location.hash === '#rectangles') { + canvas.width = 1000; + canvas.height = 540; + canvas.style.width = '1000px'; + canvas.style.height = '540px'; +} +const app = renderer({ platform: browser, renderer: webgl(canvas, shaders), text: { @@ -36,6 +48,7 @@ const { root, createElement, createText, signals, loadFont } = renderer({ numImageWorkers: 0 } }); +const { root, createElement, createText, signals, loadFont } = app; const colours = [ @@ -387,6 +400,8 @@ if (hash === 'memory') { createMemoryBenchmark(); } else if (hash === 'startup') { runStartupBenchmark(); +} else if (hash === 'rectangles') { + runFtlRectangleBenchmark({ app, root: rootNode, signals, createElement, BorderShader, createShader, borderShader }); } else { runBenchmark(); } diff --git a/frameworks/lightning2-core/index.js b/frameworks/lightning2-core/index.js index dfd7450..aed309d 100644 --- a/frameworks/lightning2-core/index.js +++ b/frameworks/lightning2-core/index.js @@ -9,6 +9,7 @@ import { adjectives, nouns } from '../../shared/data'; import { warmup } from '../../shared/utils/warmup'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; +import { runRectangleBenchmark } from '../../shared/rectangleBenchmark.js'; // apply CSS styling const style = document.createElement('style'); @@ -35,13 +36,13 @@ const pick = dict => dict[Math.round(Math.random() * 1000) % dict.length]; const options = { stage: { - w: 1920, - h: 1080, - clearColor: 0x00000000, + w: window.location.hash === '#rectangles' ? 1000 : 1920, + h: window.location.hash === '#rectangles' ? 540 : 1080, + clearColor: window.location.hash === '#rectangles' ? 0xFFFFFFFF : 0x00000000, canvas2d: false, useImageWorker: true, - pauseRafLoopOnIdle: true, - // bufferSize: 4e6, // WvB tried to raise this to 4M but it didn't work for the 20k items test + pauseRafLoopOnIdle: window.location.hash === '#rectangles' ? false : true, + bufferMemory: window.location.hash === '#rectangles' ? 32e6 : 2e6, }, debug: false, } @@ -79,7 +80,9 @@ export class App extends Lightning.Application { _init() { // get hash of the url const hash = window.location.hash.substring(1); - if (hash === 'memory') { + if (hash === 'rectangles') { + this.runRectangleBenchmark(); + } else if (hash === 'memory') { console.log('Running memory benchmark'); this.createMemoryBenchmark(); } else if (hash === 'startup') { @@ -90,6 +93,40 @@ export class App extends Lightning.Application { } } + async runRectangleBenchmark() { + const items = this.tag('Items').childList; + await runRectangleBenchmark({ + crossCheckRaf: true, + subscribeFrame: (callback) => { + this.stage.on('frameStart', callback); + return () => this.stage.off('frameStart', callback); + }, + drawScene: (scene) => { + if (scene.count > 16000) { + throw new Error('Lightning 2 supports at most 16,000 rectangles; this slice is unsupported.'); + } + items.clear(); + for (let i = 0; i < scene.count; i++) { + items.add({ + type: Rectangle, + data: { + x: scene.x[i] - scene.size[i] / 2, + y: scene.y[i] - scene.size[i] / 2, + size: scene.size[i], + }, + }); + } + + const rectangles = Array.from({ length: scene.count }, (_, i) => items.getAt(i)); + return (frameScene) => { + for (let i = 0; i < rectangles.length; i++) { + rectangles[i].patch({ x: frameScene.x[i] - frameScene.size[i] / 2 }); + } + }; + }, + }); + } + _createRow(items, index) { const data = { color: pick(colours), @@ -414,5 +451,24 @@ export class App extends Lightning.Application { } } +class Rectangle extends Lightning.Component { + static _template() { + return { + rect: true, + color: 0xFFFFFFFF, + shader: { + type: Lightning.shaders.Outline, + width: 1, + color: 0xFF000000, + }, + }; + } + + _init() { + const { x, y, size } = this.data; + this.patch({ x, y, w: size, h: size }); + } +} + const app = new App(options); document.body.appendChild(app.stage.getCanvas()); diff --git a/frameworks/lightning2/index.js b/frameworks/lightning2/index.js index d2aa5cb..967a240 100644 --- a/frameworks/lightning2/index.js +++ b/frameworks/lightning2/index.js @@ -8,6 +8,7 @@ import { adjectives, nouns } from '../../shared/data.js'; import { warmup } from '../../shared/utils/warmup.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; +import { runRectangleBenchmark } from '../../shared/rectangleBenchmark.js'; // apply CSS styling const style = document.createElement('style'); @@ -34,13 +35,13 @@ const pick = dict => dict[Math.round(Math.random() * 1000) % dict.length]; const options = { stage: { - w: 1920, - h: 1080, - clearColor: 0x00000000, + w: window.location.hash === '#rectangles' ? 1000 : 1920, + h: window.location.hash === '#rectangles' ? 540 : 1080, + clearColor: window.location.hash === '#rectangles' ? 0xFFFFFFFF : 0x00000000, canvas2d: false, useImageWorker: true, - pauseRafLoopOnIdle: true, - // bufferSize: 4e6, // WvB tried to raise this to 4M but it didn't work for the 20k items test + pauseRafLoopOnIdle: window.location.hash === '#rectangles' ? false : true, + bufferMemory: window.location.hash === '#rectangles' ? 32e6 : 2e6, }, debug: false, } @@ -127,7 +128,9 @@ export class App extends Lightning.Application { _init() { // get hash of the url const hash = window.location.hash.substring(1); - if (hash === 'memory') { + if (hash === 'rectangles') { + this.runRectangleBenchmark(); + } else if (hash === 'memory') { console.log('Running memory benchmark'); this.createMemoryBenchmark(); } else if (hash === 'startup') { @@ -138,6 +141,40 @@ export class App extends Lightning.Application { } } + async runRectangleBenchmark() { + const items = this.tag('Items').childList; + await runRectangleBenchmark({ + crossCheckRaf: true, + subscribeFrame: (callback) => { + this.stage.on('frameStart', callback); + return () => this.stage.off('frameStart', callback); + }, + drawScene: (scene) => { + if (scene.count > 16000) { + throw new Error('Lightning 2 supports at most 16,000 rectangles; this slice is unsupported.'); + } + items.clear(); + for (let i = 0; i < scene.count; i++) { + items.add({ + type: Rectangle, + data: { + x: scene.x[i] - scene.size[i] / 2, + y: scene.y[i] - scene.size[i] / 2, + size: scene.size[i], + }, + }); + } + + const rectangles = Array.from({ length: scene.count }, (_, i) => items.getAt(i)); + return (frameScene) => { + for (let i = 0; i < rectangles.length; i++) { + rectangles[i].patch({ x: frameScene.x[i] - frameScene.size[i] / 2 }); + } + }; + }, + }); + } + _createRow(items, index) { items.childList.add({ type: Block, @@ -421,5 +458,24 @@ export class App extends Lightning.Application { } } +class Rectangle extends Lightning.Component { + static _template() { + return { + rect: true, + color: 0xFFFFFFFF, + shader: { + type: Lightning.shaders.Outline, + width: 1, + color: 0xFF000000, + }, + }; + } + + _init() { + const { x, y, size } = this.data; + this.patch({ x, y, w: size, h: size }); + } +} + const app = new App(options); document.body.appendChild(app.stage.getCanvas()); diff --git a/frameworks/renderer-canvasfonts/index.js b/frameworks/renderer-canvasfonts/index.js index 0db0075..6ee4cb7 100644 --- a/frameworks/renderer-canvasfonts/index.js +++ b/frameworks/renderer-canvasfonts/index.js @@ -24,14 +24,16 @@ import { warmup } from '../../shared/utils/warmup.js'; import { waitUntilIdle } from '../../shared/utils/waitUntilIdle.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; +import { runRendererRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; -const appHeight = 1080; -const appWidth = 1920; +const rectangleMode = window.location.hash === '#rectangles'; +const appHeight = rectangleMode ? 540 : 1080; +const appWidth = rectangleMode ? 1000 : 1920; const renderer = new RendererMain({ appWidth: appWidth, appHeight: appHeight, - clearColor: 0x00000000, + clearColor: rectangleMode ? 0xffffffff : 0x00000000, numImageWorkers: 1, renderEngine: CanvasCoreRenderer, fontEngines: [ CanvasTextRenderer ], @@ -381,6 +383,8 @@ if (hash === 'memory') { } else if (hash === 'startup') { console.log('Running startup benchmark'); runStartupBenchmark(); +} else if (hash === 'rectangles') { + runRendererRectangleBenchmark(renderer, rootNode); } else { runBenchmark(); -} \ No newline at end of file +} diff --git a/frameworks/renderer/index.js b/frameworks/renderer/index.js index 5772c8c..3f45cff 100644 --- a/frameworks/renderer/index.js +++ b/frameworks/renderer/index.js @@ -18,20 +18,28 @@ import { RendererMain } from '@lightningjs/renderer'; import { WebGlCoreRenderer, SdfTextRenderer } from '@lightningjs/renderer/webgl'; +import { Border } from '@lightningjs/renderer/webgl/shaders'; import { colours, adjectives, nouns } from '../../shared/data.js'; import { warmup } from '../../shared/utils/warmup.js'; import { waitUntilIdle } from '../../shared/utils/waitUntilIdle.js'; import { reportStartup } from '../../shared/utils/startup.js'; import { run } from '../../shared/utils/run.js'; +import { runRendererRectangleBenchmark } from '../../shared/rectanglePlatformAdapters.js'; -const appHeight = 1080; -const appWidth = 1920; +const rectangleMode = window.location.hash === '#rectangles'; +const appHeight = rectangleMode ? 540 : 1080; +const appWidth = rectangleMode ? 1000 : 1920; const renderer = new RendererMain({ appWidth: appWidth, appHeight: appHeight, - clearColor: 0x00000000, + ...(rectangleMode ? { + deviceLogicalPixelRatio: 1, + devicePhysicalPixelRatio: 1, + quadBufferSize: 16 * 1024 * 1024, + } : {}), + clearColor: rectangleMode ? 0xffffffff : 0x00000000, numImageWorkers: 1, renderEngine: WebGlCoreRenderer, fontEngines: [ SdfTextRenderer ], @@ -397,6 +405,8 @@ if (hash === 'memory') { } else if (hash === 'startup') { console.log('Running startup benchmark'); runStartupBenchmark(); +} else if (hash === 'rectangles') { + runRendererRectangleBenchmark(renderer, rootNode, Border); } else { runBenchmark(); -} \ No newline at end of file +} diff --git a/index.js b/index.js index 5b3a487..1954c8d 100644 --- a/index.js +++ b/index.js @@ -28,6 +28,7 @@ import { runStartupBenchmark } from "./testrunner/runStartup.js"; import { processResults, processStartupResults } from "./testrunner/processResults.js"; import { writeResults } from "./testrunner/writeResults.js"; import { getJavaScriptBundleSize } from "./testrunner/totalBundlefileSize.js"; +import { runRectangleBenchmarks } from "./testrunner/runRectangles.js"; /** @@ -46,6 +47,7 @@ if (args.includes('--results') || args.includes('-r')) { * Useful for validating the startup functionality quickly. */ const startupOnlyFlag = args.includes('--startup-only'); +const rectanglesOnlyFlag = args.includes('--rectangles'); /** * Checks if the './dist' directory exists. @@ -162,6 +164,7 @@ let fileSizeResults = null; * @typedef {?StartupResults} startupResults */ let startupResults = null; +const rectangleResults = {}; let idx = 0; /** @@ -170,6 +173,11 @@ let idx = 0; const browserVersion = await getBrowserVersion(); console.log('Browser version:', browserVersion); +if (rectanglesOnlyFlag) { + await runRectangleBenchmarks(dirs, browserVersion); + process.exit(0); +} + /** * Initializes the results object. * @typedef {import('./testrunner/types/results.js').Result} Result @@ -224,11 +232,17 @@ const run = async (dir) => { const fileSize = getJavaScriptBundleSize(`./dist/${dir}`); fileSizeResults[dir] = fileSize; + if (!startupOnlyFlag) { + console.log(`Running rectangle rendering benchmarks for ${dir}...`); + const frameworkRectangles = await runRectangleBenchmarks([dir], browserVersion); + Object.assign(rectangleResults, frameworkRectangles.results); + } + idx++; if (idx < dirs.length) { - run(dirs[idx]); + await run(dirs[idx]); } else { - console.log('All benchmarks done!'); + console.log('All framework benchmarks done!'); console.log('Benchmark results:'); console.log(results); @@ -265,7 +279,8 @@ const run = async (dir) => { return; } - const processedResults = processResults(results, memoryResults, fileSizeResults, startupResults); + const processedResults = processResults(results, memoryResults, fileSizeResults, startupResults, rectangleResults); + console.log('All benchmarks done!'); console.log('Processed results:'); console.log(processedResults); @@ -350,4 +365,4 @@ const writeOfficialResults = (filename) => { } -run(dirs[0]); \ No newline at end of file +run(dirs[0]); diff --git a/package.json b/package.json index 18cf00e..702e8fd 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,8 @@ "setup": "npm install && npm run build", "setup:playwright": "npx playwright install", "start": "concurrently --kill-others --success last \"npx http-server -c-1 ./dist/\" \"node index.js\"", - "start:official": "concurrently --kill-others --success last \"npx http-server -c-1 ./dist/\" \"node index.js --results\"" + "start:official": "concurrently --kill-others --success last \"npx http-server -c-1 ./dist/\" \"node index.js --results\"", + "rectangles": "node index.js --rectangles" }, "author": "", "license": "MIT", diff --git a/readme.md b/readme.md index 424c3f1..dd1033f 100644 --- a/readme.md +++ b/readme.md @@ -26,6 +26,87 @@ To run only the startup benchmark (skips the throughput and memory benchmarks, u Tune the number of cold loads per framework with `STARTUP_RUNS` (default 7) and force headless Chromium with `HEADLESS=true`. +## Rectangle rendering benchmark + +Rectangle rendering is included automatically in the **full benchmark run** +(`npm start` and `npm run start:official`). Each framework completes its +throughput, memory, startup, bundle, and rectangle tests before the runner moves +to the next framework. A rectangle FPS section is added to the same HTML +results overview. Official HTML copies +include the FPS, failures, and expandable raw diagnostics. Rectangle FPS is +reported separately and does not change the duration-based weighted score. +`--startup-only` skips rectangle rendering. + +The rectangle benchmark measures steady-state FPS while 4,000, 8,000, and +16,000 seeded, mixed-size rectangles with a 1px black border and white fill +move through a 1000x540 drawing area in a 1280x720 viewport, like the +canvas-engines comparison. Each count is run as an independent slice with the +same generated positions and per-frame horizontal movement for every enabled +framework. FPS counts each framework's render-frame/tick callback, not browser +`requestAnimationFrame` callbacks. Each count has a 1-second warmup followed by +three 1.5-second FPS samples. Like the other benchmarks, each slice applies +**6x CPU throttling before navigation** (recorded as `cpuThrottlingRate: 6`). Results are saved as +`results/rectangles_.json` and printed as a table. All framework +directories enabled in `.env` and included in `dist/` are tested. +Both L2 variants also run an independent RAF counter over each FPS sample's +exact time window. The JSON includes `rafFps` and `rafChecks` (frame-event count, +RAF count, elapsed time, and both rates) to cross-check the `frameStart` counter. +The RAF observer does not move the scene or perform rendering. + +Average FPS is not a smoothness or presented-frame guarantee. `measurements` +also record `meterFps` using the comparison's FPSMeter interval-smoothing formula +(factor 10), plus `framePacing` with median/p95/p99/max callback intervals and +counts of gaps over 25ms and 50ms. Slow frames can be visible even if average FPS +is close to 60. Neither counter waits for GPU completion or measures display +presentation; the comparison's FPSMeter has the same limitation. + +Blits constructs one native-border Element per square in a stable keyed list, +then updates cached Elements with `set('x', ...)`, without triggering the entire +list each frame. This deliberately measures Blits' Element API, not list +reconciliation. This follows the documented [loop refs](https://www.lightningjs.io/v3-docs/blits/built-in/for-loop.html#referencing-elements-in-the-for-loop) +and [border attribute](https://www.lightningjs.io/v3-docs/blits/shaders/v2-conversion-guide.html#border). +`sceneValidation` verifies that node count and identities stay constant during +movement, outside the timed samples. +The generated scene and drawing area must have the same dimensions: generating +a larger scene causes offscreen culling and misleadingly high FPS. Scene bounds +and count replacement are covered by `node --test tests/rectangleBenchmark.test.js`. +Each framework runs in its own browser process. A page error, renderer crash, or +timeout is recorded as a failure and does not stop the remaining frameworks; +each framework/count slice uses a fresh browser process, with a default timeout +of 10 minutes (`RECTANGLE_TIMEOUT_MS`). A crash at one count does not stop the +other counts or frameworks. +Per-count results are saved as soon as each slice finishes. A failed count is +recorded as 0 FPS with its error, while completed earlier counts are retained. +The default counts stop at 16,000 because both Lightning 2 variants and both +L3 renderer variants (`renderer`, `renderer-local`) reject counts above +16,000 before creating elements (16-bit quad indices wrap past 16,384 slots). +If higher counts are configured via `RECTANGLE_COUNTS`, those slices are +reported as unsupported failures (0 FPS). + +Build the enabled frameworks and serve `dist/` in one terminal: + +```sh +npm run build +npx http-server -c-1 ./dist/ +``` + +Then run the full suite in another terminal: + +```sh +node index.js +``` + +For focused troubleshooting, `npm run rectangles` (or `node index.js +--rectangles`) still runs only the rectangle suite and saves its raw JSON. + +Set `HEADLESS=true` to run Chromium headlessly. For representative performance +results, use the same browser, viewport, display scaling and hardware across +runs; browser refresh-rate limits can cap the reported FPS. The runner also +accepts `RECTANGLE_FRAMEWORKS=ftl,renderer` to select a subset and +`RECTANGLE_COUNTS=8000,16000` to select counts. `RECTANGLE_WARMUP_MS`, +`RECTANGLE_SAMPLE_MS`, and `RECTANGLE_SAMPLES` adjust the sample timings (use +short values for a smoke test, not for comparable performance results). + ## Why not use js-framework-benchmark Two reasons: @@ -78,4 +159,3 @@ As of v0.0.2 the Lightning Benchmark implements weighted mean results for differ | createLots | 0.56 | | append | 0.55 | | clear | 0.42 | - diff --git a/shared/rectangleBenchmark.js b/shared/rectangleBenchmark.js new file mode 100644 index 0000000..21f7b76 --- /dev/null +++ b/shared/rectangleBenchmark.js @@ -0,0 +1,214 @@ +/** + * Shared moving-rectangle scene and FPS sampler used by each renderer adapter. + * CPU throttling is configured by the Playwright runner before navigation. + */ +export const RECTANGLE_COUNTS = [4000, 8000, 16000]; + +export const tickFpsMeter = (meter, now) => { + if (meter.lastTick !== undefined) { + meter.frameTime += (now - meter.lastTick - meter.frameTime) / 10; + } + meter.lastTick = now; + return 1000 / meter.frameTime; +}; + +export const summarizeFrameIntervals = (intervals) => { + const sorted = [...intervals].sort((a, b) => a - b); + const percentile = (p) => sorted.length ? sorted[Math.ceil(sorted.length * p) - 1] : null; + return { + intervals: sorted.length, + medianMs: percentile(0.5), + p95Ms: percentile(0.95), + p99Ms: percentile(0.99), + maxMs: sorted.length ? sorted[sorted.length - 1] : null, + over25Ms: sorted.filter((ms) => ms > 25).length, + over50Ms: sorted.filter((ms) => ms > 50).length, + }; +}; + +export const createRectangleScene = (count, width, height, seed = 0x12345678) => { + let state = seed >>> 0; + const random = () => { + state = (Math.imul(state, 1664525) + 1013904223) >>> 0; + return state / 0x100000000; + }; + + const scene = { + count, + width, + height, + x: new Float32Array(count), + y: new Float32Array(count), + size: new Float32Array(count), + speed: new Float32Array(count), + }; + + for (let i = 0; i < count; i++) { + scene.x[i] = random() * width; + scene.y[i] = random() * height; + scene.size[i] = 10 + random() * 40; + scene.speed[i] = 1 + random(); + } + return scene; +}; + +export const advanceRectangleScene = (scene) => { + for (let i = 0; i < scene.count; i++) { + let x = scene.x[i] - scene.speed[i]; + const halfExtent = scene.size[i] / 2; + if (x + halfExtent < 0) x = scene.width + halfExtent; + scene.x[i] = x; + } +}; + +const nextFrame = () => new Promise((resolve) => requestAnimationFrame(resolve)); + +const sampleFps = (scene, drawFrame, durationMs, subscribeFrame, meter, crossCheckRaf = false) => new Promise((resolve, reject) => { + let frames = 0; + let rafFrames = 0; + let rafId; + let previousFrame; + let frameError; + const intervals = []; + const start = performance.now(); + if (crossCheckRaf) { + const countRaf = () => { + rafFrames++; + rafId = requestAnimationFrame(countRaf); + }; + rafId = requestAnimationFrame(countRaf); + } + const unsubscribe = subscribeFrame(() => { + if (frameError) return; + const now = performance.now(); + if (previousFrame !== undefined) intervals.push(now - previousFrame); + previousFrame = now; + // Same FPSMeter.tick() interval smoothing as the comparison (smoothing=10). + tickFpsMeter(meter, now); + try { + advanceRectangleScene(scene); + drawFrame(scene); + frames++; + } catch (error) { + // Some engines isolate event-listener errors. Preserve the failure rather + // than silently reporting a successful sample with fewer updates. + frameError = error; + } + }); + setTimeout(() => { + unsubscribe(); + if (crossCheckRaf) cancelAnimationFrame(rafId); + if (frameError) { + reject(frameError); + return; + } + const elapsedMs = Math.max(1, performance.now() - start); + resolve({ + fps: frames * 1000 / elapsedMs, + meterFps: 1000 / meter.frameTime, + framePacing: summarizeFrameIntervals(intervals), + frames, + elapsedMs, + ...(crossCheckRaf ? { + frames, + rafFrames, + elapsedMs, + rafFps: rafFrames * 1000 / elapsedMs, + } : {}), + }); + }, durationMs); +}); + +/** + * Run all rectangle counts. `drawScene` replaces the platform's current scene + * and returns a callback that applies the next positions for each animation + * frame. + */ +export const runRectangleBenchmark = async ({ + drawScene, + subscribeFrame, + crossCheckRaf = false, + width = 1000, + height = 540, + counts = window.__RECTANGLE_BENCHMARK_CONFIG__?.counts ?? RECTANGLE_COUNTS, + warmupMs = window.__RECTANGLE_BENCHMARK_CONFIG__?.warmupMs ?? 1000, + sampleMs = window.__RECTANGLE_BENCHMARK_CONFIG__?.sampleMs ?? 1500, + samples = window.__RECTANGLE_BENCHMARK_CONFIG__?.samples ?? 3, +}) => { + const results = {}; + + for (const count of counts) { + console.log(`Rectangle slice started! ${count}`); + try { + const scene = createRectangleScene(count, width, height); + const drawFrame = await drawScene(scene); + const meter = { frameTime: 100, lastTick: undefined }; + await nextFrame(); + await nextFrame(); + await sampleFps(scene, drawFrame, warmupMs, subscribeFrame, meter, crossCheckRaf); + + const fpsSamples = []; + const rafChecks = []; + const measurements = []; + for (let sample = 0; sample < samples; sample++) { + const measurement = await sampleFps(scene, drawFrame, sampleMs, subscribeFrame, meter, crossCheckRaf); + measurements.push(measurement); + fpsSamples.push(measurement.fps); + if (crossCheckRaf) rafChecks.push(measurement); + } + + results[count] = { + fps: fpsSamples.reduce((sum, fps) => sum + fps, 0) / fpsSamples.length, + samples: fpsSamples, + measurements, + meterFps: measurements[measurements.length - 1].meterFps, + ...(drawFrame.validateScene ? { sceneValidation: drawFrame.validateScene() } : {}), + ...(crossCheckRaf ? { + rafFps: rafChecks.reduce((sum, check) => sum + check.rafFps, 0) / rafChecks.length, + rafChecks, + } : {}), + }; + console.log(`Rectangle benchmark ${count}: ${results[count].fps.toFixed(2)} FPS`); + if (crossCheckRaf) { + console.log(`L2 RAF cross-check ${count}: ${results[count].rafFps.toFixed(2)} RAF FPS`); + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + results[count] = { fps: 0, samples: [], error: message }; + console.error(`Rectangle benchmark ${count} failed: ${message}`); + } + console.log('Rectangle slice result!', { count, result: results[count] }); + } + + console.log('Rectangles!', results); + return results; +}; + +/** Bridge the shared workload to a renderer's native rectangle API. */ +export const createRectangleAdapter = ({ createRect, destroyRect, setX, width = 1000, height = 540 }) => { + let rectangles = []; + + return { + width, + height, + drawScene(scene) { + for (const rectangle of rectangles) { + if (rectangle !== undefined) destroyRect(rectangle); + } + rectangles = new Array(scene.count); + for (let i = 0; i < scene.count; i++) { + rectangles[i] = createRect({ + x: scene.x[i], + y: scene.y[i], + size: scene.size[i], + }); + } + + return (frameScene) => { + for (let i = 0; i < rectangles.length; i++) { + setX(rectangles[i], frameScene.x[i]); + } + }; + }, + }; +}; diff --git a/shared/rectanglePlatformAdapters.js b/shared/rectanglePlatformAdapters.js new file mode 100644 index 0000000..6d10b7c --- /dev/null +++ b/shared/rectanglePlatformAdapters.js @@ -0,0 +1,158 @@ +import { createRectangleAdapter, runRectangleBenchmark } from './rectangleBenchmark.js'; + +const FTL_RECT_COLOR = [0, 0, 0, 1]; + +export const runFtlRectangleBenchmark = async ({ app, root, signals, createElement, BorderShader, createShader, borderShader }) => { + const rectangles = []; + app.addActiveCheck(() => rectangles.length > 0); + return runRectangleBenchmark({ + subscribeFrame: (callback) => signals.tick.subscribe(callback), + drawScene(scene) { + for (let i = rectangles.length - 1; i >= 0; i--) { + for (const rect of rectangles[i]) rect.destroy(); + } + rectangles.length = 0; + for (let i = 0; i < scene.count; i++) { + const size = scene.size[i]; + const rects = []; + rectangles.push(rects); + if (BorderShader) { + const shader = createShader(BorderShader); + shader.width = 1; + shader.color = borderShader.color; + shader.align = 0.5; + const rect = createElement({ + x: scene.x[i], + y: scene.y[i], + w: size, + h: size, + mountX: 0.5, + mountY: 0.5, + color: [1, 1, 1, 1], + shader, + }); + rects.push(rect); + root.addChild(rect); + } else { + const border = createElement({ + x: scene.x[i], + y: scene.y[i], + w: size, + h: size, + mountX: 0.5, + mountY: 0.5, + color: FTL_RECT_COLOR, + }); + rects.push(border); + root.addChild(border); + const fill = createElement({ + x: scene.x[i], + y: scene.y[i], + w: Math.max(0, size - 2), + h: Math.max(0, size - 2), + mountX: 0.5, + mountY: 0.5, + color: [1, 1, 1, 1], + }); + rects.push(fill); + root.addChild(fill); + } + } + + return (frameScene) => { + for (let i = 0; i < rectangles.length; i++) { + for (const rect of rectangles[i]) { + rect.x = frameScene.x[i]; + rect.dirty(); + } + } + }; + }, + }); +}; + +// L3's indexed quad buffers use 16-bit indices, so a single batch wraps past +// 16,384 geometry slots — the same limit as Lightning 2. Counts above 16,000 +// are reported as unsupported slices instead of measuring wrapped geometry. +const L3_MAX_RECTANGLES = 16000; + +export const runRendererRectangleBenchmark = async (renderer, parent = renderer.root, BorderShader = null) => { + if (BorderShader) renderer.stage.shManager.registerShaderType('RectangleBorder', BorderShader); + const adapter = createRectangleAdapter({ + createRect: ({ x, y, size }) => { + if (BorderShader) { + return renderer.createNode({ + x, + y, + w: size, + h: size, + mountX: 0.5, + mountY: 0.5, + color: 0xffffffff, + parent, + shader: renderer.createShader('RectangleBorder', { + w: 1, + color: 0x000000ff, + align: 'center', + }), + }); + } + + const node = renderer.createNode({ + x, + y, + w: size, + h: size, + mountX: 0.5, + mountY: 0.5, + color: 0x000000ff, + parent, + }); + let fill; + try { + fill = renderer.createNode({ + x, + y, + w: Math.max(0, size - 2), + h: Math.max(0, size - 2), + mountX: 0.5, + mountY: 0.5, + color: 0xffffffff, + parent, + }); + } catch (error) { + node.destroy(); + throw error; + } + return { node, fill }; + }, + destroyRect: (rect) => { + if (BorderShader) rect.destroy(); + else { + rect.node.destroy(); + rect.fill.destroy(); + } + }, + setX: (rect, x) => { + if (BorderShader) rect.x = x; + else { + rect.node.x = x; + rect.fill.x = x; + } + }, + }); + const drawScene = adapter.drawScene; + return runRectangleBenchmark({ + ...adapter, + drawScene: (scene) => { + if (scene.count > L3_MAX_RECTANGLES) { + throw new Error(`Lightning 3 renderer supports at most ${L3_MAX_RECTANGLES.toLocaleString()} rectangles; this slice is unsupported.`); + } + return drawScene(scene); + }, + subscribeFrame: (callback) => { + renderer.on('frameTick', callback); + return () => renderer.off('frameTick', callback); + }, + }); +}; diff --git a/testrunner/processResults.js b/testrunner/processResults.js index 9b423af..7624199 100644 --- a/testrunner/processResults.js +++ b/testrunner/processResults.js @@ -10,9 +10,10 @@ * @param {MemoryResults} memoryResults - The memory results object. * @param {FileSizeResultsObject} fileSizeResults - The file size results object. * @param {StartupResultsObject} [startupResults] - The startup results object. + * @param {Object} [rectangleResults] - Raw rectangle slices per framework/count. * @returns {Object} - The processed and sorted results object. */ -export const processResults = (results, memoryResults, fileSizeResults, startupResults = {}) => { +export const processResults = (results, memoryResults, fileSizeResults, startupResults = {}, rectangleResults = {}) => { const processedResults = {}; const fastestTimes = { create: null, @@ -103,6 +104,11 @@ export const processResults = (results, memoryResults, fileSizeResults, startupR if (startupCells[f]) { processedResults[f].startup = startupCells[f]; } + // FPS and its diagnostics are reported independently, not mixed into + // the duration-based weighted operation score or framework ordering. + if (rectangleResults[f]) { + processedResults[f].rectangles = rectangleResults[f]; + } }); // sort the frameworks by avgMean @@ -299,4 +305,4 @@ const computeColor = function (factor) { const b = (1.0 - a) * 132 + a * 108; return `rgb(${r.toFixed(0)}, ${g.toFixed(0)}, ${b.toFixed(0)})`; } -} \ No newline at end of file +} diff --git a/testrunner/rectangleResults.js b/testrunner/rectangleResults.js new file mode 100644 index 0000000..909d5cc --- /dev/null +++ b/testrunner/rectangleResults.js @@ -0,0 +1,33 @@ +import { RECTANGLE_COUNTS } from '../shared/rectangleBenchmark.js'; + +const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (char) => ({ + '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', +})[char]); + +/** Render the FPS section in the shared results table, preserving slice errors. */ +export const renderRectangleSection = (results, frameworks, frameworkVersions = {}) => { + const counts = [...new Set(frameworks.flatMap((framework) => + Object.keys(results[framework].rectangles || {}).map(Number).filter(Number.isFinite), + ))].sort((a, b) => a - b); + if (!counts.length) counts.push(...RECTANGLE_COUNTS); + + const rows = counts.map((count) => { + const cells = frameworks.map((framework) => { + const slice = results[framework].rectangles?.[count]; + if (!slice) return 'n/a'; + if (slice.error) { + return `
FAIL (0 FPS)${escapeHtml(slice.error)}
`; + } + if (!Number.isFinite(slice.fps)) return 'n/a'; + // Include the complete diagnostics in the HTML itself so official copies + // are self-contained and do not depend on a local raw JSON file. + const diagnostics = escapeHtml(JSON.stringify(slice, null, 2)); + return `
${slice.fps.toFixed(2)} FPS
${diagnostics}
`; + }).join(''); + return `${count.toLocaleString('en-US')} moving rectangles${cells}`; + }).join('\n'); + + return `Rectangle rendering (FPS, higher is better)${frameworks.map((framework) => + `${escapeHtml(framework)} ${escapeHtml(frameworkVersions[framework] ?? '')}`, + ).join('')}${rows}`; +}; diff --git a/testrunner/runRectangles.js b/testrunner/runRectangles.js new file mode 100644 index 0000000..fa1b9e1 --- /dev/null +++ b/testrunner/runRectangles.js @@ -0,0 +1,137 @@ +import fs from 'fs'; +import { chromium } from 'playwright'; +import { RECTANGLE_COUNTS } from '../shared/rectangleBenchmark.js'; + +const DEFAULT_SLICE_TIMEOUT_MS = 10 * 60 * 1000; + +/** Run each rectangle-count slice in an isolated browser process. */ +export const runRectangleBenchmarks = async (frameworks, browserVersion) => { + const counts = process.env.RECTANGLE_COUNTS + ? process.env.RECTANGLE_COUNTS.split(',').map((count) => Number.parseInt(count, 10)).filter(Number.isFinite) + : RECTANGLE_COUNTS; + const cpuThrottlingRate = 6; + const warmupMs = Number.parseInt(process.env.RECTANGLE_WARMUP_MS || '1000', 10); + const sampleMs = Number.parseInt(process.env.RECTANGLE_SAMPLE_MS || '1500', 10); + const samples = Number.parseInt(process.env.RECTANGLE_SAMPLES || '3', 10); + const timeoutMs = Number.parseInt(process.env.RECTANGLE_TIMEOUT_MS || `${DEFAULT_SLICE_TIMEOUT_MS}`, 10); + const requestedFrameworks = process.env.RECTANGLE_FRAMEWORKS?.split(',').map((name) => name.trim()).filter(Boolean); + const baseUrl = process.env.RECTANGLE_BASE_URL || 'http://localhost:8080'; + if (requestedFrameworks?.length) { + frameworks = frameworks.filter((framework) => requestedFrameworks.includes(framework)); + } + + const startedAt = new Date(); + const filename = `rectangles_${startedAt.toISOString().replace(/[:.]/g, '-')}.json`; + const results = {}; + fs.mkdirSync('./results', { recursive: true }); + const writePartialResults = () => { + fs.writeFileSync(`./results/${filename}`, JSON.stringify({ + date: startedAt.toISOString(), + browser: browserVersion, + viewport: '1280x720 @ 1x; rectangle area 1000x540', + counts, + warmupMs, + sampleMs, + samplesPerCount: samples, + timeoutMs, + cpuThrottlingRate, + measurement: 'renderer-callback FPS, not GPU completion or presentation', + fpsMeterSmoothing: 10, + results, + }, null, 2)); + }; + + const runSlice = async (framework, count) => { + let browser; + let context; + let timeout; + + try { + // Isolating every count means a renderer crash at 16k cannot discard 4k/8k, + // and the next count gets a clean process and graphics context. + browser = await chromium.launch({ headless: process.env.HEADLESS === 'true' }); + context = await browser.newContext({ + viewport: { width: 1280, height: 720 }, + deviceScaleFactor: 1, + }); + const page = await context.newPage(); + const client = await context.newCDPSession(page); + await client.send('Emulation.setCPUThrottlingRate', { rate: cpuThrottlingRate }); + await page.addInitScript((config) => { + window.__RECTANGLE_BENCHMARK_CONFIG__ = config; + }, { counts: [count], warmupMs, sampleMs, samples }); + + const result = await new Promise((resolve, reject) => { + let settled = false; + const finish = (callback, value) => { + if (settled) return; + settled = true; + clearTimeout(timeout); + callback(value); + }; + timeout = setTimeout(() => finish( + reject, + new Error(`${framework} ${count} rectangle slice timed out after ${timeoutMs}ms`), + ), timeoutMs); + + page.on('console', async (message) => { + if (!message.text().startsWith('Rectangles!')) return; + try { + const results = await message.args()[1].jsonValue(); + finish(resolve, results[count]); + } catch (error) { + finish(reject, error); + } + }); + page.on('pageerror', (error) => finish(reject, error)); + page.on('crash', () => finish(reject, new Error(`${framework} page crashed at ${count} rectangles`))); + browser.on('disconnected', () => finish(reject, new Error(`${framework} browser process disconnected at ${count} rectangles`))); + + const url = framework === 'blits' + ? `${baseUrl}/${framework}/#/rectangles` + : `${baseUrl}/${framework}/#rectangles`; + page.goto(url).catch((error) => finish(reject, error)); + }); + + if (!result) throw new Error(`${framework} did not return a result for ${count} rectangles`); + return result; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + console.error(`Rectangle slice failed for ${framework} at ${count}: ${message}`); + return { fps: 0, samples: [], error: message }; + } finally { + clearTimeout(timeout); + await context?.close().catch(() => {}); + await browser?.close().catch(() => {}); + } + }; + + writePartialResults(); + for (const framework of frameworks) { + results[framework] = {}; + for (const count of counts) { + console.log(`Running rectangle benchmark for ${framework} at ${count.toLocaleString()} rectangles`); + results[framework][count] = await runSlice(framework, count); + const slice = results[framework][count]; + console.log(`${framework} ${count.toLocaleString()}: ${slice.error || `${slice.fps.toFixed(2)} FPS`}`); + if (slice.rafFps !== undefined) { + console.log(` RAF cross-check: ${slice.rafFps.toFixed(2)} FPS`); + } + if (slice.measurements) { + console.log(` FPSMeter-style: ${slice.meterFps.toFixed(2)} FPS; p95 intervals: ${slice.measurements.map((m) => m.framePacing.p95Ms?.toFixed(1) ?? '-').join(', ')}ms`); + } + writePartialResults(); + } + } + + console.log('Average FPS by framework and rectangle count:'); + console.table(Object.fromEntries(Object.entries(results).map(([framework, slices]) => [ + framework, + Object.fromEntries(Object.entries(slices).map(([count, result]) => [ + count, + result.error ? `FAIL (${result.error})` : `${result.fps.toFixed(2)} FPS`, + ])), + ]))); + console.log(`Rectangle results written to ./results/${filename}`); + return JSON.parse(fs.readFileSync(`./results/${filename}`, 'utf8')); +}; diff --git a/testrunner/writeResults.js b/testrunner/writeResults.js index b106ab5..513421c 100644 --- a/testrunner/writeResults.js +++ b/testrunner/writeResults.js @@ -17,6 +17,7 @@ import fs from 'fs'; import { getOSInfo, getSystemInfo } from "./systemInfo.js"; +import { renderRectangleSection } from './rectangleResults.js'; const indexHeader = ` @@ -286,10 +287,11 @@ export const writeResults = (results, frameworkVersions, browserVersion) => { const hasMemory = frameworks.some(f => results[f].memory); const hasStartup = frameworks.some(f => results[f].startup); const hasFileSize = frameworks.some(f => results[f].fileSize !== undefined); + const hasRectangles = frameworks.some(f => results[f].rectangles); // write the results header with only the relevant descriptions fileStream.write(resultsHeader.replace('{{resultsDescription}}', - `${hasOps ? opsDescription : ''}${hasStartup ? startupDescription : ''}` + `${hasOps ? opsDescription : ''}${hasStartup ? startupDescription : ''}${hasRectangles ? '

Rectangle rendering: average callback FPS (higher is better), 6x CPU slowdown, 1000x540 drawing area. Reported separately from the weighted operation score; expand a cell for frame-pacing and failure details.

' : ''}` )); // write some html @@ -371,6 +373,10 @@ export const writeResults = (results, frameworkVersions, browserVersion) => { ); } + if (hasRectangles) { + sections.push(renderRectangleSection(results, frameworks, frameworkVersions)); + } + fileStream.write(table.replace('{{sections}}', sections.join('\n'))); // write the footer @@ -385,4 +391,3 @@ export const writeResults = (results, frameworkVersions, browserVersion) => { }); }); } - diff --git a/tests/rectangleBenchmark.test.js b/tests/rectangleBenchmark.test.js new file mode 100644 index 0000000..0d14985 --- /dev/null +++ b/tests/rectangleBenchmark.test.js @@ -0,0 +1,67 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { + createRectangleAdapter, + createRectangleScene, + advanceRectangleScene, + summarizeFrameIntervals, + RECTANGLE_COUNTS, + tickFpsMeter, +} from '../shared/rectangleBenchmark.js'; + +test('default loads are 4k, 8k and 16k', () => { + assert.deepEqual(RECTANGLE_COUNTS, [4000, 8000, 16000]); +}); + +test('FPSMeter smoothing matches the reference tick formula', () => { + const meter = { frameTime: 20, lastTick: 100 }; + assert.equal(tickFpsMeter(meter, 140), 1000 / 22); + assert.equal(meter.lastTick, 140); + assert.equal(tickFpsMeter(meter, 160), 1000 / 21.8); +}); + +test('frame pacing exposes long gaps hidden by average FPS', () => { + const pacing = summarizeFrameIntervals([16, 17, 16, 100, 16]); + assert.equal(pacing.medianMs, 16); + assert.equal(pacing.p95Ms, 100); + assert.equal(pacing.maxMs, 100); + assert.equal(pacing.over25Ms, 1); + assert.equal(pacing.over50Ms, 1); + assert.equal(summarizeFrameIntervals([]).p95Ms, null); +}); + +test('adapter scene dimensions match the 1000x540 drawing area', () => { + const adapter = createRectangleAdapter({ + createRect: (props) => props, + destroyRect: () => {}, + setX: () => {}, + }); + assert.equal(adapter.width, 1000); + assert.equal(adapter.height, 540); + const scene = createRectangleScene(32000, adapter.width, adapter.height); + for (let i = 0; i < scene.count; i++) { + assert.ok(scene.x[i] >= 0 && scene.x[i] <= adapter.width); + assert.ok(scene.y[i] >= 0 && scene.y[i] <= adapter.height); + } +}); + +test('adapter replaces the previous slice rather than accumulating rectangles', () => { + const created = []; + const destroyed = []; + const adapter = createRectangleAdapter({ + createRect: (props) => { + created.push(props); + return props; + }, + destroyRect: (rect) => destroyed.push(rect), + setX: (rect, x) => { rect.x = x; }, + }); + adapter.drawScene(createRectangleScene(4000, adapter.width, adapter.height)); + const scene = createRectangleScene(8000, adapter.width, adapter.height); + const drawFrame = adapter.drawScene(scene); + assert.equal(created.length, 12000); + assert.equal(destroyed.length, 4000); + advanceRectangleScene(scene); + drawFrame(scene); + assert.equal(created[4000].x, scene.x[0]); +}); diff --git a/tests/rectangleResults.test.js b/tests/rectangleResults.test.js new file mode 100644 index 0000000..33b0e63 --- /dev/null +++ b/tests/rectangleResults.test.js @@ -0,0 +1,65 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import fs from 'node:fs/promises'; +import { processResults } from '../testrunner/processResults.js'; +import { renderRectangleSection } from '../testrunner/rectangleResults.js'; +import { writeResults } from '../testrunner/writeResults.js'; + +test('full result processing keeps rectangle slices without changing the weighted score', () => { + const operations = { a: { create: '10ms' }, b: { create: '20ms' } }; + const rectangles = { + a: { 8000: { fps: 50, samples: [50] }, 16000: { fps: 0, error: 'crash' } }, + b: { 8000: { fps: 60, samples: [60] } }, + }; + const baseline = processResults(operations, {}, {}, {}); + const combined = processResults(operations, {}, {}, {}, rectangles); + assert.deepEqual(Object.keys(combined), Object.keys(baseline)); + for (const framework of Object.keys(operations)) { + assert.equal(combined[framework].avgMean, baseline[framework].avgMean); + assert.deepEqual(combined[framework].rectangles, rectangles[framework]); + } +}); + +test('overview renders FPS, pacing diagnostics, escaped failures, and missing slices', () => { + const html = renderRectangleSection({ + a: { rectangles: { + 8000: { fps: 42.125, measurements: [{ framePacing: { p95Ms: 50 } }] }, + 64000: { fps: 0, error: '' }, + } }, + b: {}, + }, ['a', 'b'], { a: '1.0' }); + assert.match(html, /42\.13 FPS/); + assert.match(html, /8,000 moving rectangles/); + assert.match(html, /64,000 moving rectangles/); + assert.match(html, /FAIL \(0 FPS\)/); + assert.match(html, /p95Ms/); + assert.match(html, /<script>crash<\/script>/); + assert.doesNotMatch(html, /' }, + 64000: { fps: 0, error: ' ' }, } }, b: {}, }, ['a', 'b'], { a: '1.0' }); @@ -34,7 +34,8 @@ test('overview renders FPS, pacing diagnostics, escaped failures, and missing sl assert.match(html, /FAIL \(0 FPS\)/); assert.match(html, /p95Ms/); assert.match(html, /<script>crash<\/script>/); - assert.doesNotMatch(html, /