perf: préchargement GPU pour supprimer l'à-coup à la première rotation
three.js compilait les shaders et envoyait les textures au GPU au premier affichage de chaque objet. ThreeRenderer.warmUp() prépare tout derrière l'écran de chargement (shaders, textures, un rendu par point de vue). Les lumières pilotées par les props s'éteignent (intensité 0) au lieu d'être masquées, pour ne pas recompiler tous les shaders. Le smoke test échoue désormais si un shader ou une texture est préparé en cours de partie. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01UJ9HPtCegSPg9vCFM1EyfT
This commit is contained in:
parent
5cdceb4ecd
commit
54f5ae5622
|
|
@ -30,3 +30,4 @@ Le dépôt de référence est le dossier de l'utilisateur (`D:\Code\claude\escap
|
||||||
- Si l'enchaînement des énigmes change, mettre à jour `walkthrough.json` dans le même changement.
|
- Si l'enchaînement des énigmes change, mettre à jour `walkthrough.json` dans le même changement.
|
||||||
- Un nouveau type de mini-jeu doit avoir un contrôle dans `tests/scenarios.test.ts` (`checkPuzzle`) et une résolution dans `tests/smoke.cjs`.
|
- Un nouveau type de mini-jeu doit avoir un contrôle dans `tests/scenarios.test.ts` (`checkPuzzle`) et une résolution dans `tests/smoke.cjs`.
|
||||||
- Le jugement visuel final (lumière, ombres, fluidité) revient à l'utilisateur, sur sa machine.
|
- Le jugement visuel final (lumière, ombres, fluidité) revient à l'utilisateur, sur sa machine.
|
||||||
|
- Performance : tout est préparé au chargement par `ThreeRenderer.warmUp()` (shaders, textures, géométries). Une lumière pilotée par les props s'éteint (intensité 0) au lieu d'être masquée, car changer le nombre de lumières recompile tous les shaders. Le smoke test échoue si un shader ou une texture est préparé en cours de partie.
|
||||||
|
|
|
||||||
|
|
@ -55,7 +55,7 @@ Cinq énigmes enchaînées, pour 15 à 20 minutes de jeu. Attention, la solution
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `npm test` | ~1 s | Moteur et scénarios sans navigateur : références, cohérence logique, paramètres des mini-jeux, et la solution de référence (`walkthrough.json`) rejouée jusqu'à la victoire |
|
| `npm test` | ~1 s | Moteur et scénarios sans navigateur : références, cohérence logique, paramètres des mini-jeux, et la solution de référence (`walkthrough.json`) rejouée jusqu'à la victoire |
|
||||||
| `npm run check` | ~5 s | Typage + `npm test` + build |
|
| `npm run check` | ~5 s | Typage + `npm test` + build |
|
||||||
| `npm run smoke` | ~1 min | Rejoue la solution avec de vrais clics dans le jeu 3D construit (mode `?test=1`) : objets 3D introuvables, zones masquées, erreurs console, écran de victoire |
|
| `npm run smoke` | ~1 min | Rejoue la solution avec de vrais clics dans le jeu 3D construit (mode `?test=1`) : objets 3D introuvables, zones masquées, erreurs console, écran de victoire, et aucun shader ni texture préparé en cours de partie (sinon, à-coups) |
|
||||||
|
|
||||||
Options du smoke test : `npm run smoke -- --shots` (une capture par scène dans `tests/shots/`), `--hard`, `--chapter chapitre1`, `--headed`. Il a besoin de Playwright (`npm i -D playwright && npx playwright install chromium`).
|
Options du smoke test : `npm run smoke -- --shots` (une capture par scène dans `tests/shots/`), `--hard`, `--chapter chapitre1`, `--headed`. Il a besoin de Playwright (`npm i -D playwright && npx playwright install chromium`).
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,8 @@ interface PropEntry {
|
||||||
basePos: THREE.Vector3;
|
basePos: THREE.Vector3;
|
||||||
baseQuat: THREE.Quaternion;
|
baseQuat: THREE.Quaternion;
|
||||||
baseVisible: boolean;
|
baseVisible: boolean;
|
||||||
|
/** Lumière : on ne la masque jamais (changer le nombre de lumières recompile tous les shaders), on l'éteint. */
|
||||||
|
light?: { obj: THREE.Light; intensity: number };
|
||||||
mats: { mat: THREE.MeshStandardMaterial; color: THREE.Color; emissive: THREE.Color; intensity: number }[];
|
mats: { mat: THREE.MeshStandardMaterial; color: THREE.Color; emissive: THREE.Color; intensity: number }[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -70,6 +72,8 @@ export class ThreeRenderer extends BaseRenderer {
|
||||||
private downAt: [number, number] = [0, 0];
|
private downAt: [number, number] = [0, 0];
|
||||||
private debugHit = '';
|
private debugHit = '';
|
||||||
private loadingEl: HTMLElement;
|
private loadingEl: HTMLElement;
|
||||||
|
/** Préchargement GPU en cours (écran de chargement affiché). */
|
||||||
|
private warming = true;
|
||||||
/** Rendu à la demande : on ne redessine que si quelque chose a changé. */
|
/** Rendu à la demande : on ne redessine que si quelque chose a changé. */
|
||||||
private dirty = true;
|
private dirty = true;
|
||||||
private hoveredObj: THREE.Object3D | null = null;
|
private hoveredObj: THREE.Object3D | null = null;
|
||||||
|
|
@ -125,6 +129,7 @@ export class ThreeRenderer extends BaseRenderer {
|
||||||
this.composer.addPass(new OutputPass());
|
this.composer.addPass(new OutputPass());
|
||||||
|
|
||||||
this.indexWorld();
|
this.indexWorld();
|
||||||
|
void this.warmUp();
|
||||||
this.raycaster.layers.enable(PICK_LAYER);
|
this.raycaster.layers.enable(PICK_LAYER);
|
||||||
|
|
||||||
const canvas = this.gl.domElement;
|
const canvas = this.gl.domElement;
|
||||||
|
|
@ -179,7 +184,8 @@ export class ThreeRenderer extends BaseRenderer {
|
||||||
if (sm.emissive) mats.push({ mat: sm, color: sm.color.clone(), emissive: sm.emissive.clone(), intensity: sm.emissiveIntensity });
|
if (sm.emissive) mats.push({ mat: sm, color: sm.color.clone(), emissive: sm.emissive.clone(), intensity: sm.emissiveIntensity });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
this.props.set(rule.object, { obj, basePos: obj.position.clone(), baseQuat: obj.quaternion.clone(), baseVisible: obj.visible, mats });
|
const light = (obj as THREE.Light).isLight ? { obj: obj as THREE.Light, intensity: (obj as THREE.Light).intensity } : undefined;
|
||||||
|
this.props.set(rule.object, { obj, basePos: obj.position.clone(), baseQuat: obj.quaternion.clone(), baseVisible: obj.visible, mats, light });
|
||||||
}
|
}
|
||||||
for (const scene of scenario.scenes)
|
for (const scene of scenario.scenes)
|
||||||
for (const hs of scene.hotspots)
|
for (const hs of scene.hotspots)
|
||||||
|
|
@ -238,12 +244,79 @@ export class ThreeRenderer extends BaseRenderer {
|
||||||
}
|
}
|
||||||
|
|
||||||
protected canInteract(): boolean {
|
protected canInteract(): boolean {
|
||||||
return !this.camAnim;
|
return !this.camAnim && !this.warming;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Vrai pendant un mouvement de caméra ou d'objet (utile aux tests). */
|
/** Vrai pendant le préchargement ou un mouvement de caméra/d'objet (utile aux tests). */
|
||||||
get busy(): boolean {
|
get busy(): boolean {
|
||||||
return !!this.camAnim || this.tweens.length > 0;
|
return this.warming || !!this.camAnim || this.tweens.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Statistiques GPU (tests de performance : aucune compilation de shader ne doit survenir en jeu). */
|
||||||
|
renderStats(): { programs: number; textures: number; geometries: number } {
|
||||||
|
return { programs: this.gl.info.programs?.length ?? 0, textures: this.gl.info.memory.textures, geometries: this.gl.info.memory.geometries };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Préchargement GPU, derrière l'écran « Chargement de la pièce… ».
|
||||||
|
* Sans lui, three.js compile les shaders et envoie textures et géométries
|
||||||
|
* au GPU au premier affichage de chaque objet : d'où un gros à-coup la
|
||||||
|
* première fois qu'on se tourne vers un mur.
|
||||||
|
*/
|
||||||
|
private async warmUp(): Promise<void> {
|
||||||
|
const t0 = performance.now();
|
||||||
|
// Tous les objets visibles le temps du préchargement (y compris ceux encore cachés : clé, message UV...).
|
||||||
|
const hidden: THREE.Object3D[] = [];
|
||||||
|
const showAll = () =>
|
||||||
|
this.world.root.traverse((o) => {
|
||||||
|
if (!o.visible) {
|
||||||
|
hidden.push(o);
|
||||||
|
o.visible = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const restore = () => {
|
||||||
|
hidden.forEach((o) => (o.visible = false));
|
||||||
|
hidden.length = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. Compilation de tous les shaders (en parallèle si le pilote le permet)
|
||||||
|
showAll();
|
||||||
|
if (this.gl.extensions.has('KHR_parallel_shader_compile')) await this.gl.compileAsync(this.scene3d, this.camera);
|
||||||
|
else this.gl.compile(this.scene3d, this.camera);
|
||||||
|
restore();
|
||||||
|
|
||||||
|
// 2. Envoi de toutes les textures au GPU
|
||||||
|
const textures = new Set<THREE.Texture>();
|
||||||
|
this.world.root.traverse((o) => {
|
||||||
|
const mesh = o as THREE.Mesh;
|
||||||
|
if (!mesh.isMesh) return;
|
||||||
|
for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
|
||||||
|
for (const v of Object.values(m)) if ((v as THREE.Texture)?.isTexture) textures.add(v as THREE.Texture);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
textures.forEach((t) => this.gl.initTexture(t));
|
||||||
|
|
||||||
|
// 3. Un rendu complet depuis chaque point de vue (géométries, ombres, passes de post-traitement)
|
||||||
|
showAll();
|
||||||
|
const saved = { pos: this.camera.position.clone(), quat: this.camera.quaternion.clone(), fov: this.camera.fov };
|
||||||
|
const firstHotspotObj = this.world.root.getObjectByName('desk') ?? null;
|
||||||
|
for (const scene of this.engine.scenario.scenes) {
|
||||||
|
this.applyPose(this.poseOf(scene.camera));
|
||||||
|
// Le contour (OutlinePass) a ses propres shaders : on le déclenche une fois.
|
||||||
|
this.outline.selectedObjects = firstHotspotObj ? [firstHotspotObj] : [];
|
||||||
|
this.composer.render(0);
|
||||||
|
await new Promise((r) => requestAnimationFrame(r));
|
||||||
|
}
|
||||||
|
this.outline.selectedObjects = [];
|
||||||
|
restore();
|
||||||
|
this.applyPose(saved);
|
||||||
|
|
||||||
|
this.warming = false;
|
||||||
|
this.refresh(true);
|
||||||
|
this.dirty = true;
|
||||||
|
this.loadingEl.classList.add('done');
|
||||||
|
window.setTimeout(() => this.loadingEl.remove(), 700);
|
||||||
|
console.info(`[escape] préchargement GPU : ${Math.round(performance.now() - t0)} ms, ${textures.size} textures, ${this.renderStats().programs} shaders`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- État du monde ------------------------------------------------------------------------
|
// --- État du monde ------------------------------------------------------------------------
|
||||||
|
|
@ -275,7 +348,10 @@ export class ThreeRenderer extends BaseRenderer {
|
||||||
quat.multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(...rule.spin.axis).normalize(), angle));
|
quat.multiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(...rule.spin.axis).normalize(), angle));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
p.obj.visible = visible;
|
if (p.light) {
|
||||||
|
p.light.obj.visible = true;
|
||||||
|
p.light.obj.intensity = visible ? p.light.intensity : 0;
|
||||||
|
} else p.obj.visible = visible;
|
||||||
for (const m of p.mats) {
|
for (const m of p.mats) {
|
||||||
if (emissive) {
|
if (emissive) {
|
||||||
m.mat.emissive.set(emissive);
|
m.mat.emissive.set(emissive);
|
||||||
|
|
@ -478,9 +554,5 @@ export class ThreeRenderer extends BaseRenderer {
|
||||||
this.dirty = false;
|
this.dirty = false;
|
||||||
this.composer.render(dt);
|
this.composer.render(dt);
|
||||||
|
|
||||||
if (!this.loadingEl.classList.contains('done')) {
|
|
||||||
this.loadingEl.classList.add('done');
|
|
||||||
window.setTimeout(() => this.loadingEl.remove(), 700);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -128,6 +128,7 @@ function check(state, c) {
|
||||||
await page.click(`.chapter[data-chapter="${chapter}"] button[data-difficulty="${difficulty}"]`);
|
await page.click(`.chapter[data-chapter="${chapter}"] button[data-difficulty="${difficulty}"]`);
|
||||||
await idle();
|
await idle();
|
||||||
await shot('00-depart');
|
await shot('00-depart');
|
||||||
|
const statsStart = await page.evaluate(() => window.__escape.renderer.renderStats());
|
||||||
|
|
||||||
for (const [i, step] of wt.steps.entries()) {
|
for (const [i, step] of wt.steps.entries()) {
|
||||||
const label = `étape ${String(i + 1).padStart(2)} ${JSON.stringify(step)}`;
|
const label = `étape ${String(i + 1).padStart(2)} ${JSON.stringify(step)}`;
|
||||||
|
|
@ -170,6 +171,13 @@ function check(state, c) {
|
||||||
}
|
}
|
||||||
|
|
||||||
await page.waitForSelector('.screen.win', { timeout: 5000 });
|
await page.waitForSelector('.screen.win', { timeout: 5000 });
|
||||||
|
// Performance : tout doit avoir été préparé au chargement. Une compilation de shader
|
||||||
|
// en cours de partie provoque un à-coup visible (ex. première rotation vers un mur).
|
||||||
|
const statsEnd = await page.evaluate(() => window.__escape.renderer.renderStats());
|
||||||
|
console.log(` GPU : ${statsStart.programs} shaders et ${statsStart.textures} textures au départ, ${statsEnd.programs} et ${statsEnd.textures} à la fin`);
|
||||||
|
if (statsEnd.programs > statsStart.programs)
|
||||||
|
problems.push(`${statsEnd.programs - statsStart.programs} shader(s) compilé(s) en cours de partie : à-coup probable, à précharger dans ThreeRenderer.warmUp()`);
|
||||||
|
if (statsEnd.textures > statsStart.textures) problems.push(`${statsEnd.textures - statsStart.textures} texture(s) envoyée(s) au GPU en cours de partie`);
|
||||||
await shot('99-victoire');
|
await shot('99-victoire');
|
||||||
if (problems.length) throw new Error(`problèmes détectés pendant la partie :\n ${problems.join('\n ')}`);
|
if (problems.length) throw new Error(`problèmes détectés pendant la partie :\n ${problems.join('\n ')}`);
|
||||||
console.log(`✔ ${chapter} : victoire en ${((Date.now() - t0) / 1000).toFixed(1)} s`);
|
console.log(`✔ ${chapter} : victoire en ${((Date.now() - t0) / 1000).toFixed(1)} s`);
|
||||||
|
|
@ -179,7 +187,7 @@ function check(state, c) {
|
||||||
const file = path.join(SHOTS, `${chapter}-ECHEC.png`);
|
const file = path.join(SHOTS, `${chapter}-ECHEC.png`);
|
||||||
await page.screenshot({ path: file }).catch(() => undefined);
|
await page.screenshot({ path: file }).catch(() => undefined);
|
||||||
console.error(`✘ ${chapter} : ${e.message}`);
|
console.error(`✘ ${chapter} : ${e.message}`);
|
||||||
if (problems.length) console.error(` ${problems.join('\n ')}`);
|
if (problems.length && !e.message.startsWith('problèmes détectés')) console.error(` ${problems.join('\n ')}`);
|
||||||
console.error(` capture : ${path.relative(ROOT, file)}`);
|
console.error(` capture : ${path.relative(ROOT, file)}`);
|
||||||
}
|
}
|
||||||
await page.close();
|
await page.close();
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue