Skip to content

Commit 56535d3

Browse files
obiotclaude
andcommitted
TextureAtlas: compute quad UVs from the image size instead of caching them
drawImage and drawPattern now work a source rectangle's UVs out with four divisions by the image size, into a per-atlas scratch array: no string key, no allocation, and nothing stored per rectangle. - a page whose JSON size differs from its image (or whose frames were normalised by several sizes) keeps its frames' own UVs, found through an x -> y -> size index built by addUVs - the size is read when the pixels go to the GPU: on the first draw, and again after CanvasRenderTarget#invalidate (through the new TextureCache#sizeChanged); videos and 0x0 images are read every draw - getUVs(x, y, w, h) returns a frame's own UVs for a frame of the active page and a new array otherwise; a "x,y,w,h" string is no longer read as a rectangle, and frames no longer get "x,y,w,h" alias keys - both drawPattern implementations compute the UVs last, right before addQuad, since the scratch array is only valid until the next call Bit-identical to 20.10.1's UVs on every shipped atlas (fuzzed against the old implementation); the example sweep adds no new warning, error or "x,y,w,h" region. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SeWCkETjW35ZbXDRswV1hx
1 parent 4d3d165 commit 56535d3

10 files changed

Lines changed: 1080 additions & 93 deletions

File tree

‎packages/melonjs/CHANGELOG.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
# Changelog
22

3-
## _unreleased_
3+
## [20.11.0] (melonJS 2) - _unreleased_
44

55
### Fixed
6-
- TextureAtlas: source-rectangle UVs are cached separately from named frames, so cropped image and pattern draws no longer add regions to the animation dictionary. `getUVs(name)` now throws for an unknown name instead of parsing it as coordinates; use `getUVs(x, y, width, height)` for a source rectangle, or define a named region with `addRegion()` before looking it up ([#1281](https://github.com/melonjs/melonJS/issues/1281)). (thanks @snowyukitty)
6+
- TextureAtlas: drawing part of an image, a bitmap font glyph or a repeating pattern no longer adds a region to the atlas for every new source rectangle. Those regions piled up for as long as the atlas lived, and turned up among the frames an animation is built from ([#1281](https://github.com/melonjs/melonJS/issues/1281), thanks @snowyukitty)
7+
- TextureAtlas: on an atlas with pages of different sizes, a source rectangle drawn from one page no longer reuses the UVs worked out for the same rectangle on another (thanks @snowyukitty)
8+
9+
### Performance
10+
- Rendering: drawing a sprite, a glyph or a pattern computes its UVs from the image size instead of looking them up, with no string built and nothing allocated or kept. On the platformer, text and Jungle Rabbit examples a lookup took 34 to 58 ns and now takes 6 to 10, in Chrome and WebKit: 1 to 2% of a frame's CPU time on the text example, and too little to measure on the platformer
711

812
## [20.10.1] (melonJS 2) - _2026-10-21_
913

‎packages/melonjs/src/video/rendertarget/canvasrendertarget.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,9 @@ class CanvasRenderTarget extends RenderTarget {
314314
renderer.cache.get(this.canvas),
315315
);
316316
renderer.currentBatcher.markTextureDirty(this.glTextureUnit);
317+
// the new pixels may come at a new size, and UVs are worked out
318+
// from the size of the pixels on the GPU
319+
renderer.cache.sizeChanged(this.canvas);
317320
} else if (renderer.type === "WebGPU" && renderer.cache.has(this.canvas)) {
318321
// drain pending vertices, then re-upload the canvas. The store
319322
// gives the new pixels a fresh GPUTexture when draws recorded
@@ -324,6 +327,7 @@ class CanvasRenderTarget extends RenderTarget {
324327
renderer.textureStore.getBinding(renderer.cache.get(this.canvas), {
325328
force: true,
326329
});
330+
renderer.cache.sizeChanged(this.canvas);
327331
}
328332
}
329333

‎packages/melonjs/src/video/texture/atlas.js‎

Lines changed: 197 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import Texture2d from "./texture2d.ts";
1717
// (`on`, not `once`: a re-init — new Application after destroy — must
1818
// re-capture the new renderer).
1919
let _renderer;
20+
2021
on(VIDEO_INIT, (renderer) => {
2122
/**
2223
* @ignore
@@ -25,6 +26,28 @@ on(VIDEO_INIT, (renderer) => {
2526
_renderer = renderer;
2627
});
2728

29+
/**
30+
* The stored UVs of the frame at exactly this source rectangle of a page.
31+
* @param {object} page - a page's record from `TextureAtlas#_pageUVs`
32+
* @param {number} x - source x coordinate
33+
* @param {number} y - source y coordinate
34+
* @param {number} w - source width
35+
* @param {number} h - source height
36+
* @returns {Float32Array|undefined} the frame's UVs, if one is there
37+
* @ignore
38+
*/
39+
function frameUVs(page, x, y, w, h) {
40+
const corner = page.frames.get(x)?.get(y);
41+
if (corner !== undefined) {
42+
for (const f of corner) {
43+
if (f.width === w && f.height === h) {
44+
return f.uvs;
45+
}
46+
}
47+
}
48+
return undefined;
49+
}
50+
2851
/**
2952
* additional import for TypeScript
3053
* @import {CompressedImage} from "../../loader/parsers/compressed_textures/compressed_image.js";
@@ -180,18 +203,38 @@ export class TextureAtlas extends Texture2d {
180203
this.activeAtlas = undefined;
181204

182205
/**
183-
* Source-rectangle UVs, separate from the named regions in each atlas.
206+
* Per atlas page: the size its frames' UVs were normalized by, and
207+
* its frames by source rectangle (x, then y, then the frames at that
208+
* corner), kept out of the page dictionary that animation code
209+
* walks. See {@link TextureAtlas#addUVs}.
184210
* @ignore
185211
* @internal
186212
*/
187-
this._uvsByAtlas = new WeakMap();
213+
this._pageUVs = new WeakMap();
188214

189215
/**
190-
* Last numeric lookup, scoped to its atlas page.
216+
* What {@link TextureAtlas#_quadUVs} writes a computed rectangle into,
217+
* so a draw allocates nothing. Overwritten by the next call.
191218
* @ignore
192219
* @internal
193220
*/
194-
this._uvCache = { atlas: null, sx: -1, sy: -1, sw: -1, sh: -1, uvs: null };
221+
this._uvScratch = new Float32Array(4);
222+
223+
/**
224+
* The image and page last drawn from, their size, and whether that
225+
* page computes every UV from it, so a draw from the same page
226+
* decides nothing. See {@link TextureAtlas#_quadUVs}.
227+
* @ignore
228+
* @internal
229+
*/
230+
this._uvSizeCheck = {
231+
source: null,
232+
page: null,
233+
width: 0,
234+
height: 0,
235+
fixed: false,
236+
computed: true,
237+
};
195238

196239
// parse given atlas(es) paremeters
197240
if (typeof atlases !== "undefined") {
@@ -452,94 +495,144 @@ export class TextureAtlas extends Texture2d {
452495
}
453496

454497
/**
455-
* Return precomputed UVs for a named region, or cached UVs for a numeric
456-
* source rectangle. Numeric lookups do not add regions to the atlas.
498+
* Return the UVs of a named region, or of a source rectangle of the
499+
* active page.
500+
*
501+
* A rectangle that is one of the active page's frames returns that
502+
* frame's own UVs. Any other rectangle returns a new array, computed from
503+
* the size of the active page's image: nothing is cached and nothing is
504+
* added to the atlas.
457505
* @param {string|number} name - region (or frame) name, or sx when using numeric parameters
458506
* @param {number} [sy] - source y coordinate (when using numeric parameters)
459507
* @param {number} [sw] - source width (when using numeric parameters)
460508
* @param {number} [sh] - source height (when using numeric parameters)
461509
* @returns {Float32Array} region Uvs
462-
* @throws {Error} if the named region does not exist
510+
* @throws {Error} if no region has that name
463511
*/
464512
getUVs(name, sy, sw, sh) {
465513
if (typeof name === "number") {
466-
const sx = name;
467-
const atlas = this.getAtlas();
468-
const cache = this._uvCache;
469-
// fast path: return cached UVs if coordinates match last lookup
470-
if (
471-
atlas === cache.atlas &&
472-
sx === cache.sx &&
473-
sy === cache.sy &&
474-
sw === cache.sw &&
475-
sh === cache.sh
476-
) {
477-
return cache.uvs;
478-
}
479-
const rectangles = this._getUVCache(atlas, sx, sy, sw);
480-
let uvs = rectangles.get(sh);
481-
if (typeof uvs === "undefined") {
482-
const source = this.getTexture();
483-
const width = source.width || source.videoWidth;
484-
const height = source.height || source.videoHeight;
485-
uvs = new Float32Array([
486-
sx / width,
487-
sy / height,
488-
(sx + sw) / width,
489-
(sy + sh) / height,
490-
]);
491-
rectangles.set(sh, uvs);
492-
}
493-
cache.atlas = atlas;
494-
cache.sx = sx;
495-
cache.sy = sy;
496-
cache.sw = sw;
497-
cache.sh = sh;
498-
cache.uvs = uvs;
499-
return uvs;
514+
const page = this._pageUVs.get(this.getAtlas());
515+
const frame =
516+
page === undefined ? undefined : frameUVs(page, name, sy, sw, sh);
517+
return (
518+
frame ??
519+
Float32Array.from(this._quadUVs(this.getTexture(), name, sy, sw, sh))
520+
);
500521
}
501522

502-
// string-based lookup (named regions)
503523
const region = this.getRegion(name);
504-
505-
if (typeof region?.uvs === "undefined") {
506-
throw new Error("Texture - region for " + name + " not found");
524+
if (typeof region?.uvs !== "undefined") {
525+
return region.uvs;
507526
}
508-
return region.uvs;
527+
throw new Error("Texture - region for " + name + " not found");
509528
}
510529

511530
/**
512-
* Locate a rectangle's height-keyed UV map without constructing string keys.
513-
* @param {object} atlas - atlas dictionary
514-
* @param {number} x - source x coordinate
515-
* @param {number} y - source y coordinate
516-
* @param {number} width - source width
517-
* @returns {Map<number, Float32Array>} cached UVs by source height
531+
* The UVs a renderer draws a source rectangle of the active page with.
532+
*
533+
* Computed, not looked up: four divisions by the page's size. The
534+
* result is written into one scratch array, so a draw allocates nothing
535+
* and the next call overwrites it; read it straight away.
536+
*
537+
* A frame's UVs are normalized by the size its atlas file gives, which
538+
* is the page's own size unless the image was exported or loaded at
539+
* another scale than its file describes. On such a page a frame is drawn
540+
* with its own UVs, as it always was, and anything else with the page's
541+
* real size. Which kind of page this is gets decided once, and again
542+
* when another page or image is drawn from, or when the image's pixels
543+
* are replaced (see {@link TextureAtlas#_decideUVs}).
544+
* @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|ImageBitmap|OffscreenCanvas|CompressedImage} source - the active page's image, as drawn
545+
* @param {number} sx - source x coordinate
546+
* @param {number} sy - source y coordinate
547+
* @param {number} sw - source width
548+
* @param {number} sh - source height
549+
* @returns {Float32Array} the UVs, valid until the next call
518550
* @ignore
519551
* @internal
520552
*/
521-
_getUVCache(atlas, x, y, width) {
522-
let byX = this._uvsByAtlas.get(atlas);
523-
if (typeof byX === "undefined") {
524-
byX = new Map();
525-
this._uvsByAtlas.set(atlas, byX);
526-
}
527-
let byY = byX.get(x);
528-
if (typeof byY === "undefined") {
529-
byY = new Map();
530-
byX.set(x, byY);
553+
_quadUVs(source, sx, sy, sw, sh) {
554+
const check = this._uvSizeCheck;
555+
// kept small so engines inline it into the draw: deciding a page and
556+
// reading a frame's own UVs are the rare work, out of line
557+
if (
558+
check.source !== source ||
559+
check.page !== this.activeAtlas ||
560+
!check.fixed
561+
) {
562+
this._decideUVs(source);
531563
}
532-
let byWidth = byY.get(y);
533-
if (typeof byWidth === "undefined") {
534-
byWidth = new Map();
535-
byY.set(y, byWidth);
564+
if (!check.computed) {
565+
const frame = frameUVs(
566+
this._pageUVs.get(this.getAtlas()),
567+
sx,
568+
sy,
569+
sw,
570+
sh,
571+
);
572+
if (frame !== undefined) {
573+
return frame;
574+
}
536575
}
537-
let byHeight = byWidth.get(width);
538-
if (typeof byHeight === "undefined") {
539-
byHeight = new Map();
540-
byWidth.set(width, byHeight);
576+
const width = check.width;
577+
const height = check.height;
578+
const uvs = this._uvScratch;
579+
uvs[0] = sx / width;
580+
uvs[1] = sy / height;
581+
uvs[2] = (sx + sw) / width;
582+
uvs[3] = (sy + sh) / height;
583+
return uvs;
584+
}
585+
586+
/**
587+
* The out-of-line half of {@link TextureAtlas#_quadUVs}: read the size
588+
* of the image drawn from, and decide whether the active page computes
589+
* every UV from it.
590+
*
591+
* The size is read when the image's pixels go to the GPU: the first
592+
* time it is drawn, and again after {@link TextureAtlas#_sizeChanged},
593+
* which a canvas render target's `invalidate()` calls when it hands the
594+
* GPU new pixels, maybe at a new size. Between those, a resized canvas
595+
* still shows its old pixels on the GPU, and the old size is the one
596+
* that samples them; reading a DOM image's size also costs more than the
597+
* whole computation. A video is read on every draw, as it uploads every
598+
* frame, and so is an image with no size yet, one still loading.
599+
* @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|ImageBitmap|OffscreenCanvas|CompressedImage} source - the active page's image, as drawn
600+
* @ignore
601+
* @internal
602+
*/
603+
_decideUVs(source) {
604+
const check = this._uvSizeCheck;
605+
const width = source.width || source.videoWidth;
606+
const height = source.height || source.videoHeight;
607+
if (
608+
check.source === source &&
609+
check.page === this.activeAtlas &&
610+
check.width === width &&
611+
check.height === height
612+
) {
613+
return;
541614
}
542-
return byHeight;
615+
const page = this._pageUVs.get(this.getAtlas());
616+
check.source = source;
617+
check.page = this.activeAtlas;
618+
check.width = width;
619+
check.height = height;
620+
check.fixed =
621+
width > 0 && height > 0 && typeof source.videoWidth !== "number";
622+
check.computed =
623+
page === undefined ||
624+
(!page.mixed && page.width === width && page.height === height);
625+
}
626+
627+
/**
628+
* Read the image's size and decide its page again on the next draw:
629+
* the image's pixels are being replaced, maybe at another size, or a
630+
* new frame changed what its page needs.
631+
* @ignore
632+
* @internal
633+
*/
634+
_sizeChanged() {
635+
this._uvSizeCheck.source = null;
543636
}
544637

545638
/**
@@ -562,11 +655,39 @@ export class TextureAtlas extends Texture2d {
562655
(s.x + sw) / w, // u1 (right)
563656
(s.y + sh) / h, // v1 (bottom)
564657
]);
565-
// Numeric draws reuse the frame's precomputed UVs without exposing
566-
// coordinate aliases to animation consumers of the atlas dictionary.
567-
this._getUVCache(atlas, s.x, s.y, sw).set(sh, atlas[name].uvs);
568-
// A newly defined region may replace the UVs from the last lookup.
569-
this._uvCache.atlas = null;
658+
// Indexed by source rectangle beside the page, not in it: animation
659+
// code walks the page dictionary, and a second key per frame would
660+
// show up there. Also note the size these UVs were normalized by:
661+
// a draw computes its UVs from the page's own size, and only a page
662+
// where that would differ needs a frame's stored UVs.
663+
let page = this._pageUVs.get(atlas);
664+
if (page === undefined) {
665+
page = { width: w, height: h, mixed: false, frames: new Map() };
666+
this._pageUVs.set(atlas, page);
667+
} else if (page.width !== w || page.height !== h) {
668+
page.mixed = true;
669+
}
670+
let column = page.frames.get(s.x);
671+
if (column === undefined) {
672+
column = new Map();
673+
page.frames.set(s.x, column);
674+
}
675+
let corner = column.get(s.y);
676+
if (corner === undefined) {
677+
corner = [];
678+
column.set(s.y, corner);
679+
}
680+
const entry = { width: sw, height: sh, uvs: atlas[name].uvs };
681+
const i = corner.findIndex((f) => {
682+
return f.width === sw && f.height === sh;
683+
});
684+
if (i === -1) {
685+
corner.push(entry);
686+
} else {
687+
corner[i] = entry;
688+
}
689+
// a new frame can change whether its page computes every UV
690+
this._sizeChanged();
570691

571692
return atlas[name].uvs;
572693
}

‎packages/melonjs/src/video/texture/cache.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,19 @@ class TextureCache {
289289
return this.cache.has(image);
290290
}
291291

292+
/**
293+
* @ignore
294+
* @internal
295+
* the image's pixels are being replaced, maybe at another size: every
296+
* atlas drawn from it reads its size again on its next draw (see
297+
* `TextureAtlas#_decideUVs`)
298+
*/
299+
sizeChanged(image) {
300+
for (const atlas of this.cache.get(image)) {
301+
atlas._sizeChanged?.();
302+
}
303+
}
304+
292305
/**
293306
* @ignore
294307
* @internal

0 commit comments

Comments
 (0)