1 changed files with 64 additions and 0 deletions
@ -0,0 +1,64 @@ |
|||||
|
import { Assets, type AssetsBundle } from "pixi.js"; |
||||
|
import { logger } from "./Logger"; |
||||
|
|
||||
|
class AssetManager { |
||||
|
private referenceCounts: Map<string, number> = new Map(); |
||||
|
|
||||
|
async init(): Promise<void> { |
||||
|
await Assets.init({ manifest: "/manifest.json" }); |
||||
|
logger.debug("AssetManager initialized"); |
||||
|
} |
||||
|
|
||||
|
async loadBundle( |
||||
|
name: string, |
||||
|
onProgress?: (progress: number) => void |
||||
|
): Promise<AssetsBundle> { |
||||
|
// 已经加载过,增加引用计数
|
||||
|
if (this.referenceCounts.has(name)) { |
||||
|
const count = this.referenceCounts.get(name)! + 1; |
||||
|
this.referenceCounts.set(name, count); |
||||
|
logger.debug(`AssetManager: reuse bundle "${name}", refCount = ${count}`); |
||||
|
onProgress?.(1); |
||||
|
return Assets.getBundle(name); |
||||
|
} |
||||
|
|
||||
|
// 首次加载
|
||||
|
logger.debug(`AssetManager: loading bundle "${name}"`); |
||||
|
const bundle = await Assets.loadBundle(name, onProgress); |
||||
|
this.referenceCounts.set(name, 1); |
||||
|
return bundle; |
||||
|
} |
||||
|
|
||||
|
async unloadBundle(name: string): Promise<void> { |
||||
|
if (!this.referenceCounts.has(name)) { |
||||
|
logger.warn(`AssetManager: unloading unloaded bundle "${name}"`); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
const count = this.referenceCounts.get(name)! - 1; |
||||
|
this.referenceCounts.set(name, count); |
||||
|
|
||||
|
if (count <= 0) { |
||||
|
logger.debug(`AssetManager: unloading bundle "${name}"`); |
||||
|
await Assets.unloadBundle(name); |
||||
|
this.referenceCounts.delete(name); |
||||
|
} else { |
||||
|
logger.debug(`AssetManager: decrease refCount for "${name}" to ${count}`); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
isLoaded(name: string): boolean { |
||||
|
return this.referenceCounts.has(name) && this.referenceCounts.get(name)! > 0; |
||||
|
} |
||||
|
|
||||
|
getRefCount(name: string): number { |
||||
|
return this.referenceCounts.get(name) ?? 0; |
||||
|
} |
||||
|
|
||||
|
clearAll(): void { |
||||
|
this.referenceCounts.clear(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
export const assetManager = new AssetManager(); |
||||
|
export default assetManager; |
||||
Loading…
Reference in new issue