littlejsengine 1.18.28 → 1.19.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,458 +1,458 @@
1
- /**
2
- * LittleJS Texture Sheet Plugin
3
- * - Packs images into texture sheets as they are loaded
4
- * - Sprites are placed automatically, callers get a TileInfo
5
- * - Sheets are created and filled as needed
6
- * - Sheets fill in call order, images decode in parallel
7
- * - Animation frames keep layout and wrap across rows as needed
8
- * - WebGL textures upload once per batch of loads
9
- * - loadAtlas imports pre-packed atlases (TexturePacker and Aseprite json)
10
- * @namespace TextureSheets
11
- */
12
-
13
- 'use strict';
14
-
15
- /** Width and height in pixels of texture sheets created by loadSprite
16
- * @type {number}
17
- * @default
18
- * @memberof Settings */
19
- let textureSheetSize = 2048;
20
-
21
- /** Default padding pixels around each frame packed by loadSprite
22
- * @type {number}
23
- * @default
24
- * @memberof Settings */
25
- let textureSheetPadding = 1;
26
-
27
- /** Array of texture sheets created by loadSprite
28
- * @type {Array<TextureSheet>}
29
- * @memberof TextureSheets */
30
- let textureSheets = [];
31
-
32
- // pending loads pack through a queue so sheets fill in call order
33
- let textureSheetQueue = Promise.resolve();
34
- let textureSheetPendingCount = 0;
35
-
36
- /**
37
- * Texture Sheet - A texture that images are packed into as they load
38
- * Uses shelf packing, images are placed left to right then wrap to a new row
39
- * @memberof TextureSheets
40
- */
41
- class TextureSheet
42
- {
43
- /** Create a texture sheet, called automatically by loadSprite
44
- * @param {number} [size] - Width and height of the sheet in pixels */
45
- constructor(size=textureSheetSize)
46
- {
47
- ASSERT(size > 0, 'texture sheet size must be positive');
48
-
49
- /** @property {number} - Width and height of the sheet in pixels */
50
- this.size = size;
51
- /** @property {OffscreenCanvas} - Canvas holding the packed images */
52
- this.canvas = headlessMode ? undefined : new OffscreenCanvas(size, size);
53
- /** @property {OffscreenCanvasRenderingContext2D} - 2d context for the canvas */
54
- this.context = this.canvas?.getContext('2d');
55
- /** @property {TextureInfo} - The texture info for this sheet */
56
- this.textureInfo = new TextureInfo(this.canvas);
57
- /** @property {Vector2} - Where the next image will be packed */
58
- this.cursor = vec2();
59
- /** @property {number} - Height of the row being packed */
60
- this.rowHeight = 0;
61
- /** @property {boolean} - Has the canvas changed since the last webgl upload? */
62
- this.glDirty = false;
63
-
64
- if (headlessMode)
65
- {
66
- // tiles still need bounds when there is no canvas to measure
67
- this.textureInfo.size = vec2(size);
68
- this.textureInfo.sizeInverse = vec2(1/size);
69
- }
70
- }
71
-
72
- /** Find a spot for an image on this sheet without drawing it
73
- * @param {Vector2} imageSize - Size of the source image in pixels
74
- * @param {Vector2} [frameSize] - Size of each frame, or the whole image if not passed
75
- * @param {number} [padding] - How many pixels padding around each frame
76
- * @param {number|Vector2} [sourcePadding] - How many pixels padding around each frame in the source image
77
- * @return {TileInfo} Tile for the packed image, or undefined if the sheet is full */
78
- tryAdd(imageSize, frameSize=imageSize, padding=textureSheetPadding, sourcePadding=0)
79
- {
80
- ASSERT(isVector2(imageSize) && isVector2(frameSize), 'sizes must be vec2');
81
- ASSERT(frameSize.x > 0 && frameSize.y > 0, 'frame size must be positive');
82
-
83
- if (isNumber(sourcePadding))
84
- sourcePadding = vec2(sourcePadding);
85
- ASSERT(isVector2(sourcePadding) && sourcePadding.x >= 0 && sourcePadding.y >= 0,
86
- 'sourcePadding must be a number or vec2 >= 0');
87
-
88
- // the source may have its own padding baked in around each frame
89
- const sourceCellWidth = frameSize.x + sourcePadding.x*2;
90
- const sourceCellHeight = frameSize.y + sourcePadding.y*2;
91
- ASSERT(imageSize.x % sourceCellWidth === 0 && imageSize.y % sourceCellHeight === 0,
92
- 'image size must be a multiple of the padded frame size');
93
-
94
- const cellWidth = frameSize.x + padding*2;
95
- const cellHeight = frameSize.y + padding*2;
96
- const maxColumns = this.size / cellWidth | 0;
97
- ASSERT(maxColumns > 0, 'frame is too wide to fit on a texture sheet');
98
-
99
- // keep the layout of the source image, but narrow it if a row is too wide
100
- // frames wrap down to the next row, which TileInfo.frame handles via columns
101
- const sourceColumns = imageSize.x / sourceCellWidth;
102
- const frameCount = sourceColumns * (imageSize.y / sourceCellHeight);
103
- const columns = min(sourceColumns, maxColumns);
104
- const blockWidth = columns * cellWidth;
105
- const blockHeight = ceil(frameCount / columns) * cellHeight;
106
-
107
- // probe the placement using locals so a failed try leaves the sheet unchanged
108
- let x = this.cursor.x, y = this.cursor.y, rowHeight = this.rowHeight;
109
- if (x + blockWidth > this.size)
110
- {
111
- // start a new row if this one does not have enough space left
112
- x = 0;
113
- y += rowHeight;
114
- rowHeight = 0;
115
- }
116
-
117
- // out of space, the caller needs to use a different sheet
118
- if (y + blockHeight > this.size)
119
- return undefined;
120
-
121
- // commit the placement, tile pos points inside the padding to match how tile() works
122
- this.cursor.x = x + blockWidth;
123
- this.cursor.y = y;
124
- this.rowHeight = max(rowHeight, blockHeight);
125
- return new TileInfo(vec2(x + padding, y + padding), frameSize, this.textureInfo, padding, 0, columns);
126
- }
127
-
128
- /** Draw an image into this sheet at a tile returned by tryAdd
129
- * @param {HTMLImageElement} image - Source image to copy from
130
- * @param {TileInfo} tileInfo - Where to put it, from tryAdd
131
- * @param {boolean} [update] - Upload to webgl now, pass false when batching
132
- * @param {number|Vector2} [sourcePadding] - How many pixels padding around each frame in the source image */
133
- drawImage(image, tileInfo, update=true, sourcePadding=0)
134
- {
135
- ASSERT(!!this.context, 'texture sheet has no canvas');
136
-
137
- if (isNumber(sourcePadding))
138
- sourcePadding = vec2(sourcePadding);
139
-
140
- // copy frames in order, reading the source left to right, top to bottom
141
- // the destination wraps at tileInfo.columns which may be narrower than the source
142
- const frameSize = tileInfo.size;
143
- const sourceCellWidth = frameSize.x + sourcePadding.x*2;
144
- const sourceCellHeight = frameSize.y + sourcePadding.y*2;
145
- const sourceColumns = image.width / sourceCellWidth;
146
- const frameCount = sourceColumns * (image.height / sourceCellHeight);
147
- const columns = tileInfo.columns || frameCount;
148
- const cellWidth = frameSize.x + tileInfo.padding*2;
149
- const cellHeight = frameSize.y + tileInfo.padding*2;
150
- for (let i = frameCount; i--;)
151
- {
152
- const sourceX = (i % sourceColumns) * sourceCellWidth + sourcePadding.x;
153
- const sourceY = (i / sourceColumns | 0) * sourceCellHeight + sourcePadding.y;
154
- this.context.drawImage(image,
155
- sourceX, sourceY, frameSize.x, frameSize.y,
156
- tileInfo.pos.x + (i % columns) * cellWidth,
157
- tileInfo.pos.y + (i / columns | 0) * cellHeight,
158
- frameSize.x, frameSize.y);
159
- }
160
-
161
- // upload now unless the caller is batching more images
162
- this.glDirty = true;
163
- update && this.updateTexture();
164
- }
165
-
166
- /** Upload the canvas to webgl if it has changed since the last upload
167
- * Only needed after batching, drawImage uploads automatically by default */
168
- updateTexture()
169
- {
170
- if (!this.glDirty) return;
171
- this.glDirty = false;
172
- this.textureInfo.createWebGLTexture();
173
- }
174
- }
175
-
176
- ///////////////////////////////////////////////////////////////////////////////
177
-
178
- /** Load an image and pack it into a texture sheet
179
- * - Returns a TileInfo immediately which is filled in when the image loads
180
- * - Nothing is visible until it loads, use spritesReady to wait for it
181
- * - Pass frameSize for animations, then step through them with TileInfo.frame
182
- * - Grid images keep their layout and frames wrap down to the next row
183
- * - Pass sourcePadding if the source image has padding baked in around frames
184
- * @param {string} src - Image source path
185
- * @param {Vector2|number} [frameSize] - Size of each animation frame in pixels
186
- * @param {number} [padding] - How many pixels padding around each frame
187
- * @param {number|Vector2} [sourcePadding] - How many pixels padding around each frame in the source image
188
- * @return {TileInfo}
189
- * @example
190
- * const playerTile = loadSprite('player.png'); // a single sprite
191
- * const runTile = loadSprite('run.png', vec2(16)); // a 16x16 frame animation
192
- * @memberof TextureSheets */
193
- function loadSprite(src, frameSize, padding=textureSheetPadding, sourcePadding=0)
194
- {
195
- ASSERT(isStringLike(src), 'image src must be a string');
196
- ASSERT(!frameSize || isVector2(frameSize) || isNumber(frameSize), 'frameSize must be a vec2 or number');
197
- ASSERT(isNumber(padding), 'padding must be a number');
198
- ASSERT(isNumber(sourcePadding) || isVector2(sourcePadding), 'sourcePadding must be a number or vec2');
199
-
200
- if (isNumber(frameSize))
201
- frameSize = vec2(frameSize);
202
-
203
- // start with an empty tile that gets filled in when the image loads
204
- const tileInfo = new TileInfo(vec2(), vec2(), undefined, padding, 0);
205
- if (headlessMode) return tileInfo;
206
-
207
- // point at a sheet right away so drawing before it loads picks up empty pixels
208
- tileInfo.textureInfo = (textureSheets[0] || textureSheetCreate()).textureInfo;
209
-
210
- // start decoding right away, images decode in parallel
211
- const image = new Image;
212
- const imagePromise = new Promise(resolve =>
213
- {
214
- image.onerror = image.onload = resolve;
215
- image.crossOrigin = 'anonymous';
216
- image.src = src;
217
- });
218
-
219
- // pack through a queue so sheets fill in call order, not decode order
220
- ++textureSheetPendingCount;
221
- textureSheetQueue = textureSheetQueue.then(async ()=>
222
- {
223
- await imagePromise;
224
- if (image.width)
225
- {
226
- // pack onto a sheet, then fill in the tile that was already handed out,
227
- // copying every field so nothing is missed if TileInfo gains more of them
228
- const imageSize = vec2(image.width, image.height);
229
- const {sheet, tile} = textureSheetAdd(imageSize, frameSize, padding, sourcePadding);
230
- Object.assign(tileInfo, tile);
231
- sheet.drawImage(image, tileInfo, false, sourcePadding); // upload once per batch below
232
- }
233
- else
234
- {
235
- // leave the tile empty if the image failed to load
236
- LOG('loadSprite failed to load image:', src);
237
- }
238
-
239
- // upload to webgl once per batch, when the last pending load finishes
240
- if (!--textureSheetPendingCount)
241
- textureSheets.forEach(s=> s.updateTexture());
242
- });
243
-
244
- return tileInfo;
245
- }
246
-
247
- /** Load a pre-packed texture atlas and repack it onto texture sheets
248
- * - Supports TexturePacker json (hash and array) and Aseprite json
249
- * - Returns an empty object which is filled with TileInfos when loaded
250
- * - Frames are named by the json, animations are grouped automatically
251
- * - Aseprite frame tags become animations, so do names like run_0, run_1
252
- * - Trimmed frames are restored to their full source size when packed
253
- * - Rotated frames are rotated back upright when packed
254
- * @param {string} imageSrc - Atlas image path
255
- * @param {string|Object} jsonSrc - Atlas json path, or already parsed json data
256
- * @param {number} [padding] - How many pixels padding around each frame
257
- * @return {Object} Object mapping frame and animation names to TileInfos
258
- * @example
259
- * const atlas = loadAtlas('sprites.png', 'sprites.json');
260
- * await spritesReady();
261
- * drawTile(pos, size, atlas.player); // a single frame
262
- * drawTile(pos, size, atlas.run.frame(2)); // frame 2 of the run animation
263
- * @memberof TextureSheets */
264
- function loadAtlas(imageSrc, jsonSrc, padding=textureSheetPadding)
265
- {
266
- ASSERT(isStringLike(imageSrc), 'atlas image src must be a string');
267
- ASSERT(isStringLike(jsonSrc) || typeof jsonSrc === 'object', 'atlas json must be a path or object');
268
- ASSERT(isNumber(padding), 'padding must be a number');
269
-
270
- const atlas = {};
271
- if (headlessMode) return atlas;
272
-
273
- // start fetching the json and decoding the image right away, in parallel
274
- const jsonPromise = typeof jsonSrc === 'object' ? Promise.resolve(jsonSrc) :
275
- fetch(jsonSrc).then(r=> r.ok && r.json()).catch(()=> undefined);
276
- const image = new Image;
277
- const imagePromise = new Promise(resolve =>
278
- {
279
- image.onerror = image.onload = resolve;
280
- image.crossOrigin = 'anonymous';
281
- image.src = imageSrc;
282
- });
283
-
284
- // pack through a queue so sheets fill in call order, not decode order
285
- ++textureSheetPendingCount;
286
- textureSheetQueue = textureSheetQueue.then(async ()=>
287
- {
288
- const data = await jsonPromise;
289
- await imagePromise;
290
- if (image.width && data)
291
- {
292
- for (const group of parseAtlas(data))
293
- {
294
- // reserve a block of full size cells, one per frame
295
- const sourceSize = group.frames[0].sourceSize;
296
- const blockSize = vec2(sourceSize.x*group.frames.length, sourceSize.y);
297
- const {sheet, tile} = textureSheetAdd(blockSize, sourceSize, padding);
298
-
299
- // draw each frame untrimmed into its cell
300
- const context = sheet.context;
301
- const cellWidth = sourceSize.x + padding*2;
302
- const cellHeight = sourceSize.y + padding*2;
303
- group.frames.forEach((f, i)=>
304
- {
305
- const x = tile.pos.x + (i % tile.columns)*cellWidth + f.offset.x;
306
- const y = tile.pos.y + (i / tile.columns |0)*cellHeight + f.offset.y;
307
- if (f.rotated)
308
- {
309
- // stored rotated 90 degrees clockwise, draw it back upright
310
- context.save();
311
- context.translate(x, y);
312
- context.rotate(-PI/2);
313
- context.drawImage(image, f.pos.x, f.pos.y, f.size.y, f.size.x,
314
- -f.size.y, 0, f.size.y, f.size.x);
315
- context.restore();
316
- }
317
- else
318
- context.drawImage(image, f.pos.x, f.pos.y, f.size.x, f.size.y,
319
- x, y, f.size.x, f.size.y);
320
- });
321
- sheet.glDirty = true;
322
- atlas[group.name] = tile;
323
- }
324
- }
325
- else
326
- {
327
- // leave the atlas empty if either file failed to load
328
- LOG('loadAtlas failed to load:', imageSrc, jsonSrc);
329
- }
330
-
331
- // upload to webgl once per batch, when the last pending load finishes
332
- if (!--textureSheetPendingCount)
333
- textureSheets.forEach(s=> s.updateTexture());
334
- });
335
-
336
- return atlas;
337
- }
338
-
339
- /** Parse atlas json into a list of named frame groups, used by loadAtlas
340
- * - Accepts TexturePacker json (hash and array) and Aseprite json
341
- * - Frames tagged in Aseprite or named like run_0, run_1 group into animations
342
- * @param {Object} data - Parsed atlas json data
343
- * @return {Array<Object>} List of {name, frames} groups in atlas order
344
- * @memberof TextureSheets */
345
- function parseAtlas(data)
346
- {
347
- ASSERT(!!data?.frames, 'unrecognized atlas format, expected TexturePacker or Aseprite json');
348
-
349
- // normalize both hash and array frame layouts into a single list
350
- const frames = (isArray(data.frames) ?
351
- data.frames.map(f=> [f.filename, f]) : Object.entries(data.frames))
352
- .map(([name, f])=> ({
353
- name: name.replace(/\.[^.\\/]+$/, ''), // strip file extension
354
- pos: vec2(f.frame.x, f.frame.y),
355
- size: vec2(f.frame.w, f.frame.h),
356
- offset: vec2(f.spriteSourceSize?.x ?? 0, f.spriteSourceSize?.y ?? 0),
357
- sourceSize: vec2(f.sourceSize?.w ?? f.frame.w, f.sourceSize?.h ?? f.frame.h),
358
- rotated: !!f.rotated,
359
- }));
360
-
361
- const groups = [];
362
- const tags = data.meta?.frameTags;
363
- if (tags?.length)
364
- {
365
- // aseprite tags are authoritative, untagged frames stay individual
366
- const tagged = new Set;
367
- for (const tag of tags)
368
- {
369
- groups.push({name: tag.name, frames: frames.slice(tag.from, tag.to + 1)});
370
- for (let i = tag.from; i <= tag.to; ++i)
371
- tagged.add(i);
372
- }
373
- frames.forEach((f, i)=> tagged.has(i) || groups.push({name: f.name, frames: [f]}));
374
- return groups;
375
- }
376
-
377
- // group frames that share a name stem with contiguous trailing numbers
378
- // run_0.png and run_1.png become a 2 frame animation named run
379
- const stems = new Map;
380
- for (const f of frames)
381
- {
382
- let match = f.name.match(/^(.+?)([-_ ])?(\d+)$/);
383
- if (match && !match[2] && /\d$/.test(match[1]))
384
- match = undefined; // all digit tails like 10 are a name, not frame 0 of 1
385
- const stem = match ? match[1] : f.name;
386
- f.groupIndex = match ? Number(match[3]) : undefined;
387
- stems.has(stem) || stems.set(stem, []);
388
- stems.get(stem).push(f);
389
- }
390
- for (const [stem, list] of stems)
391
- {
392
- // only group 2 or more frames with contiguous indices and matching sizes
393
- list.sort((a, b)=> a.groupIndex - b.groupIndex);
394
- const grouped = list.length > 1 &&
395
- list.every((f, i)=> f.groupIndex === list[0].groupIndex + i) &&
396
- list.every(f=> f.sourceSize.x === list[0].sourceSize.x &&
397
- f.sourceSize.y === list[0].sourceSize.y);
398
- if (grouped)
399
- groups.push({name: stem, frames: list});
400
- else
401
- list.forEach(f=> groups.push({name: f.name, frames: [f]}));
402
- }
403
- return groups;
404
- }
405
-
406
- /** Wait for everything started by loadSprite and loadAtlas to finish packing
407
- * @return {Promise}
408
- * @example
409
- * async function gameInit()
410
- * {
411
- * playerTile = loadSprite('player.png');
412
- * runTile = loadSprite('run.png', vec2(16));
413
- * await spritesReady();
414
- * }
415
- * @memberof TextureSheets */
416
- async function spritesReady()
417
- {
418
- // keep waiting until the queue drains, more sprites may load while waiting
419
- while (textureSheetPendingCount)
420
- await textureSheetQueue;
421
- }
422
-
423
- // create a new texture sheet and add it to the list
424
- function textureSheetCreate()
425
- {
426
- const sheet = new TextureSheet;
427
- textureSheets.push(sheet);
428
- return sheet;
429
- }
430
-
431
- // use the first sheet with enough space, or make a new one
432
- function textureSheetAdd(imageSize, frameSize, padding, sourcePadding)
433
- {
434
- let sheet, tile;
435
- for (sheet of textureSheets)
436
- if (tile = sheet.tryAdd(imageSize, frameSize, padding, sourcePadding))
437
- break;
438
- if (!tile)
439
- {
440
- sheet = textureSheetCreate();
441
- tile = sheet.tryAdd(imageSize, frameSize, padding, sourcePadding);
442
- ASSERT(!!tile, 'image is too large to fit on a texture sheet');
443
- }
444
- return {sheet, tile};
445
- }
446
-
447
- ///////////////////////////////////////////////////////////////////////////////
448
- // Texture sheet setting setters
449
-
450
- /** Set width and height in pixels of texture sheets created by loadSprite
451
- * @param {number} size
452
- * @memberof Settings */
453
- function setTextureSheetSize(size) { textureSheetSize = size; }
454
-
455
- /** Set default padding pixels around each frame packed by loadSprite
456
- * @param {number} padding
457
- * @memberof Settings */
458
- function setTextureSheetPadding(padding) { textureSheetPadding = padding; }
1
+ /**
2
+ * LittleJS Texture Sheet Plugin
3
+ * - Packs images into texture sheets as they are loaded
4
+ * - Sprites are placed automatically, callers get a TileInfo
5
+ * - Sheets are created and filled as needed
6
+ * - Sheets fill in call order, images decode in parallel
7
+ * - Animation frames keep layout and wrap across rows as needed
8
+ * - WebGL textures upload once per batch of loads
9
+ * - loadAtlas imports pre-packed atlases (TexturePacker and Aseprite json)
10
+ * @namespace TextureSheets
11
+ */
12
+
13
+ 'use strict';
14
+
15
+ /** Width and height in pixels of texture sheets created by loadSprite
16
+ * @type {number}
17
+ * @default
18
+ * @memberof Settings */
19
+ let textureSheetSize = 2048;
20
+
21
+ /** Default padding pixels around each frame packed by loadSprite
22
+ * @type {number}
23
+ * @default
24
+ * @memberof Settings */
25
+ let textureSheetPadding = 1;
26
+
27
+ /** Array of texture sheets created by loadSprite
28
+ * @type {Array<TextureSheet>}
29
+ * @memberof TextureSheets */
30
+ let textureSheets = [];
31
+
32
+ // pending loads pack through a queue so sheets fill in call order
33
+ let textureSheetQueue = Promise.resolve();
34
+ let textureSheetPendingCount = 0;
35
+
36
+ /**
37
+ * Texture Sheet - A texture that images are packed into as they load
38
+ * Uses shelf packing, images are placed left to right then wrap to a new row
39
+ * @memberof TextureSheets
40
+ */
41
+ class TextureSheet
42
+ {
43
+ /** Create a texture sheet, called automatically by loadSprite
44
+ * @param {number} [size] - Width and height of the sheet in pixels */
45
+ constructor(size=textureSheetSize)
46
+ {
47
+ ASSERT(size > 0, 'texture sheet size must be positive');
48
+
49
+ /** @property {number} - Width and height of the sheet in pixels */
50
+ this.size = size;
51
+ /** @property {OffscreenCanvasRenderingContext2D} - 2d context for the canvas */
52
+ this.context = headlessMode ? undefined : createCanvasContext(size);
53
+ /** @property {OffscreenCanvas} - Canvas holding the packed images */
54
+ this.canvas = this.context?.canvas;
55
+ /** @property {TextureInfo} - The texture info for this sheet */
56
+ this.textureInfo = new TextureInfo(this.canvas);
57
+ /** @property {Vector2} - Where the next image will be packed */
58
+ this.cursor = vec2();
59
+ /** @property {number} - Height of the row being packed */
60
+ this.rowHeight = 0;
61
+ /** @property {boolean} - Has the canvas changed since the last webgl upload? */
62
+ this.glDirty = false;
63
+
64
+ if (headlessMode)
65
+ {
66
+ // tiles still need bounds when there is no canvas to measure
67
+ this.textureInfo.size = vec2(size);
68
+ this.textureInfo.sizeInverse = vec2(1/size);
69
+ }
70
+ }
71
+
72
+ /** Find a spot for an image on this sheet without drawing it
73
+ * @param {Vector2} imageSize - Size of the source image in pixels
74
+ * @param {Vector2} [frameSize] - Size of each frame, or the whole image if not passed
75
+ * @param {number} [padding] - How many pixels padding around each frame
76
+ * @param {number|Vector2} [sourcePadding] - How many pixels padding around each frame in the source image
77
+ * @return {TileInfo} Tile for the packed image, or undefined if the sheet is full */
78
+ tryAdd(imageSize, frameSize=imageSize, padding=textureSheetPadding, sourcePadding=0)
79
+ {
80
+ ASSERT(isVector2(imageSize) && isVector2(frameSize), 'sizes must be vec2');
81
+ ASSERT(frameSize.x > 0 && frameSize.y > 0, 'frame size must be positive');
82
+
83
+ if (isNumber(sourcePadding))
84
+ sourcePadding = vec2(sourcePadding);
85
+ ASSERT(isVector2(sourcePadding) && sourcePadding.x >= 0 && sourcePadding.y >= 0,
86
+ 'sourcePadding must be a number or vec2 >= 0');
87
+
88
+ // the source may have its own padding baked in around each frame
89
+ const sourceCellWidth = frameSize.x + sourcePadding.x*2;
90
+ const sourceCellHeight = frameSize.y + sourcePadding.y*2;
91
+ ASSERT(imageSize.x % sourceCellWidth === 0 && imageSize.y % sourceCellHeight === 0,
92
+ 'image size must be a multiple of the padded frame size');
93
+
94
+ const cellWidth = frameSize.x + padding*2;
95
+ const cellHeight = frameSize.y + padding*2;
96
+ const maxColumns = this.size / cellWidth | 0;
97
+ ASSERT(maxColumns > 0, 'frame is too wide to fit on a texture sheet');
98
+
99
+ // keep the layout of the source image, but narrow it if a row is too wide
100
+ // frames wrap down to the next row, which TileInfo.frame handles via columns
101
+ const sourceColumns = imageSize.x / sourceCellWidth;
102
+ const frameCount = sourceColumns * (imageSize.y / sourceCellHeight);
103
+ const columns = min(sourceColumns, maxColumns);
104
+ const blockWidth = columns * cellWidth;
105
+ const blockHeight = ceil(frameCount / columns) * cellHeight;
106
+
107
+ // probe the placement using locals so a failed try leaves the sheet unchanged
108
+ let x = this.cursor.x, y = this.cursor.y, rowHeight = this.rowHeight;
109
+ if (x + blockWidth > this.size)
110
+ {
111
+ // start a new row if this one does not have enough space left
112
+ x = 0;
113
+ y += rowHeight;
114
+ rowHeight = 0;
115
+ }
116
+
117
+ // out of space, the caller needs to use a different sheet
118
+ if (y + blockHeight > this.size)
119
+ return undefined;
120
+
121
+ // commit the placement, tile pos points inside the padding to match how tile() works
122
+ this.cursor.x = x + blockWidth;
123
+ this.cursor.y = y;
124
+ this.rowHeight = max(rowHeight, blockHeight);
125
+ return new TileInfo(vec2(x + padding, y + padding), frameSize, this.textureInfo, padding, 0, columns);
126
+ }
127
+
128
+ /** Draw an image into this sheet at a tile returned by tryAdd
129
+ * @param {HTMLImageElement} image - Source image to copy from
130
+ * @param {TileInfo} tileInfo - Where to put it, from tryAdd
131
+ * @param {boolean} [update] - Upload to webgl now, pass false when batching
132
+ * @param {number|Vector2} [sourcePadding] - How many pixels padding around each frame in the source image */
133
+ drawImage(image, tileInfo, update=true, sourcePadding=0)
134
+ {
135
+ ASSERT(!!this.context, 'texture sheet has no canvas');
136
+
137
+ if (isNumber(sourcePadding))
138
+ sourcePadding = vec2(sourcePadding);
139
+
140
+ // copy frames in order, reading the source left to right, top to bottom
141
+ // the destination wraps at tileInfo.columns which may be narrower than the source
142
+ const frameSize = tileInfo.size;
143
+ const sourceCellWidth = frameSize.x + sourcePadding.x*2;
144
+ const sourceCellHeight = frameSize.y + sourcePadding.y*2;
145
+ const sourceColumns = image.width / sourceCellWidth;
146
+ const frameCount = sourceColumns * (image.height / sourceCellHeight);
147
+ const columns = tileInfo.columns || frameCount;
148
+ const cellWidth = frameSize.x + tileInfo.padding*2;
149
+ const cellHeight = frameSize.y + tileInfo.padding*2;
150
+ for (let i = frameCount; i--;)
151
+ {
152
+ const sourceX = (i % sourceColumns) * sourceCellWidth + sourcePadding.x;
153
+ const sourceY = (i / sourceColumns | 0) * sourceCellHeight + sourcePadding.y;
154
+ this.context.drawImage(image,
155
+ sourceX, sourceY, frameSize.x, frameSize.y,
156
+ tileInfo.pos.x + (i % columns) * cellWidth,
157
+ tileInfo.pos.y + (i / columns | 0) * cellHeight,
158
+ frameSize.x, frameSize.y);
159
+ }
160
+
161
+ // upload now unless the caller is batching more images
162
+ this.glDirty = true;
163
+ update && this.updateTexture();
164
+ }
165
+
166
+ /** Upload the canvas to webgl if it has changed since the last upload
167
+ * Only needed after batching, drawImage uploads automatically by default */
168
+ updateTexture()
169
+ {
170
+ if (!this.glDirty) return;
171
+ this.glDirty = false;
172
+ this.textureInfo.createWebGLTexture();
173
+ }
174
+ }
175
+
176
+ ///////////////////////////////////////////////////////////////////////////////
177
+
178
+ /** Load an image and pack it into a texture sheet
179
+ * - Returns a TileInfo immediately which is filled in when the image loads
180
+ * - Nothing is visible until it loads, use spritesReady to wait for it
181
+ * - Pass frameSize for animations, then step through them with TileInfo.frame
182
+ * - Grid images keep their layout and frames wrap down to the next row
183
+ * - Pass sourcePadding if the source image has padding baked in around frames
184
+ * @param {string} src - Image source path
185
+ * @param {Vector2|number} [frameSize] - Size of each animation frame in pixels
186
+ * @param {number} [padding] - How many pixels padding around each frame
187
+ * @param {number|Vector2} [sourcePadding] - How many pixels padding around each frame in the source image
188
+ * @return {TileInfo}
189
+ * @example
190
+ * const playerTile = loadSprite('player.png'); // a single sprite
191
+ * const runTile = loadSprite('run.png', vec2(16)); // a 16x16 frame animation
192
+ * @memberof TextureSheets */
193
+ function loadSprite(src, frameSize, padding=textureSheetPadding, sourcePadding=0)
194
+ {
195
+ ASSERT(isStringLike(src), 'image src must be a string');
196
+ ASSERT(!frameSize || isVector2(frameSize) || isNumber(frameSize), 'frameSize must be a vec2 or number');
197
+ ASSERT(isNumber(padding), 'padding must be a number');
198
+ ASSERT(isNumber(sourcePadding) || isVector2(sourcePadding), 'sourcePadding must be a number or vec2');
199
+
200
+ if (isNumber(frameSize))
201
+ frameSize = vec2(frameSize);
202
+
203
+ // start with an empty tile that gets filled in when the image loads
204
+ const tileInfo = new TileInfo(vec2(), vec2(), undefined, padding, 0);
205
+ if (headlessMode) return tileInfo;
206
+
207
+ // point at a sheet right away so drawing before it loads picks up empty pixels
208
+ tileInfo.textureInfo = (textureSheets[0] || textureSheetCreate()).textureInfo;
209
+
210
+ // start decoding right away, images decode in parallel
211
+ const image = new Image;
212
+ const imagePromise = new Promise(resolve =>
213
+ {
214
+ image.onerror = image.onload = resolve;
215
+ image.crossOrigin = 'anonymous';
216
+ image.src = src;
217
+ });
218
+
219
+ // pack through a queue so sheets fill in call order, not decode order
220
+ ++textureSheetPendingCount;
221
+ textureSheetQueue = textureSheetQueue.then(async ()=>
222
+ {
223
+ await imagePromise;
224
+ if (image.width)
225
+ {
226
+ // pack onto a sheet, then fill in the tile that was already handed out,
227
+ // copying every field so nothing is missed if TileInfo gains more of them
228
+ const imageSize = vec2(image.width, image.height);
229
+ const {sheet, tile} = textureSheetAdd(imageSize, frameSize, padding, sourcePadding);
230
+ Object.assign(tileInfo, tile);
231
+ sheet.drawImage(image, tileInfo, false, sourcePadding); // upload once per batch below
232
+ }
233
+ else
234
+ {
235
+ // leave the tile empty if the image failed to load
236
+ LOG('loadSprite failed to load image:', src);
237
+ }
238
+
239
+ // upload to webgl once per batch, when the last pending load finishes
240
+ if (!--textureSheetPendingCount)
241
+ textureSheets.forEach(s=> s.updateTexture());
242
+ });
243
+
244
+ return tileInfo;
245
+ }
246
+
247
+ /** Load a pre-packed texture atlas and repack it onto texture sheets
248
+ * - Supports TexturePacker json (hash and array) and Aseprite json
249
+ * - Returns an empty object which is filled with TileInfos when loaded
250
+ * - Frames are named by the json, animations are grouped automatically
251
+ * - Aseprite frame tags become animations, so do names like run_0, run_1
252
+ * - Trimmed frames are restored to their full source size when packed
253
+ * - Rotated frames are rotated back upright when packed
254
+ * @param {string} imageSrc - Atlas image path
255
+ * @param {string|Object} jsonSrc - Atlas json path, or already parsed json data
256
+ * @param {number} [padding] - How many pixels padding around each frame
257
+ * @return {Object} Object mapping frame and animation names to TileInfos
258
+ * @example
259
+ * const atlas = loadAtlas('sprites.png', 'sprites.json');
260
+ * await spritesReady();
261
+ * drawTile(pos, size, atlas.player); // a single frame
262
+ * drawTile(pos, size, atlas.run.frame(2)); // frame 2 of the run animation
263
+ * @memberof TextureSheets */
264
+ function loadAtlas(imageSrc, jsonSrc, padding=textureSheetPadding)
265
+ {
266
+ ASSERT(isStringLike(imageSrc), 'atlas image src must be a string');
267
+ ASSERT(isStringLike(jsonSrc) || typeof jsonSrc === 'object', 'atlas json must be a path or object');
268
+ ASSERT(isNumber(padding), 'padding must be a number');
269
+
270
+ const atlas = {};
271
+ if (headlessMode) return atlas;
272
+
273
+ // start fetching the json and decoding the image right away, in parallel
274
+ const jsonPromise = typeof jsonSrc === 'object' ? Promise.resolve(jsonSrc) :
275
+ fetch(jsonSrc).then(r=> r.ok && r.json()).catch(()=> undefined);
276
+ const image = new Image;
277
+ const imagePromise = new Promise(resolve =>
278
+ {
279
+ image.onerror = image.onload = resolve;
280
+ image.crossOrigin = 'anonymous';
281
+ image.src = imageSrc;
282
+ });
283
+
284
+ // pack through a queue so sheets fill in call order, not decode order
285
+ ++textureSheetPendingCount;
286
+ textureSheetQueue = textureSheetQueue.then(async ()=>
287
+ {
288
+ const data = await jsonPromise;
289
+ await imagePromise;
290
+ if (image.width && data)
291
+ {
292
+ for (const group of parseAtlas(data))
293
+ {
294
+ // reserve a block of full size cells, one per frame
295
+ const sourceSize = group.frames[0].sourceSize;
296
+ const blockSize = vec2(sourceSize.x*group.frames.length, sourceSize.y);
297
+ const {sheet, tile} = textureSheetAdd(blockSize, sourceSize, padding);
298
+
299
+ // draw each frame untrimmed into its cell
300
+ const context = sheet.context;
301
+ const cellWidth = sourceSize.x + padding*2;
302
+ const cellHeight = sourceSize.y + padding*2;
303
+ group.frames.forEach((f, i)=>
304
+ {
305
+ const x = tile.pos.x + (i % tile.columns)*cellWidth + f.offset.x;
306
+ const y = tile.pos.y + (i / tile.columns |0)*cellHeight + f.offset.y;
307
+ if (f.rotated)
308
+ {
309
+ // stored rotated 90 degrees clockwise, draw it back upright
310
+ context.save();
311
+ context.translate(x, y);
312
+ context.rotate(-PI/2);
313
+ context.drawImage(image, f.pos.x, f.pos.y, f.size.y, f.size.x,
314
+ -f.size.y, 0, f.size.y, f.size.x);
315
+ context.restore();
316
+ }
317
+ else
318
+ context.drawImage(image, f.pos.x, f.pos.y, f.size.x, f.size.y,
319
+ x, y, f.size.x, f.size.y);
320
+ });
321
+ sheet.glDirty = true;
322
+ atlas[group.name] = tile;
323
+ }
324
+ }
325
+ else
326
+ {
327
+ // leave the atlas empty if either file failed to load
328
+ LOG('loadAtlas failed to load:', imageSrc, jsonSrc);
329
+ }
330
+
331
+ // upload to webgl once per batch, when the last pending load finishes
332
+ if (!--textureSheetPendingCount)
333
+ textureSheets.forEach(s=> s.updateTexture());
334
+ });
335
+
336
+ return atlas;
337
+ }
338
+
339
+ /** Parse atlas json into a list of named frame groups, used by loadAtlas
340
+ * - Accepts TexturePacker json (hash and array) and Aseprite json
341
+ * - Frames tagged in Aseprite or named like run_0, run_1 group into animations
342
+ * @param {Object} data - Parsed atlas json data
343
+ * @return {Array<Object>} List of {name, frames} groups in atlas order
344
+ * @memberof TextureSheets */
345
+ function parseAtlas(data)
346
+ {
347
+ ASSERT(!!data?.frames, 'unrecognized atlas format, expected TexturePacker or Aseprite json');
348
+
349
+ // normalize both hash and array frame layouts into a single list
350
+ const frames = (isArray(data.frames) ?
351
+ data.frames.map(f=> [f.filename, f]) : Object.entries(data.frames))
352
+ .map(([name, f])=> ({
353
+ name: name.replace(/\.[^.\\/]+$/, ''), // strip file extension
354
+ pos: vec2(f.frame.x, f.frame.y),
355
+ size: vec2(f.frame.w, f.frame.h),
356
+ offset: vec2(f.spriteSourceSize?.x ?? 0, f.spriteSourceSize?.y ?? 0),
357
+ sourceSize: vec2(f.sourceSize?.w ?? f.frame.w, f.sourceSize?.h ?? f.frame.h),
358
+ rotated: !!f.rotated,
359
+ }));
360
+
361
+ const groups = [];
362
+ const tags = data.meta?.frameTags;
363
+ if (tags?.length)
364
+ {
365
+ // aseprite tags are authoritative, untagged frames stay individual
366
+ const tagged = new Set;
367
+ for (const tag of tags)
368
+ {
369
+ groups.push({name: tag.name, frames: frames.slice(tag.from, tag.to + 1)});
370
+ for (let i = tag.from; i <= tag.to; ++i)
371
+ tagged.add(i);
372
+ }
373
+ frames.forEach((f, i)=> tagged.has(i) || groups.push({name: f.name, frames: [f]}));
374
+ return groups;
375
+ }
376
+
377
+ // group frames that share a name stem with contiguous trailing numbers
378
+ // run_0.png and run_1.png become a 2 frame animation named run
379
+ const stems = new Map;
380
+ for (const f of frames)
381
+ {
382
+ let match = f.name.match(/^(.+?)([-_ ])?(\d+)$/);
383
+ if (match && !match[2] && /\d$/.test(match[1]))
384
+ match = undefined; // all digit tails like 10 are a name, not frame 0 of 1
385
+ const stem = match ? match[1] : f.name;
386
+ f.groupIndex = match ? Number(match[3]) : undefined;
387
+ stems.has(stem) || stems.set(stem, []);
388
+ stems.get(stem).push(f);
389
+ }
390
+ for (const [stem, list] of stems)
391
+ {
392
+ // only group 2 or more frames with contiguous indices and matching sizes
393
+ list.sort((a, b)=> a.groupIndex - b.groupIndex);
394
+ const grouped = list.length > 1 &&
395
+ list.every((f, i)=> f.groupIndex === list[0].groupIndex + i) &&
396
+ list.every(f=> f.sourceSize.x === list[0].sourceSize.x &&
397
+ f.sourceSize.y === list[0].sourceSize.y);
398
+ if (grouped)
399
+ groups.push({name: stem, frames: list});
400
+ else
401
+ list.forEach(f=> groups.push({name: f.name, frames: [f]}));
402
+ }
403
+ return groups;
404
+ }
405
+
406
+ /** Wait for everything started by loadSprite and loadAtlas to finish packing
407
+ * @return {Promise}
408
+ * @example
409
+ * async function gameInit()
410
+ * {
411
+ * playerTile = loadSprite('player.png');
412
+ * runTile = loadSprite('run.png', vec2(16));
413
+ * await spritesReady();
414
+ * }
415
+ * @memberof TextureSheets */
416
+ async function spritesReady()
417
+ {
418
+ // keep waiting until the queue drains, more sprites may load while waiting
419
+ while (textureSheetPendingCount)
420
+ await textureSheetQueue;
421
+ }
422
+
423
+ // create a new texture sheet and add it to the list
424
+ function textureSheetCreate()
425
+ {
426
+ const sheet = new TextureSheet;
427
+ textureSheets.push(sheet);
428
+ return sheet;
429
+ }
430
+
431
+ // use the first sheet with enough space, or make a new one
432
+ function textureSheetAdd(imageSize, frameSize, padding, sourcePadding)
433
+ {
434
+ let sheet, tile;
435
+ for (sheet of textureSheets)
436
+ if (tile = sheet.tryAdd(imageSize, frameSize, padding, sourcePadding))
437
+ break;
438
+ if (!tile)
439
+ {
440
+ sheet = textureSheetCreate();
441
+ tile = sheet.tryAdd(imageSize, frameSize, padding, sourcePadding);
442
+ ASSERT(!!tile, 'image is too large to fit on a texture sheet');
443
+ }
444
+ return {sheet, tile};
445
+ }
446
+
447
+ ///////////////////////////////////////////////////////////////////////////////
448
+ // Texture sheet setting setters
449
+
450
+ /** Set width and height in pixels of texture sheets created by loadSprite
451
+ * @param {number} size
452
+ * @memberof Settings */
453
+ function setTextureSheetSize(size) { textureSheetSize = size; }
454
+
455
+ /** Set default padding pixels around each frame packed by loadSprite
456
+ * @param {number} padding
457
+ * @memberof Settings */
458
+ function setTextureSheetPadding(padding) { textureSheetPadding = padding; }