Load files from manifest for caching

This commit is contained in:
Flashfyre 2024-04-23 22:00:23 -04:00
parent e608cb6738
commit ba71d2750b
11 changed files with 77 additions and 46 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 31 KiB

View File

@ -271,7 +271,7 @@ export default class BattleScene extends SceneBase {
populateAnims(); populateAnims();
await fetch('./images/pokemon/variant/_masterlist.json').then(res => res.json()).then(v => Object.keys(v).forEach(k => variantData[k] = v[k])); await this.cachedFetch('./images/pokemon/variant/_masterlist.json').then(res => res.json()).then(v => Object.keys(v).forEach(k => variantData[k] = v[k]));
} }
create() { create() {
@ -468,8 +468,8 @@ export default class BattleScene extends SceneBase {
Promise.all([ Promise.all([
Promise.all(loadPokemonAssets), Promise.all(loadPokemonAssets),
initCommonAnims().then(() => loadCommonAnimAssets(this, true)), initCommonAnims(this).then(() => loadCommonAnimAssets(this, true)),
Promise.all([ Moves.TACKLE, Moves.TAIL_WHIP, Moves.FOCUS_ENERGY, Moves.STRUGGLE ].map(m => initMoveAnim(m))).then(() => loadMoveAnimAssets(this, defaultMoves, true)), Promise.all([ Moves.TACKLE, Moves.TAIL_WHIP, Moves.FOCUS_ENERGY, Moves.STRUGGLE ].map(m => initMoveAnim(this, m))).then(() => loadMoveAnimAssets(this, defaultMoves, true)),
this.initStarterColors() this.initStarterColors()
]).then(() => { ]).then(() => {
this.pushPhase(new LoginPhase(this)); this.pushPhase(new LoginPhase(this));
@ -505,19 +505,29 @@ export default class BattleScene extends SceneBase {
async initExpSprites(): Promise<void> { async initExpSprites(): Promise<void> {
if (expSpriteKeys.length) if (expSpriteKeys.length)
return; return;
fetch('./exp-sprites.json').then(res => res.json()).then(keys => { this.cachedFetch('./exp-sprites.json').then(res => res.json()).then(keys => {
if (Array.isArray(keys)) if (Array.isArray(keys))
expSpriteKeys.push(...keys); expSpriteKeys.push(...keys);
Promise.resolve(); Promise.resolve();
}); });
} }
cachedFetch(url: string, init?: RequestInit): Promise<Response> {
const manifest = this.game['manifest'];
if (manifest) {
const timestamp = manifest[`/${url.replace('./', '')}`];
if (timestamp)
url += `?t=${timestamp}`;
}
return fetch(url, init);
}
initStarterColors(): Promise<void> { initStarterColors(): Promise<void> {
return new Promise(resolve => { return new Promise(resolve => {
if (starterColors) if (starterColors)
return resolve(); return resolve();
fetch('./starter-colors.json').then(res => res.json()).then(sc => { this.cachedFetch('./starter-colors.json').then(res => res.json()).then(sc => {
starterColors = {}; starterColors = {};
Object.keys(sc).forEach(key => { Object.keys(sc).forEach(key => {
starterColors[key] = sc[key]; starterColors[key] = sc[key];

View File

@ -424,14 +424,14 @@ export const moveAnims = new Map<Moves, AnimConfig | [AnimConfig, AnimConfig]>()
export const chargeAnims = new Map<ChargeAnim, AnimConfig | [AnimConfig, AnimConfig]>(); export const chargeAnims = new Map<ChargeAnim, AnimConfig | [AnimConfig, AnimConfig]>();
export const commonAnims = new Map<CommonAnim, AnimConfig>(); export const commonAnims = new Map<CommonAnim, AnimConfig>();
export function initCommonAnims(): Promise<void> { export function initCommonAnims(scene: BattleScene): Promise<void> {
return new Promise(resolve => { return new Promise(resolve => {
const commonAnimNames = Utils.getEnumKeys(CommonAnim); const commonAnimNames = Utils.getEnumKeys(CommonAnim);
const commonAnimIds = Utils.getEnumValues(CommonAnim); const commonAnimIds = Utils.getEnumValues(CommonAnim);
const commonAnimFetches = []; const commonAnimFetches = [];
for (let ca = 0; ca < commonAnimIds.length; ca++) { for (let ca = 0; ca < commonAnimIds.length; ca++) {
const commonAnimId = commonAnimIds[ca]; const commonAnimId = commonAnimIds[ca];
commonAnimFetches.push(fetch(`./battle-anims/common-${commonAnimNames[ca].toLowerCase().replace(/\_/g, '-')}.json`) commonAnimFetches.push(scene.cachedFetch(`./battle-anims/common-${commonAnimNames[ca].toLowerCase().replace(/\_/g, '-')}.json`)
.then(response => response.json()) .then(response => response.json())
.then(cas => commonAnims.set(commonAnimId, new AnimConfig(cas)))); .then(cas => commonAnims.set(commonAnimId, new AnimConfig(cas))));
} }
@ -439,7 +439,7 @@ export function initCommonAnims(): Promise<void> {
}); });
} }
export function initMoveAnim(move: Moves): Promise<void> { export function initMoveAnim(scene: BattleScene, move: Moves): Promise<void> {
return new Promise(resolve => { return new Promise(resolve => {
if (moveAnims.has(move)) { if (moveAnims.has(move)) {
if (moveAnims.get(move) !== null) if (moveAnims.get(move) !== null)
@ -460,7 +460,7 @@ export function initMoveAnim(move: Moves): Promise<void> {
const defaultMoveAnim = allMoves[move] instanceof AttackMove ? Moves.TACKLE : allMoves[move] instanceof SelfStatusMove ? Moves.FOCUS_ENERGY : Moves.TAIL_WHIP; const defaultMoveAnim = allMoves[move] instanceof AttackMove ? Moves.TACKLE : allMoves[move] instanceof SelfStatusMove ? Moves.FOCUS_ENERGY : Moves.TAIL_WHIP;
const moveName = Moves[move].toLowerCase().replace(/\_/g, '-'); const moveName = Moves[move].toLowerCase().replace(/\_/g, '-');
const fetchAnimAndResolve = (move: Moves) => { const fetchAnimAndResolve = (move: Moves) => {
fetch(`./battle-anims/${moveName}.json`) scene.cachedFetch(`./battle-anims/${moveName}.json`)
.then(response => { .then(response => {
if (!response.ok) { if (!response.ok) {
console.error(`Could not load animation file for move '${moveName}'`, response.status, response.statusText); console.error(`Could not load animation file for move '${moveName}'`, response.status, response.statusText);
@ -477,7 +477,7 @@ export function initMoveAnim(move: Moves): Promise<void> {
populateMoveAnim(move, ba); populateMoveAnim(move, ba);
const chargeAttr = allMoves[move].getAttrs(ChargeAttr).find(() => true) as ChargeAttr || allMoves[move].getAttrs(DelayedAttackAttr).find(() => true) as DelayedAttackAttr; const chargeAttr = allMoves[move].getAttrs(ChargeAttr).find(() => true) as ChargeAttr || allMoves[move].getAttrs(DelayedAttackAttr).find(() => true) as DelayedAttackAttr;
if (chargeAttr) if (chargeAttr)
initMoveChargeAnim(chargeAttr.chargeAnim).then(() => resolve()); initMoveChargeAnim(scene, chargeAttr.chargeAnim).then(() => resolve());
else else
resolve(); resolve();
}); });
@ -487,7 +487,7 @@ export function initMoveAnim(move: Moves): Promise<void> {
}); });
} }
export function initMoveChargeAnim(chargeAnim: ChargeAnim): Promise<void> { export function initMoveChargeAnim(scene: BattleScene, chargeAnim: ChargeAnim): Promise<void> {
return new Promise(resolve => { return new Promise(resolve => {
if (chargeAnims.has(chargeAnim)) { if (chargeAnims.has(chargeAnim)) {
if (chargeAnims.get(chargeAnim) !== null) if (chargeAnims.get(chargeAnim) !== null)
@ -502,7 +502,7 @@ export function initMoveChargeAnim(chargeAnim: ChargeAnim): Promise<void> {
} }
} else { } else {
chargeAnims.set(chargeAnim, null); chargeAnims.set(chargeAnim, null);
fetch(`./battle-anims/${ChargeAnim[chargeAnim].toLowerCase().replace(/\_/g, '-')}.json`) scene.cachedFetch(`./battle-anims/${ChargeAnim[chargeAnim].toLowerCase().replace(/\_/g, '-')}.json`)
.then(response => response.json()) .then(response => response.json())
.then(ca => { .then(ca => {
if (Array.isArray(ca)) { if (Array.isArray(ca)) {

View File

@ -3096,7 +3096,7 @@ export class RandomMoveAttr extends OverrideMoveEffectAttr {
: [ moveTargets.targets[user.randSeedInt(moveTargets.targets.length)] ]; : [ moveTargets.targets[user.randSeedInt(moveTargets.targets.length)] ];
user.getMoveQueue().push({ move: moveId, targets: targets, ignorePP: true }); user.getMoveQueue().push({ move: moveId, targets: targets, ignorePP: true });
user.scene.unshiftPhase(new MovePhase(user.scene, user, targets, new PokemonMove(moveId, 0, 0, true), true)); user.scene.unshiftPhase(new MovePhase(user.scene, user, targets, new PokemonMove(moveId, 0, 0, true), true));
initMoveAnim(moveId).then(() => { initMoveAnim(user.scene, moveId).then(() => {
loadMoveAnimAssets(user.scene, [ moveId ], true) loadMoveAnimAssets(user.scene, [ moveId ], true)
.then(() => resolve(true)); .then(() => resolve(true));
}); });
@ -3239,7 +3239,7 @@ export class NaturePowerAttr extends OverrideMoveEffectAttr {
user.getMoveQueue().push({ move: moveId, targets: [target.getBattlerIndex()], ignorePP: true }); user.getMoveQueue().push({ move: moveId, targets: [target.getBattlerIndex()], ignorePP: true });
user.scene.unshiftPhase(new MovePhase(user.scene, user, [target.getBattlerIndex()], new PokemonMove(moveId, 0, 0, true), true)); user.scene.unshiftPhase(new MovePhase(user.scene, user, [target.getBattlerIndex()], new PokemonMove(moveId, 0, 0, true), true));
initMoveAnim(moveId).then(() => { initMoveAnim(user.scene, moveId).then(() => {
loadMoveAnimAssets(user.scene, [ moveId ], true) loadMoveAnimAssets(user.scene, [ moveId ], true)
.then(() => resolve(true)); .then(() => resolve(true));
}); });

View File

@ -394,7 +394,7 @@ export abstract class PokemonSpeciesForm {
return new Promise(resolve => { return new Promise(resolve => {
if (variantColorCache.hasOwnProperty(key)) if (variantColorCache.hasOwnProperty(key))
return resolve(); return resolve();
fetch(`./images/pokemon/variant/${spritePath}.json`).then(res => res.json()).then(c => { scene.cachedFetch(`./images/pokemon/variant/${spritePath}.json`).then(res => res.json()).then(c => {
variantColorCache[key] = c; variantColorCache[key] = c;
resolve(); resolve();
}); });

View File

@ -275,7 +275,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
loadAssets(ignoreOverride: boolean = true): Promise<void> { loadAssets(ignoreOverride: boolean = true): Promise<void> {
return new Promise(resolve => { return new Promise(resolve => {
const moveIds = this.getMoveset().map(m => m.getMove().id); const moveIds = this.getMoveset().map(m => m.getMove().id);
Promise.allSettled(moveIds.map(m => initMoveAnim(m))) Promise.allSettled(moveIds.map(m => initMoveAnim(this.scene, m)))
.then(() => { .then(() => {
loadMoveAnimAssets(this.scene, moveIds); loadMoveAnimAssets(this.scene, moveIds);
this.getSpeciesForm().loadAssets(this.scene, this.getGender() === Gender.FEMALE, this.formIndex, this.shiny, this.variant); this.getSpeciesForm().loadAssets(this.scene, this.getGender() === Gender.FEMALE, this.formIndex, this.shiny, this.variant);
@ -317,7 +317,7 @@ export default abstract class Pokemon extends Phaser.GameObjects.Container {
if (variantSet && variantSet[this.variant] === 1) { if (variantSet && variantSet[this.variant] === 1) {
if (variantColorCache.hasOwnProperty(key)) if (variantColorCache.hasOwnProperty(key))
return resolve(); return resolve();
fetch(`./images/pokemon/variant/${battleSpritePath}.json`).then(res => res.json()).then(c => { this.scene.cachedFetch(`./images/pokemon/variant/${battleSpritePath}.json`).then(res => res.json()).then(c => {
variantColorCache[key] = c; variantColorCache[key] = c;
resolve(); resolve();
}); });

View File

@ -19,12 +19,7 @@ export class LoadingScene extends SceneBase {
} }
preload() { preload() {
const indexFile = Array.from(document.querySelectorAll('script')).map(s => s.src).find(s => /\/index/.test(s)); this.load['manifest'] = this.game['manifest'];
if (indexFile) {
const buildIdMatch = /index\-(.*?)\.js$/.exec(indexFile);
if (buildIdMatch)
this.load['cacheBuster'] = buildIdMatch[1];
}
if (!isMobile()) if (!isMobile())
this.load.video('intro_dark', 'images/intro_dark.mp4', true); this.load.video('intro_dark', 'images/intro_dark.mp4', true);

View File

@ -76,7 +76,21 @@ Phaser.GameObjects.Rectangle.prototype.setPositionRelative = setPositionRelative
document.fonts.load('16px emerald').then(() => document.fonts.load('10px pkmnems')); document.fonts.load('16px emerald').then(() => document.fonts.load('10px pkmnems'));
const game = new Phaser.Game(config); let game;
game.sound.pauseOnBlur = false;
const startGame = () => {
game = new Phaser.Game(config);
game.sound.pauseOnBlur = false;
};
fetch('/manifest.json')
.then(res => res.json())
.then(jsonResponse => {
startGame();
game['manifest'] = jsonResponse.manifest;
}).catch(() => {
// Manifest not found (likely local build)
startGame();
});
export default game; export default game;

View File

@ -2613,7 +2613,7 @@ export class MoveAnimTestPhase extends BattlePhase {
} else if (player) } else if (player)
console.log(Moves[moveId]); console.log(Moves[moveId]);
initMoveAnim(moveId).then(() => { initMoveAnim(this, moveId).then(() => {
loadMoveAnimAssets(this.scene, [ moveId ], true) loadMoveAnimAssets(this.scene, [ moveId ], true)
.then(() => { .then(() => {
new MoveAnim(moveId, player ? this.scene.getPlayerPokemon() : this.scene.getEnemyPokemon(), (player !== (allMoves[moveId] instanceof SelfStatusMove) ? this.scene.getEnemyPokemon() : this.scene.getPlayerPokemon()).getBattlerIndex()).play(this.scene, () => { new MoveAnim(moveId, player ? this.scene.getPlayerPokemon() : this.scene.getEnemyPokemon(), (player !== (allMoves[moveId] instanceof SelfStatusMove) ? this.scene.getEnemyPokemon() : this.scene.getPlayerPokemon()).getBattlerIndex()).play(this.scene, () => {
@ -3675,7 +3675,7 @@ export class LearnMovePhase extends PlayerPartyMemberPokemonPhase {
if (emptyMoveIndex > -1) { if (emptyMoveIndex > -1) {
pokemon.setMove(emptyMoveIndex, this.moveId); pokemon.setMove(emptyMoveIndex, this.moveId);
initMoveAnim(this.moveId).then(() => { initMoveAnim(this, this.moveId).then(() => {
loadMoveAnimAssets(this.scene, [ this.moveId ], true) loadMoveAnimAssets(this.scene, [ this.moveId ], true)
.then(() => { .then(() => {
this.scene.ui.setMode(messageMode).then(() => { this.scene.ui.setMode(messageMode).then(() => {

View File

@ -1,26 +1,29 @@
let cacheBuster = ''; let manifest: object;
const ignoredFiles = [ 'intro_dark' ];
export default class CacheBustedLoaderPlugin extends Phaser.Loader.LoaderPlugin { export default class CacheBustedLoaderPlugin extends Phaser.Loader.LoaderPlugin {
constructor(scene: Phaser.Scene) { constructor(scene: Phaser.Scene) {
super(scene) super(scene)
} }
get cacheBuster() { get manifest() {
return cacheBuster return manifest;
} }
set cacheBuster(version) { set manifest(manifestObj: object) {
cacheBuster = version manifest = manifestObj;
} }
addFile(file): void { addFile(file): void {
if (!Array.isArray(file)) if (!Array.isArray(file))
file = [ file ]; file = [ file ];
if (!ignoredFiles.includes(file?.key) && cacheBuster) file.forEach(item => {
file.forEach(item => item.url += '?v=' + cacheBuster); if (manifest) {
const timestamp = manifest[`/${item.url.replace(/\/\//g, '/')}` ];
if (timestamp)
item.url += `?t=${timestamp}`;
}
});
super.addFile(file); super.addFile(file);
} }

View File

@ -5,25 +5,35 @@ export class SceneBase extends Phaser.Scene {
super(config); super(config);
} }
getCachedUrl(url: string): string {
const manifest = this.game['manifest'];
if (manifest) {
const timestamp = manifest[`/${url}`];
if (timestamp)
url += `?t=${timestamp}`;
}
return url;
}
loadImage(key: string, folder: string, filename?: string) { loadImage(key: string, folder: string, filename?: string) {
if (!filename) if (!filename)
filename = `${key}.png`; filename = `${key}.png`;
this.load.image(key, `images/${folder}/${filename}`); this.load.image(key, this.getCachedUrl(`images/${folder}/${filename}`));
if (folder.startsWith('ui')) { if (folder.startsWith('ui')) {
legacyCompatibleImages.push(key); legacyCompatibleImages.push(key);
folder = folder.replace('ui', 'ui/legacy'); folder = folder.replace('ui', 'ui/legacy');
this.load.image(`${key}_legacy`, `images/${folder}/${filename}`); this.load.image(`${key}_legacy`, this.getCachedUrl(`images/${folder}/${filename}`));
} }
} }
loadSpritesheet(key: string, folder: string, size: integer, filename?: string) { loadSpritesheet(key: string, folder: string, size: integer, filename?: string) {
if (!filename) if (!filename)
filename = `${key}.png`; filename = `${key}.png`;
this.load.spritesheet(key, `images/${folder}/${filename}`, { frameWidth: size, frameHeight: size }); this.load.spritesheet(key, this.getCachedUrl(`images/${folder}/${filename}`), { frameWidth: size, frameHeight: size });
if (folder.startsWith('ui')) { if (folder.startsWith('ui')) {
legacyCompatibleImages.push(key); legacyCompatibleImages.push(key);
folder = folder.replace('ui', 'ui/legacy'); folder = folder.replace('ui', 'ui/legacy');
this.load.spritesheet(`${key}_legacy`, `images/${folder}/${filename}`, { frameWidth: size, frameHeight: size }); this.load.spritesheet(`${key}_legacy`, this.getCachedUrl(`images/${folder}/${filename}`), { frameWidth: size, frameHeight: size });
} }
} }
@ -32,11 +42,11 @@ export class SceneBase extends Phaser.Scene {
filenameRoot = key; filenameRoot = key;
if (folder) if (folder)
folder += '/'; folder += '/';
this.load.atlas(key, `images/${folder}${filenameRoot}.png`, `images/${folder}/${filenameRoot}.json`); this.load.atlas(key, this.getCachedUrl(`images/${folder}${filenameRoot}.png`), this.getCachedUrl(`images/${folder}/${filenameRoot}.json`));
if (folder.startsWith('ui')) { if (folder.startsWith('ui')) {
legacyCompatibleImages.push(key); legacyCompatibleImages.push(key);
folder = folder.replace('ui', 'ui/legacy'); folder = folder.replace('ui', 'ui/legacy');
this.load.atlas(`${key}_legacy`, `images/${folder}${filenameRoot}.png`, `images/${folder}/${filenameRoot}.json`); this.load.atlas(`${key}_legacy`, this.getCachedUrl(`images/${folder}${filenameRoot}.png`), this.getCachedUrl(`images/${folder}/${filenameRoot}.json`));
} }
} }
@ -49,14 +59,13 @@ export class SceneBase extends Phaser.Scene {
folder += '/'; folder += '/';
if (!Array.isArray(filenames)) if (!Array.isArray(filenames))
filenames = [ filenames ]; filenames = [ filenames ];
for (let f of filenames as string[]) { for (let f of filenames as string[])
this.load.audio(key, `audio/se/${folder}${f}`); this.load.audio(key, this.getCachedUrl(`audio/se/${folder}${f}`));
}
} }
loadBgm(key: string, filename?: string) { loadBgm(key: string, filename?: string) {
if (!filename) if (!filename)
filename = `${key}.mp3`; filename = `${key}.mp3`;
this.load.audio(key, `audio/bgm/${filename}`); this.load.audio(key, this.getCachedUrl(`audio/bgm/${filename}`));
} }
} }