Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(runtime): the bar moves while the engine downloads, not only when it lands

esengine21e320b25edf
diff --git a/pipeline/src/export/splash.ts b/pipeline/src/export/splash.ts
index 92c887859..ab0d38ab2 100644
--- a/pipeline/src/export/splash.ts
+++ b/pipeline/src/export/splash.ts
@@ -86,6 +86,10 @@ export function splashHtml(title: string, look: SplashLook = {}): string {
export interface Splash {
/** Mark a stage finished and advance the bar by that stage's weight. */
reach(stage: BootStage): void;
+ /** How far through a stage that has NOT finished — `0..1` of its own weight.
+ * `engine` alone is 40 of the 100, so a bar that only moves on completion
+ * stands still for most of a cold start. */
+ within(stage: BootStage, fraction: number): void;
/** Fade out and remove. Safe to call twice. */
done(): void;
}
@@ -94,7 +98,7 @@ export interface Splash {
* The events a page outside the bundle listens for — a portal SDK's own loading
* screen. DOM events, not a global: a listener must be added BEFORE the bundle
* runs, and the page carries no script of ours to define one on. `progress` is
- * 0..1 and never goes backwards.
+ * 0..1 and never goes backwards; `partial` marks a stage still running.
*/
export const BOOT_PROGRESS_EVENT = 'esengine:bootprogress';
export const FIRST_FRAME_EVENT = 'esengine:firstframe';
@@ -112,6 +116,8 @@ export function attachSplash(doc: Document = document): Splash {
const label = root && doc.getElementById(LABEL);
const showUntil = Date.now() + Number(root?.getAttribute('data-min-ms') ?? 0);
let done = 0;
+ /** What the bar is showing, so a partial step never pulls it back. */
+ let shown = 0;
let finished = false;
const seen = new Set<BootStage>();
const announce = (type: string, detail: unknown): void => {
@@ -123,7 +129,26 @@ export function attachSplash(doc: Document = document): Splash {
root.classList.add('es-splash-gone');
setTimeout(() => root.remove(), 400);
};
+ /** Never backwards. Answers whether the bar actually moved a whole percent,
+ * which is the only movement worth telling a portal's own screen about. */
+ const show = (progress: number): boolean => {
+ if (progress <= shown) return false;
+ const was = Math.round(shown * 100);
+ shown = progress;
+ const now = Math.round(progress * 100);
+ if (bar) bar.style.width = `${now}%`;
+ return now > was;
+ };
return {
+ within(stage, fraction) {
+ if (seen.has(stage)) return;
+ const weight = BOOT_STAGES.find((s) => s.id === stage)?.weight ?? 0;
+ const partial = Math.max(0, Math.min(1, fraction)) * weight;
+ const progress = Math.min(1, (done + partial) / BOOT_TOTAL);
+ // `partial` marks a stage still running, so a listener can tell "40% of
+ // the way through fetching the engine" from "the engine is up".
+ if (show(progress)) announce(BOOT_PROGRESS_EVENT, { stage, progress, partial: true });
+ },
reach(stage) {
// Idempotent by stage, not additive: a retried leg must not push the bar
// past what it has actually finished.
@@ -131,7 +156,7 @@ export function attachSplash(doc: Document = document): Splash {
seen.add(stage);
done += BOOT_STAGES.find((s) => s.id === stage)?.weight ?? 0;
const progress = Math.min(1, done / BOOT_TOTAL);
- if (bar) bar.style.width = `${Math.round(progress * 100)}%`;
+ show(progress);
const at = BOOT_STAGES.findIndex((s) => s.id === stage);
const next = BOOT_STAGES[at + 1];
if (label && next) label.textContent = `${next.says}…`;
@@ -140,7 +165,7 @@ export function attachSplash(doc: Document = document): Splash {
done() {
if (finished) return;
finished = true;
- if (bar) bar.style.width = '100%';
+ show(1);
announce(FIRST_FRAME_EVENT, {});
// A boot that finished in 120ms would otherwise flash a bar that appears
// and vanishes, which reads as a glitch rather than as loading.
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index 0bd6825c2..893069b30 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -57,7 +57,52 @@ import type {
SceneData, AddressableManifest, PackagedGameConfig, RenderSurfaceSource, WorldManifest,
} from 'esengine';
import type { ESEngineModule } from 'esengine/wasm';
-import { attachSplash } from '../export/splash';
+import { attachSplash, type Splash } from '../export/splash';
+
+/**
+ * Fetch the engine binary through a stream we can count, and hand the SAME
+ * stream to the compiler — emscripten fetches it itself otherwise and nothing
+ * sees the bytes. Re-wrapping the body keeps `instantiateStreaming`: reading it
+ * to an ArrayBuffer first would buy the bar at the cost of what it measures.
+ */
+function engineInstantiator(url: string, splash: Splash | null) {
+ return (imports: WebAssembly.Imports,
+ ok: (inst: WebAssembly.Instance, mod: WebAssembly.Module) => void): Record<string, never> => {
+ void (async () => {
+ const res = await fetch(url);
+ const total = Number(res.headers.get('content-length') ?? 0);
+ // No length or no stream ⇒ the honest answer is the stage weight alone.
+ const source = total > 0 && res.body ? new Response(counted(res.body, total, splash), {
+ headers: { 'content-type': 'application/wasm' },
+ }) : res;
+ const { instance, module } = await WebAssembly.instantiateStreaming(source, imports);
+ ok(instance, module);
+ })();
+ return {};
+ };
+}
+
+/** The same bytes, announced as they pass. */
+function counted(body: ReadableStream<Uint8Array>, total: number, splash: Splash | null): ReadableStream<Uint8Array> {
+ const reader = body.getReader();
+ let got = 0;
+ return new ReadableStream<Uint8Array>({
+ async pull(controller) {
+ const { done, value } = await reader.read();
+ if (done) {
+ controller.close();
+ return;
+ }
+ got += value.byteLength;
+ splash?.within('engine', got / total);
+ controller.enqueue(value);
+ },
+ cancel(reason) {
+ void reader.cancel(reason);
+ },
+ });
+}
+
async function boot(): Promise<void> {
const canvas = document.getElementById('canvas') as HTMLCanvasElement;
// Null on a page without one, and every call below is then a no-op: a start
@@ -143,6 +188,7 @@ async function boot(): Promise<void> {
const module = await createModule({
canvas,
locateFile: (p: string) => `${wasmBase}${p}`,
+ instantiateWasm: engineInstantiator(`${wasmBase}esengine.wasm`, splash),
print: (t: string) => console.log(t),
printErr: (t: string) => console.error(t),
...(gpu.device ? { preinitializedWebGPUDevice: gpu.device } : {}),
diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjs
index fa3c2a54d..d52ea4fcd 100644
--- a/tools/goldenProjects.mjs
+++ b/tools/goldenProjects.mjs
@@ -893,9 +893,10 @@ export const GOLDEN = [
// limit. Naming it here lets the host REFUSE it too: on a bad network the
// game cannot start, and all it can still do is say which package failed.
subpackage: { name: 'engine' },
- // A first screen is a question about a NETWORK — on this machine the whole
- // boot beats the splash's own fade. Judged over a declared link instead.
- firstScreen: { link: 'slow-4g', maxMs: 300 },
+ // A first screen is a question about a NETWORK: on this machine the whole
+ // boot beats the splash's fade. `maxStillMs` is the longest the bar may
+ // stand still — 8s leaves room for the bundle's own download.
+ firstScreen: { link: 'slow-4g', maxMs: 300, maxStillMs: 8000 },
},
{
id: 'sprite-animation',
diff --git a/tools/launchers/launch-export.mjs b/tools/launchers/launch-export.mjs
index 13ff9b734..c32e7f3ff 100644
--- a/tools/launchers/launch-export.mjs
+++ b/tools/launchers/launch-export.mjs
@@ -118,6 +118,7 @@ const BOOT_RECORDER = `(() => {
ms: Math.round(performance.now()),
stage: e.detail && e.detail.stage,
progress: e.detail && e.detail.progress,
+ partial: !!(e.detail && e.detail.partial),
}));
addEventListener('esengine:firstframe', () => { firstFrame = Math.round(performance.now()); });
window.__estellaBoot = () => {
@@ -174,8 +175,13 @@ function serve(root, safeArea, frameMs) {
if (injected === html) console.log(' no <head> to inject the safe area or clock into');
bytes = Buffer.from(injected);
}
- res.writeHead(200, { 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream' })
- .end(bytes);
+ // Content-Length, which node omits unless told (it chunks instead): every
+ // real server sends it, and a loader that reports download progress has
+ // nothing to divide by without it.
+ res.writeHead(200, {
+ 'content-type': MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream',
+ 'content-length': bytes.length,
+ }).end(bytes);
} catch {
res.writeHead(404).end();
}
@@ -336,7 +342,13 @@ const SCENE = flag('scene', '');
// than one that stops, and only the sequence can say which happened.
const steps = (seen?.marks ?? []).map((m) => m.progress);
const backwards = steps.findIndex((p, i) => i > 0 && p < steps[i - 1]);
- console.log(` boot: ${JSON.stringify({ ...seen, monotonic: backwards < 0 })}`);
+ // The longest the bar stood still while the player was looking at it —
+ // measured from the screen appearing to the frame arriving, so a stage that
+ // reports nothing for its whole length is counted rather than averaged away.
+ const at = [seen?.firstScreenMs, ...(seen?.marks ?? []).map((m) => m.ms), seen?.firstFrameMs]
+ .filter((n) => typeof n === 'number');
+ const stillMs = at.reduce((worst, n, i) => (i > 0 ? Math.max(worst, n - at[i - 1]) : worst), 0);
+ console.log(` boot: ${JSON.stringify({ ...seen, monotonic: backwards < 0, stillMs })}`);
if (backwards >= 0) errors.push(`the boot bar went backwards at step ${backwards}`);
}
diff --git a/tools/verify-golden.mjs b/tools/verify-golden.mjs
index c546bc059..ed5403762 100644
--- a/tools/verify-golden.mjs
+++ b/tools/verify-golden.mjs
@@ -454,16 +454,21 @@ for (const { id, target } of pairs) {
let boot = null;
try { boot = found ? JSON.parse(found[1]) : null; } catch { boot = null; }
const at = boot?.firstScreenMs ?? null;
- const ok = typeof at === 'number' && at <= firstScreen.maxMs && boot?.monotonic === true;
+ const still = boot?.stillMs ?? Infinity;
+ const ok = typeof at === 'number' && at <= firstScreen.maxMs && boot?.monotonic === true
+ && still <= firstScreen.maxStillMs;
results.push({
id, target, stage: 'first-screen', ok,
why: ok ? '' : at === null
? 'the page reported no first paint at all — nothing was on screen to time'
- : `the start screen appeared at ${at}ms over ${firstScreen.link}`
- + ` (limit ${firstScreen.maxMs}ms)${boot?.monotonic === false ? ', and its progress went backwards' : ''}`,
+ : at > firstScreen.maxMs
+ ? `the start screen appeared at ${at}ms over ${firstScreen.link} (limit ${firstScreen.maxMs}ms)`
+ : boot?.monotonic === false ? 'the start screen\'s progress went backwards'
+ : `the bar stood still for ${still}ms (limit ${firstScreen.maxStillMs}ms) — a stage is`
+ + ' reporting nothing for its whole length',
});
console.log(`${ok ? '✓' : '✗'} ${id} ${target} — start screen at ${at ?? 'never'}ms over ${firstScreen.link}`
- + `, first frame at ${boot?.firstFrameMs ?? 'never'}ms`);
+ + `, first frame at ${boot?.firstFrameMs ?? 'never'}ms, still at most ${still}ms`);
}
// The 分包 the host REFUSES. The ordinary launch above already proved the happy