split narrator srt

This commit is contained in:
math-pixel
2026-06-03 01:01:48 +02:00
parent 18fb5e39e9
commit b1037d5107
10 changed files with 289 additions and 15 deletions
@@ -0,0 +1,125 @@
import { useEffect } from "react";
import { useGameStore } from "@/managers/stores/useGameStore";
import { useSubtitleStore } from "@/managers/stores/useSubtitleStore";
import { AudioManager } from "@/managers/AudioManager";
const HISTOIRE_AUDIO_PATH = "/sounds/dialogue/narrateur_histoireelectricienne.mp3";
/**
* Text blocks for the electricienne history narration (max 5 lines each).
* Displayed sequentially — timings are calculated dynamically from the actual
* audio duration so they are always correct regardless of the mp3 length.
*/
const HISTOIRE_BLOCKS = [
"L'électricienne t'a aidé à la Centrale ? Aaaaah c'est ça que j'adore ici, tout le monde s'entraide, personne se juge, une vraie petite famille.",
"Sache que l'électricienne a une histoire assez particulière. Elle est née au nord du continent, dans la ville de Kalska. Elle a grandit heureuse, avec sa mère Edith, son père Jordan et ses deux petits frères Malo et Justin.",
"Il y a quelques années de ça, comme tu le sais, c'est les pays du Nord, qui par grande surprise, ont été obligés de migrer en premier. Ils ont alors entamé leur périple, pays par pays, ville par ville, village par village.",
"Un jour de marche comme les autres depuis plusieurs mois, une tempête climatique les a pris de court. S'étant séparés pour trouver des vivres dans le village, le père et un des deux frères sont malheureusement partis. C'est tragique.",
"Mais un beau jour, ils sont tombés ici, par hasard dans leur périple. On les a accueillis les bras ouverts et ils ont pu se reconstruire doucement parmi nous et font partie intégrante de la communauté aujourd'hui.",
] as const;
const TOTAL_CHARS = HISTOIRE_BLOCKS.reduce((sum, b) => sum + b.length, 0);
/** Compute start/end times for each block based on actual audio duration. */
function buildBlockTimings(
duration: number,
): Array<{ start: number; end: number }> {
let t = 0;
return HISTOIRE_BLOCKS.map((block) => {
const blockDuration = (block.length / TOTAL_CHARS) * duration;
const start = t;
t += blockDuration;
return { start, end: t };
});
}
/**
* Play the histoire audio and keep `useSubtitleStore` in sync with
* dynamically-computed block boundaries.
* Movement is intentionally NOT blocked so the player can explore while
* listening to the narration.
*/
function useHistoireSubtitlePlayback(enabled: boolean): void {
useEffect(() => {
if (!enabled) return undefined;
let isCancelled = false;
const audio = AudioManager.getInstance().playSound(HISTOIRE_AUDIO_PATH, 1, {
category: "dialogue",
});
if (!audio) return undefined;
const { setActiveSubtitle, clearActiveSubtitle } =
useSubtitleStore.getState();
/** Wire up block-level subtitle sync once we know the audio duration. */
function startSync(): void {
const duration = audio.duration;
if (!duration || isNaN(duration) || isCancelled) return;
const timings = buildBlockTimings(duration);
function onTimeUpdate(): void {
const t = audio.currentTime;
const idx = timings.findIndex(
({ start, end }) => t >= start && t < end,
);
if (idx >= 0) {
setActiveSubtitle({
speaker: "Narrateur",
text: HISTOIRE_BLOCKS[idx],
});
}
}
audio.addEventListener("timeupdate", onTimeUpdate);
audio.addEventListener("ended", clearActiveSubtitle, { once: true });
}
// If duration is already known (cached audio), start immediately.
if (audio.duration && !isNaN(audio.duration)) {
startSync();
} else {
audio.addEventListener("loadedmetadata", startSync, { once: true });
}
return () => {
isCancelled = true;
audio.pause();
useSubtitleStore.getState().clearActiveSubtitle();
};
}, [enabled]);
}
/**
* Handles the farm mission narrative intro:
* locked → (auto) → electricienne_history → plays audio with block subtitles
*/
export function FarmNarrativeFlow(): null {
const mainState = useGameStore((state) => state.mainState);
const step = useGameStore((state) => state.farm.currentStep);
const setMissionStep = useGameStore((state) => state.setMissionStep);
// locked is purely a gate — transition immediately to electricienne_history.
useEffect(() => {
if (mainState !== "farm" || step !== "locked") return;
setMissionStep("farm", "electricienne_history");
}, [mainState, step, setMissionStep]);
// Ensure movement is always allowed during the electricienne_history narration,
// regardless of what the previous step may have blocked.
const setCanMove = useGameStore((state) => state.setCanMove);
useEffect(() => {
if (mainState !== "farm" || step !== "electricienne_history") return;
setCanMove(true);
}, [mainState, step, setCanMove]);
useHistoireSubtitlePlayback(
mainState === "farm" && step === "electricienne_history",
);
return null;
}
@@ -19,8 +19,13 @@ export function PylonLightingEffect(): null {
const mainState = useGameStore((state) => state.mainState);
const step = useGameStore((state) => state.pylon.currentStep);
// True from "approaching" until narrator-outro (lighting resets before the outro audio)
const isActive = mainState === "pylon" && step !== "locked" && step !== "narrator-outro";
// True from "approaching" until done — lighting starts reverting as soon as
// the repair is complete (powerup sfx plays at "done", outro dialogue at "narrator-outro").
const isActive =
mainState === "pylon" &&
step !== "locked" &&
step !== "done" &&
step !== "narrator-outro";
// Working THREE.Color instances — lerped every frame
const ambientRef = useRef(new THREE.Color(LIGHTING_STATE.ambientColor));
@@ -1,3 +1,4 @@
import { useEffect } from "react";
import { useGameStore } from "@/managers/stores/useGameStore";
import { useDialoguePlayback } from "@/hooks/gameplay/useDialoguePlayback";
import { ZoneDetection } from "@/components/zone/ZoneDetection";
@@ -5,22 +6,109 @@ import { PylonFarmerNPC } from "@/components/gameplay/pylon/PylonFarmerNPC";
import { PylonNarratorOutro } from "@/components/gameplay/pylon/PylonNarratorOutro";
import { PYLON_APPROACH_ZONE, PYLON_ARRIVED_ZONE } from "@/data/gameplay/zones";
import { PYLON_NARRATIVE_DIALOGUES } from "@/data/gameplay/pylonConfig";
import { AudioManager } from "@/managers/AudioManager";
import { loadDialogueManifest } from "@/utils/dialogues/loadDialogueManifest";
import { playDialogueById } from "@/utils/dialogues/playDialogue";
const PYLON_POWERDOWN_SFX = "/sounds/effect/generateur-powerdown.mp3";
const PYLON_POWERUP_SFX = "/sounds/effect/generateur-powerup.mp3";
export function PylonNarrativeFlow(): React.JSX.Element | null {
const mainState = useGameStore((state) => state.mainState);
const step = useGameStore((state) => state.pylon.currentStep);
const setMissionStep = useGameStore((state) => state.setMissionStep);
const setCanMove = useGameStore((state) => state.setCanMove);
useDialoguePlayback({
enabled: mainState === "pylon" && step === "approaching",
dialogueId: PYLON_NARRATIVE_DIALOGUES.electricOutage,
});
// ── approaching : powerdown sfx → then electricOutage dialogue ────────────
useEffect(() => {
if (mainState !== "pylon" || step !== "approaching") return undefined;
let isCancelled = false;
setCanMove(false);
void (async () => {
// 1. Play the generator powerdown sound effect
const sfx = AudioManager.getInstance().playSound(
PYLON_POWERDOWN_SFX,
1,
{ category: "sfx" },
);
// 2. Wait for it to finish (or skip if it can't load)
if (sfx) {
await new Promise<void>((resolve) => {
sfx.addEventListener("ended", () => resolve(), { once: true });
sfx.addEventListener("error", () => resolve(), { once: true });
});
}
if (isCancelled) return;
// 3. Play the narrative dialogue
const manifest = await loadDialogueManifest();
if (isCancelled || !manifest) {
setCanMove(true);
return;
}
const audio = await playDialogueById(
manifest,
PYLON_NARRATIVE_DIALOGUES.electricOutage,
);
if (isCancelled || !audio) {
setCanMove(true);
return;
}
audio.addEventListener(
"ended",
() => {
setCanMove(true);
},
{ once: true },
);
})();
return () => {
isCancelled = true;
setCanMove(true);
};
}, [mainState, step, setCanMove]);
// ── arrived : searchCentral dialogue (unchanged) ──────────────────────────
useDialoguePlayback({
enabled: mainState === "pylon" && step === "arrived",
dialogueId: PYLON_NARRATIVE_DIALOGUES.searchCentral,
});
// ── done : powerup sfx + lighting revert → auto-transition to narrator-outro
useEffect(() => {
if (mainState !== "pylon" || step !== "done") return undefined;
const sfx = AudioManager.getInstance().playSound(PYLON_POWERUP_SFX, 1, {
category: "sfx",
});
if (sfx) {
sfx.addEventListener(
"ended",
() => setMissionStep("pylon", "narrator-outro"),
{ once: true },
);
sfx.addEventListener(
"error",
() => setMissionStep("pylon", "narrator-outro"),
{ once: true },
);
} else {
// Fallback if the audio can't load
setMissionStep("pylon", "narrator-outro");
}
return undefined;
}, [mainState, step, setMissionStep]);
// narrator-outro audio sequence + completeMission are handled in PylonNarratorOutro
if (mainState !== "pylon") return null;
+1 -1
View File
@@ -170,7 +170,7 @@ export function RepairGame({
onComplete={() => setMissionStep(mission, "done")}
/>
) : null}
{step === "done" ? (
{step === "done" && mission !== "pylon" ? (
<RepairCompletionStep
config={config}
onComplete={() => completeMission(mission)}