@polygonjs/polygonjs
Version:
node-based WebGL 3D engine https://polygonjs.com
104 lines (103 loc) • 2.97 kB
JavaScript
;
import { LoadingManager } from "three";
import { Poly } from "../../engine/Poly";
import { isArray } from "../Type";
import { sanitizeUrl } from "../UrlHelper";
export function modifyUrl(url) {
const remapedUrl = Poly.assetUrls.remapedUrl(url);
if (remapedUrl) {
return remapedUrl;
}
return url;
}
export function createLoadingManager() {
const loadingManager = new LoadingManager();
loadingManager.setURLModifier(modifyUrl);
return loadingManager;
}
export const LOADING_MANAGER = createLoadingManager();
const _CoreBaseLoader = class {
// not static
constructor(_url, _node, blobOptions = {}) {
this._url = _url;
this._node = _node;
this.blobOptions = blobOptions;
// static
this.loadingManager = LOADING_MANAGER;
if (isArray(this._url)) {
this._url = this._url.map(sanitizeUrl);
} else {
this._url = sanitizeUrl(this._url);
}
}
static extension(url) {
let ext = null;
try {
const _url = new URL(url);
ext = _url.searchParams.get("ext");
} catch (e) {
}
if (!ext) {
const url_without_params = url.split("?")[0];
const elements = url_without_params.split(".");
ext = elements[elements.length - 1].toLowerCase();
}
return ext;
}
extension() {
return isArray(this._url) ? _CoreBaseLoader.extension(this._url[0]) : _CoreBaseLoader.extension(this._url);
}
_urlToLoad() {
const blobOrFullUrl = (fullUrl) => {
if (this._node) {
const assetsRoot = this._node.scene().assets.root();
if (!fullUrl.startsWith("http")) {
fullUrl = assetsRoot ? sanitizeUrl(`${assetsRoot}/${fullUrl}`) : fullUrl;
}
}
return fullUrl;
};
if (isArray(this._url)) {
return this._url.map(blobOrFullUrl);
} else {
return blobOrFullUrl(this._url);
}
}
static async _loadMultipleUrlsGlobal(options) {
const promises = [];
for (const file of options.files) {
const fullUrl = file.fullUrl;
const _fetch = async () => {
const response = await fetch(fullUrl);
if (response.ok) {
return {};
} else {
return { error: `failed to fetch '${fullUrl}'` };
}
};
promises.push(_fetch());
}
const responses = await Promise.all(promises);
if (options.node) {
for (const response of responses) {
if (response.error) {
options.node.states.error.set(options.error);
}
}
}
}
static onAssetLoaded(callback) {
this._onAssetLoadedCallbacks = this._onAssetLoadedCallbacks || [];
this._onAssetLoadedCallbacks.push(callback);
}
static _runOnAssetLoadedCallbacks(url, asset) {
if (!this._onAssetLoadedCallbacks) {
return;
}
for (const callback of this._onAssetLoadedCallbacks) {
callback(url, asset);
}
}
};
export let CoreBaseLoader = _CoreBaseLoader;
CoreBaseLoader.loadingManager = LOADING_MANAGER;