@moku-labs/game 0.15.123 → 0.15.125

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.
@@ -15181,6 +15181,155 @@ function createDemandApi(ctx, deps) {
15181
15181
  };
15182
15182
  }
15183
15183
  //#endregion
15184
+ //#region src/plugins/renderer/host/readback.ts
15185
+ /** Bytes of one pixel: the engine loads PNG and WebP only, so every source is 8-bit RGBA. */
15186
+ const BYTES_PER_PIXEL$2 = 4;
15187
+ /**
15188
+ * Estimates the GPU bytes of one texture source: 4 bytes per pixel, every mip level, a level never
15189
+ * smaller than one pixel.
15190
+ *
15191
+ * @param source - The size fields of a Pixi `TextureSource`.
15192
+ * @param source.pixelWidth - Width in real pixels.
15193
+ * @param source.pixelHeight - Height in real pixels.
15194
+ * @param source.mipLevelCount - Mip levels, 1 without mipmaps.
15195
+ * @returns The estimated bytes.
15196
+ * @example
15197
+ * ```ts
15198
+ * sourceBytes({ pixelWidth: 4, pixelHeight: 4, mipLevelCount: 3 }); // 84: 16 + 4 + 1 pixels
15199
+ * ```
15200
+ */
15201
+ function sourceBytes(source) {
15202
+ let pixels = 0;
15203
+ let width = source.pixelWidth;
15204
+ let height = source.pixelHeight;
15205
+ for (let level = 0; level < Math.max(1, source.mipLevelCount); level += 1) {
15206
+ pixels += width * height;
15207
+ width = Math.max(1, Math.floor(width / 2));
15208
+ height = Math.max(1, Math.floor(height / 2));
15209
+ }
15210
+ return pixels * BYTES_PER_PIXEL$2;
15211
+ }
15212
+ /**
15213
+ * Tells a render target from art: Pixi gives a target no upload method and no resource.
15214
+ *
15215
+ * @param source - The upload fields of a Pixi `TextureSource`.
15216
+ * @param source.uploadMethodId - How Pixi uploads it; `"unknown"` for a render target.
15217
+ * @param source.resource - What it uploads; none for a render target.
15218
+ * @returns True for a render target.
15219
+ * @example
15220
+ * ```ts
15221
+ * isTarget({ uploadMethodId: "unknown", resource: null }); // true
15222
+ * ```
15223
+ */
15224
+ function isTarget$3(source) {
15225
+ return source.uploadMethodId === "unknown" && (source.resource === null || source.resource === void 0);
15226
+ }
15227
+ /**
15228
+ * Counts the texture sources the GPU holds and sums their estimated bytes, split three ways: a
15229
+ * source with no upload method and no resource is a render target (a filter texture, a picture
15230
+ * Pixi renders into), one the engine keeps as a picture is kept, every other source is art.
15231
+ * Pixi's `managedTextures` exists on the WebGPU and the WebGL texture system alike (checked in
15232
+ * 8.22); Pixi's canvas renderer keeps no GPU texture and answers zero. Both systems answer
15233
+ * `Object.values` of a `GCManagedHash`, which keeps a `null` slot for every unloaded source, so
15234
+ * only the live sources are counted. An indexed walk: no array is made.
15235
+ *
15236
+ * @param app - The application that draws.
15237
+ * @param kept - The sources the engine keeps as pictures.
15238
+ * @returns The count, the bytes and their split.
15239
+ */
15240
+ function textureUsage(app, kept) {
15241
+ const system = app.renderer.texture;
15242
+ const usage = {
15243
+ count: 0,
15244
+ bytes: 0,
15245
+ art: 0,
15246
+ targets: 0,
15247
+ kept: 0
15248
+ };
15249
+ if (!("managedTextures" in system)) return usage;
15250
+ const sources = system.managedTextures;
15251
+ const total = sources.length;
15252
+ for (let index = 0; index < total; index += 1) {
15253
+ const source = sources[index];
15254
+ if (!source) continue;
15255
+ const bytes = sourceBytes(source);
15256
+ usage.count += 1;
15257
+ usage.bytes += bytes;
15258
+ if (kept.has(source)) usage.kept += bytes;
15259
+ else if (isTarget$3(source)) usage.targets += bytes;
15260
+ else usage.art += bytes;
15261
+ }
15262
+ return usage;
15263
+ }
15264
+ /**
15265
+ * Hides containers for the length of one synchronous call and shows them again right after it,
15266
+ * also when it throws. A container hidden already stays hidden.
15267
+ *
15268
+ * @param hidden - The containers to hide.
15269
+ * @param work - The call; it runs with them hidden.
15270
+ * @returns What the call returned.
15271
+ */
15272
+ function withHidden(hidden, work) {
15273
+ const shown = hidden.filter((container) => container.visible);
15274
+ for (const container of shown) container.visible = false;
15275
+ try {
15276
+ return work();
15277
+ } finally {
15278
+ for (const container of shown) container.visible = true;
15279
+ }
15280
+ }
15281
+ /**
15282
+ * Draws the stage into a PNG over the whole canvas, bars included, with Pixi's extract system.
15283
+ * Pixi renders the stage synchronously inside the call and encodes afterwards, so the containers
15284
+ * in `hidden` are hidden around the call alone: no drawn frame sees them hidden. A failed read is
15285
+ * logged and answers `undefined`, so a caller never has to catch.
15286
+ *
15287
+ * @param ctx - Domain context of the renderer plugin.
15288
+ * @param app - The application that draws.
15289
+ * @param hidden - The layer containers to leave out of the picture.
15290
+ * @returns A `data:image/png;base64,…` URL, or `undefined` when Pixi could not read the frame.
15291
+ */
15292
+ async function extractStage(ctx, app, hidden) {
15293
+ try {
15294
+ return await withHidden(hidden, () => app.renderer.extract.base64({
15295
+ target: app.stage,
15296
+ frame: app.screen,
15297
+ clearColor: ctx.config.background,
15298
+ format: "png"
15299
+ }));
15300
+ } catch (error) {
15301
+ ctx.log.error("renderer: capture failed", { error });
15302
+ return;
15303
+ }
15304
+ }
15305
+ /** The resolution the pixel oracle reads the stage at: a quarter of the pixels, a 2-px change still shows. */
15306
+ const ORACLE_RESOLUTION = .5;
15307
+ /**
15308
+ * Draws the stage live into RGBA pixels with Pixi's extract system, framed as a capture is, at
15309
+ * half resolution. A failed read is logged once per application state and answers `undefined`.
15310
+ *
15311
+ * @param ctx - Domain context of the renderer plugin.
15312
+ * @param app - The application that draws.
15313
+ * @param resolution - Device pixels per CSS pixel of the read; half by default.
15314
+ * @returns The pixels, or `undefined` when Pixi could not read them.
15315
+ */
15316
+ function readPixels(ctx, app, resolution = ORACLE_RESOLUTION) {
15317
+ try {
15318
+ return app.renderer.extract.pixels({
15319
+ target: app.stage,
15320
+ frame: app.screen,
15321
+ clearColor: ctx.config.background,
15322
+ resolution
15323
+ }).pixels;
15324
+ } catch (error) {
15325
+ if (!ctx.state.host.pixelsFailed) {
15326
+ ctx.state.host.pixelsFailed = true;
15327
+ ctx.log.error("renderer: pixel read failed", { error });
15328
+ }
15329
+ return;
15330
+ }
15331
+ }
15332
+ //#endregion
15184
15333
  //#region src/plugins/renderer/host/device.ts
15185
15334
  /**
15186
15335
  * The GPU device of the application that draws now. Only a WebGPU application has one; a lost
@@ -15207,8 +15356,9 @@ function liveGl(state) {
15207
15356
  return "gl" in app.renderer ? app.renderer.gl : void 0;
15208
15357
  }
15209
15358
  /**
15210
- * Starts a loss: the renderer stops drawing, the game pauses and the event goes out. A loss
15211
- * while the plugin is already down, or while a restore runs, is ignored.
15359
+ * Starts a loss: the renderer stops drawing, the game pauses and the event goes out; then the `decideLoss` callbacks
15360
+ * hear it, and one that answers true marks the page as leaving (F189). A loss while the plugin is already down, or
15361
+ * while a restore runs, is ignored.
15212
15362
  *
15213
15363
  * @param ctx - Domain context of the renderer plugin.
15214
15364
  * @param kind - Which backend lost its device.
@@ -15218,6 +15368,11 @@ function liveGl(state) {
15218
15368
  function beginLoss(ctx, kind, reason) {
15219
15369
  const state = ctx.state.host;
15220
15370
  if (!state.ready || state.restoring) return false;
15371
+ const info = {
15372
+ kind,
15373
+ reason,
15374
+ textureBytes: state.app === void 0 ? 0 : textureUsage(state.app, state.kept).bytes
15375
+ };
15221
15376
  state.ready = false;
15222
15377
  state.restoring = true;
15223
15378
  ctx.deps.lifecycle.push("device-lost");
@@ -15225,20 +15380,21 @@ function beginLoss(ctx, kind, reason) {
15225
15380
  kind,
15226
15381
  reason
15227
15382
  });
15383
+ for (const decide of state.lossDeciders) if (decide(info)) state.leaving = true;
15228
15384
  return true;
15229
15385
  }
15230
15386
  /**
15231
- * Ends a restore: the renderer draws again and the pause reason goes. The `onRestore` callbacks
15232
- * run first: after a WebGPU restore the whole display tree is new and they rebuild it; after a
15233
- * WebGL restore the tree stands, but the canvas and every render texture came back empty, so they
15234
- * ask for a whole frame and the pictures again.
15387
+ * Ends a restore: the renderer draws again and the pause reason goes. The `onRestore` callbacks run first: after a
15388
+ * WebGPU restore the whole display tree is new and they rebuild it; after a WebGL restore the tree stands, but the
15389
+ * canvas and every render texture came back empty, so they ask for a whole frame and the pictures again. A page that
15390
+ * leaves after the loss (F189) restores nothing: the call returns at once and the pause reason stays.
15235
15391
  *
15236
15392
  * @param ctx - Domain context of the renderer plugin.
15237
15393
  * @param rebuild - True when a new application replaced the old one.
15238
15394
  */
15239
15395
  function finishRestore(ctx, rebuild) {
15240
15396
  const state = ctx.state.host;
15241
- if (!state.restoring) return;
15397
+ if (!state.restoring || state.leaving) return;
15242
15398
  state.ready = true;
15243
15399
  state.restoring = false;
15244
15400
  for (const fn of state.onRestore) fn(rebuild);
@@ -15259,6 +15415,7 @@ function watchDevice(ctx, restart) {
15259
15415
  const onLost = async (info) => {
15260
15416
  if (ctx.state.host.app !== app) return;
15261
15417
  if (!beginLoss(ctx, "webgpu", info.reason)) return;
15418
+ if (ctx.state.host.leaving) return;
15262
15419
  if (await restart()) finishRestore(ctx, true);
15263
15420
  };
15264
15421
  app.renderer.gpu.device.lost.then(onLost).catch((error) => ctx.log.error("renderer: restore failed", { error }));
@@ -16775,6 +16932,8 @@ function createHostState() {
16775
16932
  restoring: false,
16776
16933
  onReady: [],
16777
16934
  onRestore: [],
16935
+ lossDeciders: [],
16936
+ leaving: false,
16778
16937
  onLoss: [],
16779
16938
  cleanups: [],
16780
16939
  unsupported: void 0,
@@ -17041,6 +17200,7 @@ function stopHost(state) {
17041
17200
  state.unsupported = void 0;
17042
17201
  state.onReady.length = 0;
17043
17202
  state.onRestore.length = 0;
17203
+ state.lossDeciders.length = 0;
17044
17204
  state.onLoss.length = 0;
17045
17205
  state.onResolutionChange.length = 0;
17046
17206
  state.onTrim.length = 0;
@@ -17063,7 +17223,7 @@ function stopHost(state) {
17063
17223
  * bounds (slot -1) boxes a reader's doubles the same way, for every caller: a slot that may not exist is checked first.
17064
17224
  */
17065
17225
  /** Bytes of one MiB. */
17066
- const BYTES_PER_MB$1 = 1048576;
17226
+ const BYTES_PER_MB$2 = 1048576;
17067
17227
  /**
17068
17228
  * Rounds a number to a fixed count of decimals, so a counter reads well in a panel and a log line stays short.
17069
17229
  *
@@ -17164,155 +17324,6 @@ function cellU8(column, index) {
17164
17324
  return column[index] ?? NaN;
17165
17325
  }
17166
17326
  //#endregion
17167
- //#region src/plugins/renderer/host/readback.ts
17168
- /** Bytes of one pixel: the engine loads PNG and WebP only, so every source is 8-bit RGBA. */
17169
- const BYTES_PER_PIXEL$2 = 4;
17170
- /**
17171
- * Estimates the GPU bytes of one texture source: 4 bytes per pixel, every mip level, a level never
17172
- * smaller than one pixel.
17173
- *
17174
- * @param source - The size fields of a Pixi `TextureSource`.
17175
- * @param source.pixelWidth - Width in real pixels.
17176
- * @param source.pixelHeight - Height in real pixels.
17177
- * @param source.mipLevelCount - Mip levels, 1 without mipmaps.
17178
- * @returns The estimated bytes.
17179
- * @example
17180
- * ```ts
17181
- * sourceBytes({ pixelWidth: 4, pixelHeight: 4, mipLevelCount: 3 }); // 84: 16 + 4 + 1 pixels
17182
- * ```
17183
- */
17184
- function sourceBytes(source) {
17185
- let pixels = 0;
17186
- let width = source.pixelWidth;
17187
- let height = source.pixelHeight;
17188
- for (let level = 0; level < Math.max(1, source.mipLevelCount); level += 1) {
17189
- pixels += width * height;
17190
- width = Math.max(1, Math.floor(width / 2));
17191
- height = Math.max(1, Math.floor(height / 2));
17192
- }
17193
- return pixels * BYTES_PER_PIXEL$2;
17194
- }
17195
- /**
17196
- * Tells a render target from art: Pixi gives a target no upload method and no resource.
17197
- *
17198
- * @param source - The upload fields of a Pixi `TextureSource`.
17199
- * @param source.uploadMethodId - How Pixi uploads it; `"unknown"` for a render target.
17200
- * @param source.resource - What it uploads; none for a render target.
17201
- * @returns True for a render target.
17202
- * @example
17203
- * ```ts
17204
- * isTarget({ uploadMethodId: "unknown", resource: null }); // true
17205
- * ```
17206
- */
17207
- function isTarget$3(source) {
17208
- return source.uploadMethodId === "unknown" && (source.resource === null || source.resource === void 0);
17209
- }
17210
- /**
17211
- * Counts the texture sources the GPU holds and sums their estimated bytes, split three ways: a
17212
- * source with no upload method and no resource is a render target (a filter texture, a picture
17213
- * Pixi renders into), one the engine keeps as a picture is kept, every other source is art.
17214
- * Pixi's `managedTextures` exists on the WebGPU and the WebGL texture system alike (checked in
17215
- * 8.22); Pixi's canvas renderer keeps no GPU texture and answers zero. Both systems answer
17216
- * `Object.values` of a `GCManagedHash`, which keeps a `null` slot for every unloaded source, so
17217
- * only the live sources are counted. An indexed walk: no array is made.
17218
- *
17219
- * @param app - The application that draws.
17220
- * @param kept - The sources the engine keeps as pictures.
17221
- * @returns The count, the bytes and their split.
17222
- */
17223
- function textureUsage(app, kept) {
17224
- const system = app.renderer.texture;
17225
- const usage = {
17226
- count: 0,
17227
- bytes: 0,
17228
- art: 0,
17229
- targets: 0,
17230
- kept: 0
17231
- };
17232
- if (!("managedTextures" in system)) return usage;
17233
- const sources = system.managedTextures;
17234
- const total = sources.length;
17235
- for (let index = 0; index < total; index += 1) {
17236
- const source = sources[index];
17237
- if (!source) continue;
17238
- const bytes = sourceBytes(source);
17239
- usage.count += 1;
17240
- usage.bytes += bytes;
17241
- if (kept.has(source)) usage.kept += bytes;
17242
- else if (isTarget$3(source)) usage.targets += bytes;
17243
- else usage.art += bytes;
17244
- }
17245
- return usage;
17246
- }
17247
- /**
17248
- * Hides containers for the length of one synchronous call and shows them again right after it,
17249
- * also when it throws. A container hidden already stays hidden.
17250
- *
17251
- * @param hidden - The containers to hide.
17252
- * @param work - The call; it runs with them hidden.
17253
- * @returns What the call returned.
17254
- */
17255
- function withHidden(hidden, work) {
17256
- const shown = hidden.filter((container) => container.visible);
17257
- for (const container of shown) container.visible = false;
17258
- try {
17259
- return work();
17260
- } finally {
17261
- for (const container of shown) container.visible = true;
17262
- }
17263
- }
17264
- /**
17265
- * Draws the stage into a PNG over the whole canvas, bars included, with Pixi's extract system.
17266
- * Pixi renders the stage synchronously inside the call and encodes afterwards, so the containers
17267
- * in `hidden` are hidden around the call alone: no drawn frame sees them hidden. A failed read is
17268
- * logged and answers `undefined`, so a caller never has to catch.
17269
- *
17270
- * @param ctx - Domain context of the renderer plugin.
17271
- * @param app - The application that draws.
17272
- * @param hidden - The layer containers to leave out of the picture.
17273
- * @returns A `data:image/png;base64,…` URL, or `undefined` when Pixi could not read the frame.
17274
- */
17275
- async function extractStage(ctx, app, hidden) {
17276
- try {
17277
- return await withHidden(hidden, () => app.renderer.extract.base64({
17278
- target: app.stage,
17279
- frame: app.screen,
17280
- clearColor: ctx.config.background,
17281
- format: "png"
17282
- }));
17283
- } catch (error) {
17284
- ctx.log.error("renderer: capture failed", { error });
17285
- return;
17286
- }
17287
- }
17288
- /** The resolution the pixel oracle reads the stage at: a quarter of the pixels, a 2-px change still shows. */
17289
- const ORACLE_RESOLUTION = .5;
17290
- /**
17291
- * Draws the stage live into RGBA pixels with Pixi's extract system, framed as a capture is, at
17292
- * half resolution. A failed read is logged once per application state and answers `undefined`.
17293
- *
17294
- * @param ctx - Domain context of the renderer plugin.
17295
- * @param app - The application that draws.
17296
- * @param resolution - Device pixels per CSS pixel of the read; half by default.
17297
- * @returns The pixels, or `undefined` when Pixi could not read them.
17298
- */
17299
- function readPixels(ctx, app, resolution = ORACLE_RESOLUTION) {
17300
- try {
17301
- return app.renderer.extract.pixels({
17302
- target: app.stage,
17303
- frame: app.screen,
17304
- clearColor: ctx.config.background,
17305
- resolution
17306
- }).pixels;
17307
- } catch (error) {
17308
- if (!ctx.state.host.pixelsFailed) {
17309
- ctx.state.host.pixelsFailed = true;
17310
- ctx.log.error("renderer: pixel read failed", { error });
17311
- }
17312
- return;
17313
- }
17314
- }
17315
- //#endregion
17316
17327
  //#region src/plugins/renderer/host/pool.ts
17317
17328
  /**
17318
17329
  * @file renderer/host — the pool trim (C14): gives back the idle render targets Pixi's global `TexturePool` keeps,
@@ -17415,7 +17426,7 @@ function trimPool(ctx, reason) {
17415
17426
  const before = targetBytes(app, state.kept);
17416
17427
  clearPool(pixi, state.pool.held);
17417
17428
  const after = targetBytes(app, state.kept);
17418
- const freedMb = roundTo((before - after) / BYTES_PER_MB$1, 2);
17429
+ const freedMb = roundTo((before - after) / BYTES_PER_MB$2, 2);
17419
17430
  state.pool.baseline = after;
17420
17431
  state.pool.restDone = true;
17421
17432
  state.pool.sceneAt = void 0;
@@ -17558,6 +17569,9 @@ function createHostApi(ctx, deps) {
17558
17569
  onReady: (fn) => {
17559
17570
  state.onReady.push(fn);
17560
17571
  },
17572
+ decideLoss: (fn) => {
17573
+ state.lossDeciders.push(fn);
17574
+ },
17561
17575
  onRestore: (fn) => {
17562
17576
  state.onRestore.push(fn);
17563
17577
  },
@@ -17602,6 +17616,12 @@ function createHostApi(ctx, deps) {
17602
17616
  });
17603
17617
  return true;
17604
17618
  },
17619
+ onGpu: (source) => {
17620
+ const app = state.app;
17621
+ if (!state.ready || app === void 0) return false;
17622
+ const slot = source._gpuData[app.renderer.uid];
17623
+ return slot !== void 0 && slot !== null;
17624
+ },
17605
17625
  initSource: (source) => {
17606
17626
  const app = state.app;
17607
17627
  if (!state.ready || app === void 0) return;
@@ -18206,7 +18226,7 @@ function renderStage1(kctx, pixi, matrices, record) {
18206
18226
  * @param record - The record, `s1` set.
18207
18227
  * @returns The stand-in.
18208
18228
  */
18209
- function standInOf(pixi, record) {
18229
+ function standInOf$1(pixi, record) {
18210
18230
  const s1 = record.s1 ?? pixi.Texture.EMPTY;
18211
18231
  if (record.standIn === void 0 || record.standIn.destroyed) {
18212
18232
  record.standIn = new pixi.Sprite(s1);
@@ -18410,7 +18430,7 @@ function readsPlace(record) {
18410
18430
  function renderStage3(kctx, pixi, matrices, record, now) {
18411
18431
  const { key } = record;
18412
18432
  const output = outputOf(kctx, pixi, record, now.r, now.P);
18413
- const standIn = standInOf(pixi, record);
18433
+ const standIn = standInOf$1(pixi, record);
18414
18434
  const Ps = key[KEY.Ps] ?? 0;
18415
18435
  if (readsPlace(record)) setOrigins(record.slots, (key[KEY.X0] ?? 0) - Ps + now.tx - (key[KEY.tx] ?? 0), (key[KEY.Y0] ?? 0) - Ps + now.ty - (key[KEY.ty] ?? 0));
18416
18436
  matrices.m3.set(1, 0, 0, 1, Ps, Ps);
@@ -18519,7 +18539,7 @@ function warnRefused(kctx, label) {
18519
18539
  if (state.warnedBudget) return;
18520
18540
  state.warnedBudget = true;
18521
18541
  kctx.ctx.log.warn("renderer:kept-budget", {
18522
- mb: roundTo(state.bytes / BYTES_PER_MB$1, 2),
18542
+ mb: roundTo(state.bytes / BYTES_PER_MB$2, 2),
18523
18543
  keptMb: kctx.ctx.config.keptMb,
18524
18544
  refused: label
18525
18545
  });
@@ -19458,7 +19478,7 @@ function createKeptState(config) {
19458
19478
  frame: 0,
19459
19479
  unsorted: false,
19460
19480
  bytes: 0,
19461
- budget: config.keptMb * BYTES_PER_MB$1,
19481
+ budget: config.keptMb * BYTES_PER_MB$2,
19462
19482
  takesOpen: 0,
19463
19483
  takesWindow: 0,
19464
19484
  refreshesOpen: 0,
@@ -20278,7 +20298,7 @@ function neededBytes(record, now, box) {
20278
20298
  * @param view - Its view.
20279
20299
  */
20280
20300
  function handFilters(kctx, pixi, record, view) {
20281
- const standIn = standInOf(pixi, record);
20301
+ const standIn = standInOf$1(pixi, record);
20282
20302
  kctx.sync.clearFilters(record.top);
20283
20303
  kctx.sync.applyFilters(view, filtersOf$1(kctx.ctx.state.sync, record.entity), noMark$1, standIn);
20284
20304
  }
@@ -22177,7 +22197,7 @@ function createKeptApi(ctx, deps) {
22177
22197
  sprite: (id) => spriteOf$1(kctx, id),
22178
22198
  stats: () => ({
22179
22199
  pictures: state.drawnPictures,
22180
- mb: roundTo(state.bytes / BYTES_PER_MB$1, 2),
22200
+ mb: roundTo(state.bytes / BYTES_PER_MB$2, 2),
22181
22201
  retakes: state.takesWindow,
22182
22202
  evicted: state.evictedWindow,
22183
22203
  refused: state.refusedWindow
@@ -22388,6 +22408,148 @@ function stopDemand(state) {
22388
22408
  state.verify.reference = void 0;
22389
22409
  }
22390
22410
  //#endregion
22411
+ //#region src/plugins/renderer/loss.ts
22412
+ /** The `localStorage` key of the kept records. */
22413
+ const LOSS_KEY = "moku-game:gpu-losses";
22414
+ /** Bytes in a megabyte. */
22415
+ const BYTES_PER_MB$1 = 1048576;
22416
+ /** Milliseconds in a second. */
22417
+ const MS_PER_S = 1e3;
22418
+ /**
22419
+ * Rounds to one decimal.
22420
+ *
22421
+ * @param value - A number.
22422
+ * @returns The number to one decimal.
22423
+ * @example
22424
+ * ```ts
22425
+ * tenth(12.345); // 12.3
22426
+ * ```
22427
+ */
22428
+ function tenth(value) {
22429
+ return Math.round(value * 10) / 10;
22430
+ }
22431
+ /**
22432
+ * Seconds since the page started: the wall clock against the page's time origin.
22433
+ *
22434
+ * @param now - The wall clock in milliseconds.
22435
+ * @returns The seconds, to one decimal; 0 where the page has no time origin.
22436
+ */
22437
+ function uptimeOf(now) {
22438
+ const origin = globalThis.performance?.timeOrigin;
22439
+ return origin === void 0 ? 0 : tenth((now - origin) / MS_PER_S);
22440
+ }
22441
+ /**
22442
+ * The JS heap in use, in megabytes, where the browser tells it: `performance.memory` of Chromium. WebKit has none.
22443
+ *
22444
+ * @returns The megabytes, or `undefined`: the record is kept without it.
22445
+ */
22446
+ function heapMb$1() {
22447
+ const used = (globalThis.performance?.memory)?.usedJSHeapSize;
22448
+ return typeof used === "number" ? tenth(used / BYTES_PER_MB$1) : void 0;
22449
+ }
22450
+ /**
22451
+ * The flow path the game stands on, or `""` before the graph runs.
22452
+ *
22453
+ * @param ctx - Domain context of the renderer plugin.
22454
+ * @returns The path.
22455
+ */
22456
+ function pathOf$1(ctx) {
22457
+ try {
22458
+ return ctx.deps.flow.state().path;
22459
+ } catch {
22460
+ return "";
22461
+ }
22462
+ }
22463
+ /**
22464
+ * Tells whether a parsed value has the fields of a kept record.
22465
+ *
22466
+ * @param value - A parsed element.
22467
+ * @returns True for an object with the fields the log reads.
22468
+ */
22469
+ function isLossRecord(value) {
22470
+ if (typeof value !== "object" || value === null) return false;
22471
+ const record = value;
22472
+ return typeof record.at === "number" && typeof record.kind === "string" && typeof record.reason === "string" && typeof record.path === "string" && typeof record.freed === "number" && typeof record.reloaded === "boolean";
22473
+ }
22474
+ /**
22475
+ * Reads the kept records. Anything that is not a list, and a storage that throws, reads as none.
22476
+ *
22477
+ * @returns The records, oldest first.
22478
+ */
22479
+ function readLosses() {
22480
+ try {
22481
+ const text = globalThis.localStorage?.getItem(LOSS_KEY);
22482
+ const parsed = text === null || text === void 0 ? [] : JSON.parse(text);
22483
+ return Array.isArray(parsed) ? parsed.filter((value) => isLossRecord(value)) : [];
22484
+ } catch {
22485
+ return [];
22486
+ }
22487
+ }
22488
+ /**
22489
+ * Keeps the newest records. A storage that refuses the write (private mode, full) keeps nothing: the log still has
22490
+ * the loss.
22491
+ *
22492
+ * @param records - The records, oldest first.
22493
+ */
22494
+ function writeLosses(records) {
22495
+ try {
22496
+ globalThis.localStorage?.setItem(LOSS_KEY, JSON.stringify(records.slice(-10)));
22497
+ } catch {}
22498
+ }
22499
+ /**
22500
+ * Reloads the page. Headless and in a test there is no page, so nothing happens.
22501
+ */
22502
+ function reloadPage$2() {
22503
+ globalThis.location?.reload();
22504
+ }
22505
+ /**
22506
+ * Records a lost device and decides whether the page leaves: it reloads when textures had their decoded image freed,
22507
+ * since they cannot be uploaded to a new device; without any, the renderer restores as before. The `decideLoss`
22508
+ * callback of the plugin root.
22509
+ *
22510
+ * @param ctx - Domain context of the renderer plugin.
22511
+ * @param info - What was lost and the texture bytes the lost application held.
22512
+ * @param freed - How many textures hold the stand-in instead of their decoded image.
22513
+ * @param reload - Reloads the page; a test passes a spy.
22514
+ * @returns True when the page reloads.
22515
+ */
22516
+ function leaveAfterLoss(ctx, info, freed, reload = reloadPage$2) {
22517
+ const reloaded = freed > 0;
22518
+ const now = ctx.deps.clock.now();
22519
+ const record = {
22520
+ at: now,
22521
+ uptimeS: uptimeOf(now),
22522
+ kind: info.kind,
22523
+ reason: info.reason,
22524
+ path: pathOf$1(ctx),
22525
+ textureMb: tenth(info.textureBytes / BYTES_PER_MB$1),
22526
+ heapMb: heapMb$1(),
22527
+ freed,
22528
+ reloaded,
22529
+ reported: false
22530
+ };
22531
+ ctx.log.error("renderer:gpu-lost", record);
22532
+ writeLosses([...readLosses(), record]);
22533
+ if (reloaded) reload();
22534
+ return reloaded;
22535
+ }
22536
+ /**
22537
+ * Logs every kept loss no start has reported yet, once: the line a phone shows after the reload a loss caused. Called
22538
+ * when the renderer starts.
22539
+ *
22540
+ * @param ctx - Domain context of the renderer plugin.
22541
+ */
22542
+ function reportLosses(ctx) {
22543
+ const records = readLosses();
22544
+ const unreported = records.filter((record) => record.reported !== true);
22545
+ if (unreported.length === 0) return;
22546
+ for (const record of unreported) ctx.log.warn("renderer:gpu-lost-before", record);
22547
+ writeLosses(records.map((record) => ({
22548
+ ...record,
22549
+ reported: true
22550
+ })));
22551
+ }
22552
+ //#endregion
22391
22553
  //#region src/plugins/renderer/monitor/log-types.ts
22392
22554
  /**
22393
22555
  * The version every line carries as `v`.
@@ -22827,7 +22989,7 @@ function usedHeapBytes() {
22827
22989
  */
22828
22990
  function heapMb() {
22829
22991
  const bytes = usedHeapBytes();
22830
- return Number.isNaN(bytes) ? null : roundTo(bytes / BYTES_PER_MB$1, 2);
22992
+ return Number.isNaN(bytes) ? null : roundTo(bytes / BYTES_PER_MB$2, 2);
22831
22993
  }
22832
22994
  //#endregion
22833
22995
  //#region src/plugins/renderer/monitor/problems.ts
@@ -25192,16 +25354,16 @@ function sampleLine(pc, start, end) {
25192
25354
  heapMb: (sections & SECTION.memory) === 0 ? null : heapMb(),
25193
25355
  kept: {
25194
25356
  pictures: totals.keptMax,
25195
- mb: roundTo(pc.ctx.state.kept.bytes / BYTES_PER_MB$1, 2),
25357
+ mb: roundTo(pc.ctx.state.kept.bytes / BYTES_PER_MB$2, 2),
25196
25358
  retakes: totals.retakes,
25197
25359
  refreshes: deps.kept.drainRefreshes()
25198
25360
  },
25199
25361
  textures: {
25200
25362
  count: usage.count,
25201
- mb: ms(usage.bytes / BYTES_PER_MB$1),
25202
- art: ms(usage.art / BYTES_PER_MB$1),
25203
- targets: ms(usage.targets / BYTES_PER_MB$1),
25204
- kept: ms(usage.kept / BYTES_PER_MB$1)
25363
+ mb: ms(usage.bytes / BYTES_PER_MB$2),
25364
+ art: ms(usage.art / BYTES_PER_MB$2),
25365
+ targets: ms(usage.targets / BYTES_PER_MB$2),
25366
+ kept: ms(usage.kept / BYTES_PER_MB$2)
25205
25367
  },
25206
25368
  views: views.views,
25207
25369
  pooled: views.pooled,
@@ -25751,7 +25913,7 @@ function writeEvent(pc, name, detail) {
25751
25913
  /** A flush once a second of page clock. */
25752
25914
  const FLUSH_MS = 1e3;
25753
25915
  /** A heap drop of at least this many bytes between two commits hints at a collection. */
25754
- const GC_DROP_BYTES = .5 * BYTES_PER_MB$1;
25916
+ const GC_DROP_BYTES = .5 * BYTES_PER_MB$2;
25755
25917
  /** Pixels per megapixel. */
25756
25918
  const PIXELS_PER_MPX = 1e6;
25757
25919
  /** The most skipped frames the 8-bit `skipped` column holds; more are written as this. */
@@ -25799,7 +25961,7 @@ function writePasses(pc, slot) {
25799
25961
  c.filterApplies[slot] = counted ? cellF64(counts, COUNT.filterApplies) : NaN;
25800
25962
  c.filterMpx[slot] = counted ? cellF64(counts, COUNT.filterPixels) / PIXELS_PER_MPX : NaN;
25801
25963
  c.uploads[slot] = counted ? cellF64(counts, COUNT.uploads) : NaN;
25802
- c.uploadMb[slot] = counted ? cellF64(counts, COUNT.uploadBytes) / BYTES_PER_MB$1 : NaN;
25964
+ c.uploadMb[slot] = counted ? cellF64(counts, COUNT.uploadBytes) / BYTES_PER_MB$2 : NaN;
25803
25965
  c.rebuilds[slot] = perf.produced === 0 ? NaN : cellF64(counts, COUNT.rebuilds);
25804
25966
  const targets = (bits & MEASURE.targets) !== 0;
25805
25967
  c.targetsCreated[slot] = targets ? cellF64(counts, COUNT.targetsCreated) : NaN;
@@ -27356,11 +27518,11 @@ function createMonitorApi(ctx, deps) {
27356
27518
  drawn: drawing ? roundTo(state.drawnFps, 1) : 0,
27357
27519
  frameMs: roundTo(state.frameMs, 2),
27358
27520
  textures: usage.count,
27359
- textureMb: roundTo(usage.bytes / BYTES_PER_MB$1, 2),
27521
+ textureMb: roundTo(usage.bytes / BYTES_PER_MB$2, 2),
27360
27522
  textureMbSplit: {
27361
- art: roundTo(usage.art / BYTES_PER_MB$1, 2),
27362
- targets: roundTo(usage.targets / BYTES_PER_MB$1, 2),
27363
- kept: roundTo(usage.kept / BYTES_PER_MB$1, 2)
27523
+ art: roundTo(usage.art / BYTES_PER_MB$2, 2),
27524
+ targets: roundTo(usage.targets / BYTES_PER_MB$2, 2),
27525
+ kept: roundTo(usage.kept / BYTES_PER_MB$2, 2)
27364
27526
  },
27365
27527
  views: counts.views,
27366
27528
  pooled: counts.pooled,
@@ -30857,6 +31019,83 @@ function paintShape(object, value, color) {
30857
31019
  strokeShape(object, value);
30858
31020
  }
30859
31021
  //#endregion
31022
+ //#region src/plugins/renderer/sync/release.ts
31023
+ /**
31024
+ * Tells whether a decoded image can be freed: an `ImageBitmap` has `close`, an `<img>` element has none.
31025
+ *
31026
+ * @param image - The decoded image.
31027
+ * @returns True for an image with `close`.
31028
+ */
31029
+ function isClosable(image) {
31030
+ return typeof image === "object" && image !== null && "close" in image && typeof image.close === "function";
31031
+ }
31032
+ /**
31033
+ * The 1x1 transparent image every freed source holds, made once per renderer: a canvas with a 2d context, which both
31034
+ * `copyExternalImageToTexture` and `texSubImage2D` take.
31035
+ *
31036
+ * @param release - The release branch of the sync state.
31037
+ * @returns The stand-in.
31038
+ */
31039
+ function standInOf(release) {
31040
+ if (release.standIn !== void 0) return release.standIn;
31041
+ const canvas = new OffscreenCanvas(1, 1);
31042
+ canvas.getContext("2d");
31043
+ release.standIn = canvas;
31044
+ return canvas;
31045
+ }
31046
+ /**
31047
+ * Remembers a new source of `textures.create` whose decoded image can be freed: it waits for its upload. An image that
31048
+ * cannot be closed, or a runtime without `OffscreenCanvas`, keeps its image.
31049
+ *
31050
+ * @param state - The sync branch of the plugin state.
31051
+ * @param source - The source just made.
31052
+ */
31053
+ function holdImage(state, source) {
31054
+ if (!isClosable(source.resource) || typeof OffscreenCanvas === "undefined") return;
31055
+ state.release.pending.push(source);
31056
+ }
31057
+ /**
31058
+ * Frees the decoded images Pixi has on the GPU now: each bitmap is closed and its source gets the stand-in. A source
31059
+ * not uploaded yet keeps waiting, and one destroyed meanwhile leaves the list. Runs after the stage pass of a drawn
31060
+ * frame; one compare while nothing waits, and no allocation while sources wait (the body of the sync module's
31061
+ * `releaseStep`).
31062
+ *
31063
+ * @param sctx - Domain context of the sync module.
31064
+ */
31065
+ function releaseStep(sctx) {
31066
+ const { release } = sctx.ctx.state.sync;
31067
+ const pending = release.pending;
31068
+ if (pending.length === 0) return;
31069
+ let kept = 0;
31070
+ for (let index = 0; index < pending.length; index += 1) {
31071
+ const source = pending[index];
31072
+ if (source === void 0 || source.destroyed) continue;
31073
+ if (!sctx.deps.host.onGpu(source)) {
31074
+ pending[kept] = source;
31075
+ kept += 1;
31076
+ continue;
31077
+ }
31078
+ const image = source.resource;
31079
+ source.resource = standInOf(release);
31080
+ release.freed.add(source);
31081
+ if (isClosable(image)) image.close();
31082
+ }
31083
+ pending.length = kept;
31084
+ }
31085
+ /**
31086
+ * Frees the decoded image of a source that goes before its upload, at once instead of at the next collection, and
31087
+ * forgets a freed one. A freed source holds the stand-in and closes nothing.
31088
+ *
31089
+ * @param state - The sync branch of the plugin state.
31090
+ * @param source - The source of a texture being destroyed.
31091
+ */
31092
+ function dropImage(state, source) {
31093
+ const { release } = state;
31094
+ if (release.freed.delete(source)) return;
31095
+ const image = source.resource;
31096
+ if (isClosable(image)) image.close();
31097
+ }
31098
+ //#endregion
30860
31099
  //#region src/plugins/renderer/sync/textures.ts
30861
31100
  /** The colour a missing texture is drawn in. */
30862
31101
  const PLACEHOLDER_TINT = 16711935;
@@ -30964,6 +31203,7 @@ function defaultBordersOf(nine) {
30964
31203
  }
30965
31204
  /**
30966
31205
  * Makes a Pixi texture out of a decoded image, on behalf of `assets`, which decides when it leaves the GPU.
31206
+ * An ImageBitmap is held until its source is on the GPU, then closed and replaced by a 1x1 stand-in (sync/release.ts).
30967
31207
  *
30968
31208
  * @param sctx - Domain context of the sync module.
30969
31209
  * @param image - The decoded image.
@@ -30979,6 +31219,7 @@ function createTexture(sctx, image, options) {
30979
31219
  }) : pixi.Texture.from(image);
30980
31220
  const nine = options?.nine;
30981
31221
  base.source.autoGarbageCollect = false;
31222
+ holdImage(sctx.ctx.state.sync, base.source);
30982
31223
  if (nine === void 0) return base;
30983
31224
  const bordered = new pixi.Texture({
30984
31225
  source: base.source,
@@ -31134,7 +31375,7 @@ function clearFrames(state) {
31134
31375
  * Frees a texture, its source and the crops cut from it. A slice keeps the source: it belongs to
31135
31376
  * the page, which frees it. A source that goes lets go of its `change` listeners first, the ones
31136
31377
  * of its style too, so no bind group Pixi still keeps is told. A texture destroyed twice is a
31137
- * no-op.
31378
+ * no-op. A bitmap not yet uploaded is closed at once, and a freed source leaves the freed list.
31138
31379
  *
31139
31380
  * @param state - The sync branch of the plugin state.
31140
31381
  * @param texture - The texture to free.
@@ -31146,6 +31387,7 @@ function destroyTexture(state, texture) {
31146
31387
  texture.destroy(false);
31147
31388
  return;
31148
31389
  }
31390
+ dropImage(state, texture.source);
31149
31391
  destroyWhole(texture);
31150
31392
  }
31151
31393
  //#endregion
@@ -34069,9 +34311,9 @@ function withDeps$8(ctx) {
34069
34311
  * drawn and clears them; a drawn frame draws the probes of the warm-up onto the canvas first (F4: the
34070
34312
  * stage pass clears them, in the same task, so they never show), then uploads the queued texture sources (F60), then
34071
34313
  * the kept pictures (`kept.flush`, so the canvas stays one pass, E7), then the stage, then a shot of the frame just drawn
34072
- * while the canvas texture holds it (`shots.after`, never of the heat map), then the pixel leg of the kept oracle;
34073
- * `demand` settles the
34074
- * frame (the dev check, the pixel oracle), and `monitor` closes it and hands a drawn one to a
34314
+ * while the canvas texture holds it (`shots.after`, never of the heat map), then, when Pixi drew it, the decoded images
34315
+ * now on the GPU are freed (`sync.releaseStep`, F189), then the pixel leg of the kept oracle;
34316
+ * `demand` settles the frame (the dev check, the pixel oracle), and `monitor` closes it and hands a drawn one to a
34075
34317
  * waiting capture; last, `host` trims Pixi's texture pool when a rest or a scene change is due. The display objects
34076
34318
  * are written by the `sync` system. While the overdraw heat map of a dev or debug build is on, every frame asks to be
34077
34319
  * drawn and its stage pass is drawn as the map (`sync.drawOverdraw`).
@@ -34113,6 +34355,7 @@ function renderFrame(ctx, modules) {
34113
34355
  if (rendered) {
34114
34356
  ctx.deps.time.frameDrawn();
34115
34357
  if (probed || uploaded || built) ctx.deps.time.frameProbed();
34358
+ modules.sync.releaseStep();
34116
34359
  }
34117
34360
  modules.kept.after();
34118
34361
  }
@@ -34135,6 +34378,7 @@ function renderFrame(ctx, modules) {
34135
34378
  async function startRenderer(ctx) {
34136
34379
  const rendererCtx = withDeps$8(ctx);
34137
34380
  const modules = createModules$1(rendererCtx);
34381
+ reportLosses(rendererCtx);
34138
34382
  modules.host.onResolution(() => modules.demand.whole("resize"));
34139
34383
  modules.host.onReady(() => {
34140
34384
  modules.viewport.start();
@@ -34148,6 +34392,7 @@ async function startRenderer(ctx) {
34148
34392
  modules.sync.forget();
34149
34393
  modules.shots.forget();
34150
34394
  });
34395
+ modules.host.decideLoss((info) => leaveAfterLoss(rendererCtx, info, modules.sync.freedCount()));
34151
34396
  modules.host.onRestore((rebuilt) => {
34152
34397
  modules.demand.whole("restore");
34153
34398
  if (!rebuilt) return;
@@ -37398,6 +37643,8 @@ function createSyncApi(ctx, deps) {
37398
37643
  warmStep: () => warmStep(sctx),
37399
37644
  takeBuildWork: () => takeBuildWork(state.aside),
37400
37645
  uploadStep: () => uploadStep(sctx),
37646
+ releaseStep: () => releaseStep(sctx),
37647
+ freedCount: () => state.release.freed.size,
37401
37648
  onWarm: (fn) => {
37402
37649
  state.warm.listeners.push(fn);
37403
37650
  },
@@ -38232,6 +38479,19 @@ function createUploadState() {
38232
38479
  return upload;
38233
38480
  }
38234
38481
  /**
38482
+ * Creates the empty release branch: no bitmap waits, none was freed, no stand-in made yet. Its own non-exported
38483
+ * function, as `emptyMap`.
38484
+ *
38485
+ * @returns The release branch of the sync state.
38486
+ */
38487
+ function createReleaseState() {
38488
+ return {
38489
+ pending: [],
38490
+ freed: emptySet$4(),
38491
+ standIn: void 0
38492
+ };
38493
+ }
38494
+ /**
38235
38495
  * Creates the empty aside queue of a scene build: nothing waits for a view. Its own non-exported function, as
38236
38496
  * `emptyMap`.
38237
38497
  *
@@ -38290,6 +38550,7 @@ function createSyncState(debug) {
38290
38550
  viewlessEntries: false,
38291
38551
  warm: createWarmState(),
38292
38552
  upload: createUploadState(),
38553
+ release: createReleaseState(),
38293
38554
  hollowClass: void 0,
38294
38555
  filterKinds: emptyWeakMap$1(),
38295
38556
  filterOwners: emptyWeakMap$1(),