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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/core/CoreNode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ import { CoreNode, type CoreNodeProps, UpdateType } from './CoreNode.js';
import { Stage } from './Stage.js';
import { CoreRenderer } from './renderers/CoreRenderer.js';
import { mock } from 'vitest-mock-extended';
import { type TextureOptions } from './CoreTextureManager.js';
import {
type CoreTextureManager,
type TextureOptions,
} from './CoreTextureManager.js';
import { createBound } from './lib/utils.js';
import { ImageTexture } from './textures/ImageTexture.js';

Expand Down Expand Up @@ -79,6 +82,7 @@ describe('CoreNode', () => {
state: 'loaded',
},
renderer: mock<CoreRenderer>() as CoreRenderer,
txManager: mock<CoreTextureManager>({ frame: 0 }) as CoreTextureManager,
});

describe('set color()', () => {
Expand Down
6 changes: 6 additions & 0 deletions src/core/CoreNode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1546,6 +1546,12 @@ export class CoreNode extends EventEmitter {

const previous = this.renderState;
this.renderState = renderState;
// An image coming on screen uploads ahead of preload-margin images.
const texture = this.props.texture;
if (renderState === CoreNodeRenderState.InViewport && texture) {
texture.lastOnScreen = this.stage.txManager.frame;
this.stage.txManager.prioritize(texture);
}
const event = CoreNodeRenderStateMap.get(renderState);
assertTruthy(event);
this.emit(event, {
Expand Down
24 changes: 24 additions & 0 deletions src/core/CoreTextureManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,8 +241,32 @@ export class CoreTextureManager extends EventEmitter {
*
* @param texture - The texture to upload
*/
/**
* Frames drawn, advanced by the Stage: how recently a texture was on screen
* (upload order, memory cleanup order).
*/
public frame = 0;

/**
* An image just came on screen: if its upload is queued, move it to the
* front, ahead of images preloading in the bounds margin.
*/
prioritize(texture: Texture): void {
const i = this.uploadTextureQueue.indexOf(texture);
if (i > 0) {
this.uploadTextureQueue.splice(i, 1);
this.uploadTextureQueue.unshift(texture);
}
}

enqueueUploadTexture(texture: Texture): void {
if (this.uploadTextureQueue.includes(texture) === false) {
// On screen within the last ~second (it came into view while still
// fetching): upload it first.
if (this.frame - texture.lastOnScreen < 60) {
this.uploadTextureQueue.unshift(texture);
return;
}
this.uploadTextureQueue.push(texture);
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/core/Stage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,8 @@ export class Stage {
root.update(this.deltaTime, root.clippingRect);
}

this.txManager.frame++;

// Process some textures asynchronously but don't block the frame
// Use a background task to prevent frame drops
if (this.txManager.hasUpdates() === true) {
Expand Down
21 changes: 17 additions & 4 deletions src/core/TextureMemoryManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,15 +248,28 @@ export class TextureMemoryManager {
// Skip null entries, mark cleaned textures as null for later defrag
let currentMemUsed = this.memUsed;

for (let i = 0; i < this.loadedTextures.length; i++) {
// Least recently on screen first, not oldest loaded: oldest-first freed a
// home page's posters (loaded first, still one Back press away) before a
// page's that would never be seen again. A texture owned by a node is in
// view now, so its age counts from now. Cleanup is rare, so the sort is
// cheap next to the GPU memory it frees.
const now = this.stage.txManager.frame;
const candidates: Texture[] = [];
for (const texture of this.loadedTextures) {
if (!texture) continue; // Skip null entries from previous deletions
if (texture.renderableOwners.length > 0) {
texture.lastOnScreen = now;
}
candidates.push(texture);
}
candidates.sort((a, b) => a.lastOnScreen - b.lastOnScreen);

for (const texture of candidates) {
// Early exit: target memory reached
if (full === false && currentMemUsed < memTarget) {
break;
}

const texture = this.loadedTextures[i];
if (!texture) continue; // Skip null entries from previous deletions

// Fast type check for cleanable textures
const isCleanableType =
texture.type === TextureType.image ||
Expand Down
29 changes: 29 additions & 0 deletions src/core/platforms/web/WebPlatform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@ interface FontFaceSetWithAdd extends FontFaceSet {
add(font: FontFace): this;
}

/**
* Deadline for one image request, in milliseconds. A poster is tens to a few
* hundred KB from a CDN, so a healthy request finishes well under a second;
* past 5s it has stalled, and the retry (1s, 2s, 4s...) recovers it sooner
* than waiting longer would. On a very slow link a large image that needs
* more than 5s will not load; raise this if that is seen on devices.
*/
const FETCH_TIMEOUT_MS = 5000;

export class WebPlatform extends Platform {
private useImageWorker: boolean;
private imageWorkerManager: ImageWorkerManager | null = null;
Expand Down Expand Up @@ -213,6 +222,26 @@ export class WebPlatform extends Platform {
}
}
};
// A request that never completes (seen on tvOS NativeScript: the server
// answered, the XHR never heard back) would hold its image forever, never
// loaded and never retried. Past the deadline it fails like a network
// error, so the texture retries.
const timer = setTimeout(() => {
xhr.onreadystatechange = null;
try {
xhr.abort();
} catch {
// rejected below either way
}
reject(new Error(`Timed out loading ${url}`));
}, FETCH_TIMEOUT_MS);
const settle = xhr.onreadystatechange;
xhr.onreadystatechange = function (event) {
if (xhr.readyState === 4) {
clearTimeout(timer);
}
settle.call(this, event);
};
xhr.open('GET', url, true);
xhr.send(null);
});
Expand Down
14 changes: 10 additions & 4 deletions src/core/textures/ImageTexture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,9 @@ export interface ImageTextureProps {
/**
* Maximum number of times to retry loading the image if it fails.
*
* @default 5
* @default the stage's `maxRetryCount` setting
*/
maxRetryCount?: number;
maxRetryCount?: number | null;
}

export interface ImageResponse {
Expand Down Expand Up @@ -139,7 +139,10 @@ export class ImageTexture extends Texture {

this.platform = txManager.platform;
this.props = props;
this.maxRetryCount = props.maxRetryCount as number;
// Only an explicit per-texture count overrides the stage's.
if (props.maxRetryCount !== null) {
this.maxRetryCount = props.maxRetryCount;
}
}

override async getTextureSource(): Promise<TextureData> {
Expand Down Expand Up @@ -278,7 +281,10 @@ export class ImageTexture extends Texture {
sy: props.sy ?? null,
sw: props.sw ?? null,
sh: props.sh ?? null,
maxRetryCount: props.maxRetryCount ?? 5,
// Unset stays unset, so the Texture keeps the stage's maxRetryCount from
// its constructor. The `src` setter passes none, so a hard default of 5
// meant the app's setting never reached a single image.
maxRetryCount: props.maxRetryCount ?? null,
};
}

Expand Down
33 changes: 33 additions & 0 deletions src/core/textures/Texture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,16 @@ export abstract class Texture extends EventEmitter {
* is loaded/freed. Set to 0 when texture is not loaded.
*/
public retryCount = 0;
/** Earliest time of the next load attempt after a failure. */
public retryAt = 0;
private retryTimer: ReturnType<typeof setTimeout> | null = null;
static RETRY_FIRST_MS = 1000;
static RETRY_MAX_MS = 60000;
/**
* The texture manager frame at which a node showing this texture last came
* on screen: orders the upload queue and memory cleanup.
*/
public lastOnScreen = -Infinity;
public maxRetryCount: number;

/**
Expand Down Expand Up @@ -322,6 +332,20 @@ export abstract class Texture extends EventEmitter {
// We've exceeded the max retry count, do not attempt to load again
return;
}
// Still inside the retry wait: a timer brings it back, and loads only if
// a node still wants the texture by then.
const wait = this.retryAt - Date.now();
if (wait > 0) {
if (this.retryTimer === null) {
this.retryTimer = setTimeout(() => {
this.retryTimer = null;
if (this.renderableOwners.length > 0) {
this.load();
}
}, wait);
}
return;
}
this.txManager.loadTexture(this);
}

Expand Down Expand Up @@ -430,6 +454,15 @@ export abstract class Texture extends EventEmitter {
// this is used to compare against maxRetryCount, if set
// to determine if we should try loading again
this.retryCount += 1;
// The next attempt waits, doubling from 1s to 60s. Back-to-back retries
// spent the whole count in a few seconds of bad network, and the image
// then never loaded again for the session.
this.retryAt =
Date.now() +
Math.min(
Texture.RETRY_MAX_MS,
Texture.RETRY_FIRST_MS * 2 ** (this.retryCount - 1),
);

queueMicrotask(this.releaseTask);
} else if (state === 'loading') {
Expand Down