escape_game/src/engine/BaseRenderer.ts

499 lines
19 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { isMuted, playSound, setMuted } from './audio';
import { cursorCss } from './cursors';
import type { Engine, MessageKind, Transition, View } from './Engine';
import type { Clue, CursorKind, Hotspot, Item, PuzzleDef, Scene } from './types';
import { getPuzzleFactory, type PuzzleContext, type PuzzleInstance } from '../puzzles/registry';
export interface RendererOptions {
/** Résout un chemin d'image du scénario ("images/key.svg") en URL utilisable. */
resolveImage(path: string): string;
onWin(): void;
onMenu(): void;
}
export function el<K extends keyof HTMLElementTagNameMap>(tag: K, className?: string, parent?: HTMLElement): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
if (className) e.className = className;
parent?.appendChild(e);
return e;
}
/** Flèche visible à l'écran pour les bandes de navigation. */
const ARROWS: Record<string, string> = {
__left: 'M20 12H5M11 5l-7 7 7 7',
__right: 'M4 12h15M13 5l7 7-7 7',
__back: 'M12 4v15M5 13l7 7 7-7',
};
function navArrow(id: string): HTMLElement {
const span = el('span', 'nav-arrow');
span.innerHTML = `<svg viewBox="0 0 24 24" aria-hidden="true"><path d="${ARROWS[id] ?? ''}" fill="none" stroke="currentColor" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></svg>`;
return span;
}
export function formatTime(ms: number): string {
const s = Math.floor(ms / 1000);
return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}`;
}
/**
* Interface commune autour du rendu : cadre 16:9, HUD et inventaire, messages,
* infobulles, mini-jeux, zones écran (navigation), clavier et mode debug.
* La sous-classe (ThreeRenderer) fournit le contenu de la scène.
*/
export abstract class BaseRenderer implements View {
readonly root: HTMLElement;
protected stage: HTMLElement;
protected sceneLayer: HTMLElement;
protected hotspotsEl: HTMLElement;
protected debugEl: HTMLElement;
protected debug = false;
private messageEl: HTMLElement;
private messageText: HTMLElement;
private toastEl: HTMLElement;
private uvHaloEl: HTMLElement;
private notebookBtn: HTMLButtonElement;
private notebookEl: HTMLElement | null = null;
/** Dernier objet obtenu : sa case clignote dans l'inventaire. */
private freshItem: string | null = null;
private tooltipEl: HTMLElement;
private puzzleLayer: HTMLElement;
private inventoryEl: HTMLElement;
private timerEl: HTMLElement;
private heldEl: HTMLElement;
private soundBtn: HTMLButtonElement;
private messageTimer: number | undefined;
private clockTimer: number | undefined;
private puzzle: PuzzleInstance | null = null;
private dragStart: [number, number] | null = null;
private dragBox: HTMLElement | null = null;
private onMouseUpBound = (e: MouseEvent) => this.onDebugMouseUp(e);
constructor(
protected engine: Engine,
protected opts: RendererOptions,
) {
const [w, h] = engine.scenario.resolution;
this.root = el('div', 'game');
this.root.style.setProperty('--ratio', String(w / h));
const wrap = el('div', 'stage-wrap', this.root);
this.stage = el('div', 'stage', wrap);
this.sceneLayer = el('div', 'scenes', this.stage);
this.hotspotsEl = el('div', 'hotspots', this.stage);
this.messageEl = el('div', 'message', this.stage);
this.messageText = el('span', 'message-text', this.messageEl);
this.toastEl = el('div', 'item-toast', this.stage);
this.uvHaloEl = el('div', 'uv-halo', this.stage);
this.tooltipEl = el('div', 'tooltip', this.stage);
this.puzzleLayer = el('div', 'puzzle-layer', this.stage);
this.debugEl = el('div', 'debug-info', this.stage);
const hud = el('div', 'hud', this.root);
this.inventoryEl = el('div', 'inventory', hud);
const right = el('div', 'hud-right', hud);
this.timerEl = el('div', 'timer', right);
this.notebookBtn = el('button', 'hud-btn notebook-btn', right);
this.notebookBtn.title = 'Carnet d’indices (C)';
this.notebookBtn.onclick = () => this.toggleNotebook();
const hintBtn = el('button', 'hud-btn', right);
hintBtn.innerHTML = '<span>?</span> Indice';
hintBtn.title = 'Obtenir un indice (H)';
hintBtn.onclick = () => engine.nextHint();
this.soundBtn = el('button', 'hud-btn', right);
this.soundBtn.onclick = () => {
setMuted(!isMuted());
this.updateSoundBtn();
};
this.updateSoundBtn();
const menuBtn = el('button', 'hud-btn', right);
menuBtn.textContent = 'Menu';
menuBtn.onclick = () => opts.onMenu();
this.heldEl = el('div', 'held-item', this.root);
// Le message en cours se ferme au clic suivant, n'importe où dans la scène.
this.stage.addEventListener(
'pointerdown',
(e) => {
if ((e.target as HTMLElement).closest('.message button')) return;
this.hideMessage();
},
true,
);
this.stage.addEventListener('contextmenu', (e) => {
e.preventDefault();
if (this.puzzle) return;
const hs = this.canInteract() ? this.hotspotAt(e) : null;
if (hs && engine.rightClick(hs)) return;
engine.goBack();
});
this.root.addEventListener('mousemove', (e) => this.onMouseMove(e));
this.stage.addEventListener('mousedown', (e) => this.onDebugMouseDown(e));
window.addEventListener('mouseup', this.onMouseUpBound);
window.addEventListener('keydown', this.onKey);
this.clockTimer = window.setInterval(() => (this.timerEl.textContent = formatTime(engine.state.elapsedMs)), 500);
}
// --- À fournir par le rendu ---------------------------------------------------------
abstract showScene(scene: Scene, transition: Transition): void;
/** Met à jour le contenu de la scène selon l'état (calques, objets 3D...). */
protected abstract refreshStage(instant: boolean): void;
/** Touche supplémentaire (mode debug notamment). */
/** Zone sous le pointeur (rendus 3D) ; null par défaut. */
protected hotspotAt(_e: MouseEvent): Hotspot | null {
return null;
}
protected onExtraKey(_e: KeyboardEvent): void {}
protected onDebugChanged(): void {}
/** Texte additionnel affiché dans la barre de debug. */
protected debugExtra(): string {
return '';
}
destroy(): void {
window.removeEventListener('keydown', this.onKey);
window.removeEventListener('mouseup', this.onMouseUpBound);
window.clearInterval(this.clockTimer);
window.clearTimeout(this.messageTimer);
this.puzzle?.destroy?.();
this.root.remove();
}
protected get puzzleOpen(): boolean {
return this.puzzle !== null;
}
private onKey = (e: KeyboardEvent): void => {
if (e.key === 'Escape') {
if (this.notebookEl) this.toggleNotebook(false);
else if (this.puzzle) this.closePuzzle();
else if (this.messageEl.classList.contains('visible')) this.hideMessage();
else this.engine.goBack();
} else if ((e.key === 'c' || e.key === 'C') && !this.debug) {
this.toggleNotebook();
} else if (e.key === 'h' || e.key === 'H') {
this.engine.nextHint();
} else if (e.key === 'd' || e.key === 'D') {
this.debug = !this.debug;
this.stage.classList.toggle('debug', this.debug);
this.onDebugChanged();
this.refresh();
} else {
this.onExtraKey(e);
}
};
private updateSoundBtn(): void {
this.soundBtn.textContent = isMuted() ? 'Son : off' : 'Son : on';
}
// --- Rafraîchissement -----------------------------------------------------------------
refresh(instant = false): void {
this.refreshStage(instant);
this.renderRectHotspots();
this.renderInventory();
const n = this.engine.state.notebook.length;
this.notebookBtn.innerHTML = `Carnet${n ? ` <b>${n}</b>` : ''}`;
if (this.notebookEl) this.renderNotebook();
}
/** Zones écran (rect) : flèches de navigation et zones écran éventuelles. */
private renderRectHotspots(): void {
const scene = this.engine.currentScene;
const [w, h] = this.engine.scenario.resolution;
this.hotspotsEl.replaceChildren();
for (const hs of this.engine.activeHotspots(scene)) {
if (!hs.rect) continue;
const isNav = hs.id.startsWith('__');
const zone = el('div', `hotspot${isNav ? ' nav' : ''}`, this.hotspotsEl);
const [x, y, rw, rh] = hs.rect;
Object.assign(zone.style, {
left: `${(x / w) * 100}%`,
top: `${(y / h) * 100}%`,
width: `${(rw / w) * 100}%`,
height: `${(rh / h) * 100}%`,
cursor: this.cursorFor(hs),
});
zone.dataset.id = hs.id;
if (this.debug) zone.dataset.debug = hs.id;
if (isNav) zone.appendChild(navArrow(hs.id));
zone.addEventListener('click', (e) => {
e.stopPropagation();
if (this.dragBox || !this.canInteract()) return;
this.engine.click(hs);
});
zone.addEventListener('mouseenter', (e) => {
this.showTooltip(hs);
this.onMouseMove(e);
});
zone.addEventListener('mouseleave', () => this.hideTooltip());
}
}
/** Une sous-classe peut bloquer les clics (ex. caméra en mouvement). */
protected canInteract(): boolean {
return true;
}
protected cursorFor(hs: Hotspot): string {
const isNav = hs.id.startsWith('__');
// En Difficile, aucun indice visuel sur les objets : au joueur de tester.
if (!isNav && this.engine.state.difficulty === 'hard') return 'default';
if (this.engine.state.selected && !isNav) return cursorCss('use');
let kind: CursorKind = 'look';
if (hs.cursor) kind = hs.cursor;
else {
const first = hs.interactions[hs.interactions.length - 1]?.do[0];
if (first && ('goto' in first || 'puzzle' in first)) kind = 'zoom';
else if (hs.interactions.some((i) => i.do.some((a) => 'give' in a))) kind = 'take';
}
return cursorCss(kind);
}
protected showTooltip(hs: Hotspot): void {
// En Difficile, pas d'infobulle sur les objets (seulement sur la navigation).
if (this.engine.state.difficulty === 'hard' && !hs.id.startsWith('__')) return this.hideTooltip();
const sel = this.engine.state.selected;
const label = sel && hs.label && !hs.id.startsWith('__') ? `Utiliser ${this.engine.getItem(sel)?.name ?? ''} sur : ${hs.label}` : hs.label;
if (!label) return this.hideTooltip();
this.tooltipEl.textContent = label;
this.tooltipEl.classList.add('visible');
}
protected hideTooltip(): void {
this.tooltipEl.classList.remove('visible');
}
// --- Inventaire -------------------------------------------------------------------
private renderInventory(): void {
const state = this.engine.state;
this.inventoryEl.replaceChildren();
const SLOTS = 6;
for (let i = 0; i < SLOTS; i++) {
const slot = el('button', 'slot', this.inventoryEl);
const id = state.inventory[i];
if (!id) {
slot.disabled = true;
continue;
}
const item = this.engine.getItem(id);
const img = el('img', '', slot);
img.src = item ? this.opts.resolveImage(item.icon) : '';
img.alt = item?.name ?? id;
img.draggable = false;
slot.title = item ? `${item.name}${item.description ? ' — ' + item.description : ''}` : id;
slot.dataset.item = id;
slot.classList.toggle('selected', state.selected === id);
if (id === this.freshItem) slot.classList.add('fresh');
slot.onclick = () => {
const sel = this.engine.state.selected;
if (sel && sel !== id) this.engine.combine(sel, id);
else this.engine.selectItem(id);
};
}
const uv = this.engine.scenario.uvLight;
this.uvHaloEl.classList.toggle('visible', !!uv && state.selected === uv.item);
const held = state.selected ? this.engine.getItem(state.selected) : undefined;
if (held) {
this.heldEl.style.backgroundImage = `url("${this.opts.resolveImage(held.icon)}")`;
this.heldEl.classList.add('visible');
} else {
this.heldEl.classList.remove('visible');
}
}
// --- Messages ---------------------------------------------------------------------
showMessage(text: string, kind: MessageKind): void {
window.clearTimeout(this.messageTimer);
this.messageEl.className = `message visible ${kind}`;
this.messageText.textContent = text;
this.messageEl.querySelector('.clue-btn')?.remove();
if (kind === 'hint') playSound('beep');
// Fermeture automatique (le clic suivant le ferme aussi).
this.messageTimer = window.setTimeout(() => this.hideMessage(), Math.max(5000, text.length * 70));
}
protected hideMessage(): void {
window.clearTimeout(this.messageTimer);
this.messageEl.classList.remove('visible');
}
/** Bouton « Noter dans le carnet » sous le message courant. */
offerClue(clue: Clue): void {
this.messageEl.querySelector('.clue-btn')?.remove();
const btn = el('button', 'clue-btn', this.messageEl);
btn.textContent = 'Noter dans le carnet';
btn.title = clue.text;
btn.onclick = (e) => {
e.stopPropagation();
this.engine.noteClue(clue.id);
btn.textContent = 'Noté ✓';
btn.disabled = true;
this.notebookBtn.classList.remove('pulse');
void this.notebookBtn.offsetWidth;
this.notebookBtn.classList.add('pulse');
window.setTimeout(() => this.hideMessage(), 700);
};
// Laisse le temps de cliquer : la fermeture automatique est repoussée.
window.clearTimeout(this.messageTimer);
this.messageTimer = window.setTimeout(() => this.hideMessage(), 9000);
}
/** Annonce centrale « Objet obtenu » + case de l'inventaire qui clignote. */
itemGained(item: Item): void {
this.toastEl.innerHTML = '';
const img = el('img', '', this.toastEl);
img.src = this.opts.resolveImage(item.icon);
img.alt = '';
el('div', 'item-toast-label', this.toastEl).textContent = 'Objet obtenu';
el('div', 'item-toast-name', this.toastEl).textContent = item.name;
this.toastEl.classList.remove('show');
void this.toastEl.offsetWidth;
this.toastEl.classList.add('show');
this.freshItem = item.id;
window.setTimeout(() => {
if (this.freshItem === item.id) this.freshItem = null;
}, 2600);
}
// --- Carnet ----------------------------------------------------------------------
private toggleNotebook(open = !this.notebookEl): void {
if (!open) {
this.notebookEl?.remove();
this.notebookEl = null;
return;
}
if (this.notebookEl) return;
this.hideTooltip();
const overlay = el('div', 'puzzle-overlay visible notebook-overlay', this.puzzleLayer);
overlay.addEventListener('click', (e) => {
if (e.target === overlay) this.toggleNotebook(false);
});
this.notebookEl = overlay;
this.renderNotebook();
}
private renderNotebook(): void {
if (!this.notebookEl) return;
const ids = this.engine.state.notebook;
this.notebookEl.innerHTML = '';
const book = el('div', 'notebook', this.notebookEl);
const close = el('button', 'puzzle-close', book);
close.textContent = '×';
close.title = 'Fermer (Échap)';
close.onclick = () => this.toggleNotebook(false);
el('h3', '', book).textContent = 'Carnet';
if (!ids.length) {
el('p', 'notebook-empty', book).textContent = 'Aucune note pour l’instant. Quand vous découvrez un indice, choisissez « Noter dans le carnet ».';
return;
}
const list = el('ol', '', book);
for (const id of ids) el('li', '', list).textContent = this.engine.getClue(id)?.text ?? id;
}
// --- Puzzles ------------------------------------------------------------------------
openPuzzle(def: PuzzleDef, ctx: PuzzleContext): void {
this.closePuzzle();
const overlay = el('div', 'puzzle-overlay', this.puzzleLayer);
overlay.addEventListener('click', (e) => {
if (e.target === overlay) this.closePuzzle();
});
const box = el('div', 'puzzle-box', overlay);
if (def.title) el('div', 'puzzle-title', box).textContent = def.title;
const close = el('button', 'puzzle-close', box);
close.textContent = '×';
close.title = 'Fermer (Échap)';
close.onclick = () => this.closePuzzle();
const instance = getPuzzleFactory(def.type)(ctx);
box.appendChild(instance.el);
this.puzzle = { el: overlay, destroy: instance.destroy };
this.hideTooltip();
requestAnimationFrame(() => overlay.classList.add('visible'));
}
closePuzzle(): void {
if (!this.puzzle) return;
this.puzzle.destroy?.();
this.puzzle.el.remove();
this.puzzle = null;
}
showWin(): void {
this.closePuzzle();
this.hideMessage();
this.hideTooltip();
this.opts.onWin();
}
// --- Souris : objet tenu, infobulle, outil de debug ------------------------------
protected toImageCoords(e: MouseEvent): [number, number] {
const r = this.stage.getBoundingClientRect();
const [w, h] = this.engine.scenario.resolution;
return [Math.round(((e.clientX - r.left) / r.width) * w), Math.round(((e.clientY - r.top) / r.height) * h)];
}
protected onMouseMove(e: MouseEvent): void {
this.heldEl.style.transform = `translate(${e.clientX + 14}px, ${e.clientY + 14}px)`;
const r = this.stage.getBoundingClientRect();
this.uvHaloEl.style.transform = `translate(${e.clientX - r.left}px, ${e.clientY - r.top}px) translate(-50%, -50%)`;
// Décalage plus grand quand un objet est tenu, pour ne pas masquer son icône.
const dy = this.engine.state.selected ? 62 : 22;
const tx = Math.min(e.clientX - r.left + 18, r.width - this.tooltipEl.offsetWidth - 8);
this.tooltipEl.style.transform = `translate(${tx}px, ${e.clientY - r.top + dy}px)`;
if (this.debug) {
const [x, y] = this.toImageCoords(e);
const extra = this.debugExtra();
this.debugEl.textContent = `DEBUG · scène "${this.engine.currentScene.id}" · écran x=${x} y=${y}${extra ? ' · ' + extra : ''}`;
if (this.dragStart && this.dragBox) {
const [sx, sy] = this.dragStart;
const [w, h] = this.engine.scenario.resolution;
Object.assign(this.dragBox.style, {
left: `${(Math.min(sx, x) / w) * 100}%`,
top: `${(Math.min(sy, y) / h) * 100}%`,
width: `${(Math.abs(x - sx) / w) * 100}%`,
height: `${(Math.abs(y - sy) / h) * 100}%`,
});
}
}
}
/** Mode debug (touche D) : Maj+glisser trace une zone et copie son "rect" JSON. */
private onDebugMouseDown(e: MouseEvent): void {
if (!this.debug || !e.shiftKey || e.button !== 0) return;
e.preventDefault();
e.stopPropagation();
this.dragStart = this.toImageCoords(e);
this.dragBox = el('div', 'drag-box', this.stage);
}
private onDebugMouseUp(e: MouseEvent): void {
if (!this.dragStart || !this.dragBox) return;
const [sx, sy] = this.dragStart;
const [x, y] = this.toImageCoords(e);
const rect = `"rect": [${Math.min(sx, x)}, ${Math.min(sy, y)}, ${Math.abs(x - sx)}, ${Math.abs(y - sy)}]`;
this.copyToClipboard(rect);
const box = this.dragBox;
this.dragStart = null;
window.setTimeout(() => {
box.remove();
this.dragBox = null;
}, 1200);
}
protected copyToClipboard(text: string): void {
console.info(text);
navigator.clipboard?.writeText(text).catch(() => undefined);
this.showMessage(`${text} (copié)`, 'info');
}
}