# 資源加載器
xr-frame允許開發(fā)者定制資源加載器,來添加自己所需的資源類型。所有的資源加載器都需要派生自AssetLoader類,然后使用上一章的方法在xml中或者手動(dòng)使用。
在基礎(chǔ)庫版本v2.29.2以上,支持自定義資源加載器。
# 以一個(gè)加載器為例
讓我們以內(nèi)置的紋理加載器為例,
import XrFrame from 'XrFrame';
const xrFrameSystem = wx.getXrFrameSystem();
// 指定紋理可接受的額外參數(shù)
export interface ITextureLoaderOptions {
anisoLevel?: number;
}
// 加載紋理時(shí)會(huì)被傳入的數(shù)據(jù)
type ITextureLoadData = XrFrame.IAssetLoadData<ITextureLoaderOptions>;
// 定制加載器
export default class TextureLoader extends xrFrameSystem.AssetLoader<XrFrame.Texture, ITextureLoaderOptions> {
// 指定加載器參數(shù)的`schema`,和**數(shù)據(jù)解析**一章中的數(shù)據(jù)類型一致
public readonly schema: ILoaderOptionsSchema = {
anisoLevel: {type: 'number', defaultValue: 1},
};
// 當(dāng)紋理資源加載時(shí)會(huì)調(diào)用這個(gè)方法
public load(
params: ITextureLoadData,
callbacks: {
// 開發(fā)者需要在加載進(jìn)度更新時(shí)調(diào)用的回調(diào)
onLoading(progress: number): void;
// 開發(fā)者需要在加載完成時(shí)調(diào)用的回調(diào)
onLoaded(value: Kanata.Texture): void;
// 開發(fā)者需要在加載出錯(cuò)時(shí)調(diào)用的回調(diào)
onError(error: Error): void;
}
): void {
const {options} = params;
// 這里可以拿到當(dāng)前場景`scene`的引用
const img = this.scene.createImage();
img.onload = () => {
const texture = this.scene.createTexture({
source: [img],
width: img.width,
height: img.height,
anisoLevel: options.anisoLevel
});
callbacks.onLoaded(texture);
}
img.onerror = (error) => {
callbacks.onError(error);
}
img.src = params.src;
}
// 返回一個(gè)當(dāng)前加載器指定類型資源的**默認(rèn)資源列表**,這些資源可以直接被組件引用,但它們都是`defer`的,只有在用到的時(shí)候才會(huì)去加載。
public getBuiltin() {
return [
{
assetId: 'brdf-lut',
src: 'https://mmbizwxaminiprogram-1258344707.cos.ap-guangzhou.myqcloud.com/xr-frame/brdflut.png',
options: {}
}
];
}
// 某個(gè)資源被取消加載時(shí)會(huì)調(diào)用,記得一定要先調(diào)用父級的方法
public cancel(params: ITextureLoadData) {
super.cancel();
}
// 某個(gè)資源被釋放時(shí)會(huì)調(diào)用,這里可以執(zhí)行釋放操作
public release(params: ITextureLoadData, value: XrFrame.Texture) {
value.destroy();
}
}
// 注冊加載器到框架,資源類型為`texture`
xrFrameSystem.registerAssetLoader('texture', TextureLoader);
通過這個(gè)紋理加載器我們可以看到,資源系統(tǒng)是通過加載器的load、cancel、release三個(gè)方法來管理整個(gè)資源的生命周期的。
最后將加載器注冊為某種類型后,這種資源類型將會(huì)同時(shí)被注冊進(jìn)組件數(shù)據(jù)解析器,在schema中定義使用。
# 原始加載器
除了后續(xù)會(huì)提到的各種類型的資源加載器外,為了最靈活應(yīng)對需求,框架提供了原始加載器RawLoader來加載最原始的數(shù)據(jù),其類型為raw,options為{encoding: 'binary' | 'utl-8'},默認(rèn)是二進(jìn)制。