threepipe
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AssetImporter.ts 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. import {EventDispatcher, EventListener, FileLoader, LoaderUtils, LoadingManager} from 'three'
  2. import {
  3. IAssetImporter,
  4. IImportResultUserData,
  5. ImportAssetOptions,
  6. ImportFilesOptions,
  7. ImportResult,
  8. LoadFileOptions,
  9. ProcessRawOptions,
  10. } from './IAssetImporter'
  11. import {IAsset, IFile} from './IAsset'
  12. import {IImporter, ILoader} from './IImporter'
  13. import {Importer} from './Importer'
  14. import {SimpleJSONLoader} from './import'
  15. import {parseFileExtension} from 'ts-browser-helpers'
  16. import {IObject3D} from '../core'
  17. // export type IAssetImporterEvent = Event&{
  18. // type: IAssetImporterEventTypes,
  19. // data?: ImportResult, options?: ProcessRawOptions,
  20. // path?: string, progress?: number, state?: string, error?: any
  21. // files?: Map<string, IFile>
  22. // url?: string, loaded?: number, total?: number
  23. // loader?: ILoader,
  24. // }
  25. // export type IAssetImporterEventTypes = 'onLoad' | 'onProgress' | 'onStop' | 'onError' | 'onStart' | 'loaderCreate' | 'importFile' | 'importFiles' | 'processRaw' | 'processRawStart'
  26. export interface IAssetImporterEventMap {
  27. loaderCreate: {type: 'loaderCreate', loader: ILoader}
  28. importFile: {type: 'importFile', path: string, state: 'downloading'|'done'|'error'|'adding', progress?: number, loadedBytes?: number, totalBytes?: number, error?: any}
  29. importFiles: {type: 'importFiles', files: Map<string, IFile>, state: 'start'|'end'}
  30. processRaw: {type: 'processRaw', data: any, options: ProcessRawOptions, path?: string}
  31. processRawStart: {type: 'processRawStart', data: any, options: ProcessRawOptions, path?: string}
  32. /**
  33. * @deprecated use the {@link importFile} event instead
  34. */
  35. onLoad: {type: 'onLoad'}
  36. /**
  37. * @deprecated use the {@link importFile} event instead
  38. */
  39. onProgress: {type: 'onProgress', url: string, loaded: number, total: number}
  40. /**
  41. * @deprecated use the {@link importFile} event instead
  42. */
  43. onError: {type: 'onError', url: string}
  44. /**
  45. * @deprecated use the {@link importFile} event instead
  46. */
  47. onStart: {type: 'onStart', url: string, loaded: number, total: number}
  48. }
  49. /**
  50. * Asset Importer
  51. *
  52. * Utility class to import assets from local files, blobs, urls, etc.
  53. * Used in {@link AssetManager} to import assets.
  54. * Acts as a wrapper over three.js LoadingManager and adds support for dynamically loading loaders, caching assets, better event dispatching and file tracking.
  55. * @category Asset Manager
  56. */
  57. export class AssetImporter extends EventDispatcher<IAssetImporterEventMap> implements IAssetImporter {
  58. private _loadingManager: LoadingManager
  59. private _logger = console.log
  60. // Used when loading multiple files at once.
  61. protected _rootContext?: {path: string, rootUrl: string, /* baseUrl: string;*/}
  62. private _loaderCache: {loader: ILoader, ext: string[], mime: string[]}[] = []
  63. private _fileDatabase: Map<string, IFile> = new Map<string, IFile>()
  64. private _cachedAssets: IAsset[] = []
  65. static WHITE_IMAGE_DATA = new ImageData(new Uint8ClampedArray([255, 255, 255, 255]), 1, 1)
  66. readonly importers: IImporter[] = [
  67. // new Importer(VideoTextureLoader, ['mp4', 'ogg', 'mov', 'data:video'], false),
  68. new Importer(SimpleJSONLoader, ['json', 'vjson'], ['application/json'], false),
  69. new Importer(FileLoader, ['txt'], ['text/plain'], false),
  70. // new Importer(RGBEPNGLoader, ['rgbe.png', 'hdr.png', 'hdrpng'], ['image/png+rgbe'], false), // todo: not working on windows?
  71. // new Importer(LUTCubeLoader2, ['cube'], false),
  72. ]
  73. constructor(logging = false) {
  74. super()
  75. if (!logging) this._logger = () => {return}
  76. // this._viewer = viewer
  77. this._onLoad = this._onLoad.bind(this)
  78. this._onProgress = this._onProgress.bind(this)
  79. this._onError = this._onError.bind(this)
  80. this._onStart = this._onStart.bind(this)
  81. this._urlModifier = this._urlModifier.bind(this)
  82. this._loadingManager = new LoadingManager(this._onLoad, this._onProgress, this._onError)
  83. this._loadingManager.onStart = this._onStart
  84. this._loadingManager.setURLModifier(this._urlModifier)
  85. }
  86. get loadingManager(): LoadingManager {
  87. return this._loadingManager
  88. }
  89. get cachedAssets(): IAsset[] {
  90. return this._cachedAssets
  91. }
  92. addImporter(...importers: IImporter[]) {
  93. for (const importer of importers) {
  94. if (this.importers.includes(importer)) {
  95. console.warn('AssetImporter: Importer already added', importer)
  96. return
  97. }
  98. this.importers.push(importer)
  99. }
  100. }
  101. removeImporter(...importers: IImporter[]) {
  102. for (const importer of importers) {
  103. const index = this.importers.indexOf(importer)
  104. if (index >= 0) this.importers.splice(index, 1)
  105. }
  106. }
  107. // region import functions
  108. async import<T extends ImportResult|undefined = ImportResult>(assetOrPath?: string | IAsset | IAsset[] | File | File[], options?: ImportAssetOptions): Promise<(T|undefined)[]> {
  109. if (!assetOrPath) return []
  110. if (Array.isArray(assetOrPath)) return (await Promise.all(assetOrPath.map(async a => this.import<T>(a, options)))).flat(1)
  111. if (assetOrPath instanceof File) return await this.importFile<T>(assetOrPath, options)
  112. if (typeof assetOrPath === 'object') return await this.importAsset<T>(assetOrPath, options)
  113. if (typeof assetOrPath === 'string') return await this.importPath<T>(assetOrPath, options)
  114. console.error('AssetImporter: Invalid asset or path', assetOrPath)
  115. return []
  116. }
  117. async importSingle<T extends ImportResult|undefined = ImportResult>(asset?: IAsset | string, options?: ImportAssetOptions): Promise<T|undefined> {
  118. return (await this.import<T>(asset, options))?.[0]
  119. }
  120. async importPath<T extends ImportResult|undefined = ImportResult|undefined>(path: string, options: ImportAssetOptions = {}): Promise<T[]> {
  121. const op = {...options}
  122. delete op.pathOverride
  123. delete op.forceImport
  124. delete op.reimportDisposed
  125. delete op.fileHandler
  126. delete op.importedFile
  127. const opts = JSON.stringify(op)
  128. const cached = this._cachedAssets.find(a => a.path === path && a._options === opts)
  129. let asset: IAsset
  130. if (cached) asset = cached
  131. else asset = {path}
  132. asset._options = opts
  133. if (options.importedFile) asset.file = options.importedFile
  134. return await this.importAsset(asset, options)
  135. }
  136. // import and process an IAsset
  137. async importAsset<T extends ImportResult|undefined = ImportResult|undefined>(asset?: IAsset, options: ImportAssetOptions = {}, onDownloadProgress?: (e:ProgressEvent)=>void): Promise<T[]> {
  138. if (!asset) return []
  139. if (!asset.path && !asset.file && !options.pathOverride) {
  140. return [asset as any] // maybe already imported asset
  141. }
  142. // Cache the asset reference if it is not already cached
  143. if (!this._cachedAssets.includes(asset)) {
  144. if (Object.entries(asset).length === 1 && asset.path) {
  145. const ca = this._cachedAssets.find(value => value.path === asset.path)
  146. if (ca) Object.assign(asset, ca)
  147. }
  148. const ca = this._cachedAssets.findIndex(value => value.path === asset.path)
  149. if (ca >= 0) this._cachedAssets.splice(ca, 1)
  150. this._cachedAssets.push(asset)
  151. }
  152. let result: any = asset?.preImported
  153. if (!result && asset?.preImportedRaw) {
  154. result = await asset.preImportedRaw
  155. }
  156. const path = options.pathOverride || asset.path
  157. // console.log(result)
  158. if (!options.forceImport && result) {
  159. const results = await this.processRaw<T>(result, options, path) // just in case its not processed. Internal check is done to ensure it's not processed twice
  160. // let isDisposed = false // if any of the objects is disposed
  161. // for (const r of results) {
  162. // // todo: check if this is still required.
  163. // if ((r as RootSceneImportResult)?.userData?.rootSceneModelRoot) { // in case processImported is false we need a special case check here
  164. // if (r?.children?.find((c: any) => c.__disposed)) {
  165. // isDisposed = true
  166. // break
  167. // }
  168. // }
  169. // if (r && !r.__disposed) continue // todo add __disposed to object, material, texture, etc
  170. // isDisposed = true
  171. // break
  172. // }
  173. // todo: should we check if any of it's children is disposed ?
  174. // if (!isDisposed || options.reimportDisposed === false)
  175. return results
  176. }
  177. // todo: add support to get cloned asset? if we want to import multiple times and everytime return a cloned asset
  178. asset.preImportedRaw = this._loadFile(path, typeof asset.file?.arrayBuffer === 'function' ? asset.file : undefined, options, onDownloadProgress)
  179. result = await asset.preImportedRaw
  180. if (result) result = await this.processRaw(result, options, path)
  181. if (result) {
  182. if (options.processRaw !== false) asset.preImported = result
  183. const arrs: any[] = []
  184. if (Array.isArray(result)) arrs.push(...result)
  185. else {
  186. if (result.userData?.rootSceneModelRoot) arrs.push(...result.children)
  187. else arrs.push(result)
  188. }
  189. // remove preImportedRaw when any of the assets is disposed. This is to prevent memory leaks
  190. arrs.forEach(r=>r.addEventListener?.('dispose', () => { // todo: recheck after dispose logic change
  191. if (asset?.preImportedRaw) asset.preImportedRaw = undefined
  192. if (asset?.preImported) asset.preImported = undefined
  193. }))
  194. }
  195. return result
  196. }
  197. async importFile<T extends ImportResult|undefined = ImportResult|undefined>(file?: File, options: ImportAssetOptions = {}, onDownloadProgress?: (e:ProgressEvent)=>void): Promise<T[]> {
  198. if (!file) return []
  199. if (!(file instanceof File)) {
  200. console.error('AssetImporter: Invalid file', file)
  201. return []
  202. }
  203. return this.importAsset(this._cachedAssets.find(a=>a.file === file) ?? {
  204. path: file.name || file.webkitRelativePath, file,
  205. }, options, onDownloadProgress)
  206. }
  207. /**
  208. * Import multiple local files/blobs from a map of files, like when a local folder is loaded, or when multiple files are dropped.
  209. * @param files
  210. * @param options
  211. */
  212. async importFiles<T extends ImportResult|undefined=ImportResult|undefined>(files: Map<string, IFile>, options: ImportFilesOptions = {}): Promise<Map<string, T[]>> {
  213. const loaded = new Map<string, any>()
  214. let {allowedExtensions} = options
  215. if (allowedExtensions && allowedExtensions.length < 1) allowedExtensions = undefined
  216. if (files.size === 0) return loaded
  217. this.dispatchEvent({type: 'importFiles', files: files, state: 'start'})
  218. const baseFiles: string[] = []
  219. const altFiles: string[] = []
  220. // Note: mostly path === file.name
  221. files.forEach((file, path) => { // todo: handle only one file at the top
  222. this.registerFile(path, file)
  223. const ext = file.ext
  224. const mime = file.mime
  225. if ((ext || mime) && // todo: files with no extensions are not supported right now. This also includes __MacOSX
  226. (allowedExtensions?.includes((ext || mime || '').toLowerCase()) ?? true)) {
  227. if (this._isRootFile(ext)) baseFiles.push(path)
  228. else altFiles.push(path)
  229. }
  230. })
  231. if (baseFiles.length > 0) {
  232. for (const value of baseFiles) {
  233. let res = await this._loadFile(value, undefined, options)
  234. if (res) res = await this.processRaw(res, options, value)
  235. loaded.set(value, res)
  236. }
  237. } else {
  238. for (const value of altFiles) {
  239. let res = await this._loadFile(value, undefined, options)
  240. if (res) res = await this.processRaw(res, options, value)
  241. loaded.set(value, res)
  242. }
  243. // todo: handle no baseFiles
  244. }
  245. this.dispatchEvent({type: 'importFiles', files: files, state: 'end'})
  246. files.forEach((_, path) => this.unregisterFile(path))
  247. return loaded
  248. }
  249. // load a single file
  250. private async _loadFile(path: string, file?: IFile, options: LoadFileOptions = {}, onDownloadProgress?: (e: ProgressEvent)=>void): Promise<ImportResult | ImportResult[] | undefined> {
  251. if (file?.__loadedAsset) return file.__loadedAsset
  252. this.dispatchEvent({type: 'importFile', path, state:'downloading', progress: 0})
  253. let res: ImportResult | ImportResult[] | undefined
  254. try {
  255. const loader = this.registerFile(path, file)
  256. // const url = this.resolveURL(path) // todo: why is this required? maybe for query string?
  257. // const path2 = path.replace(/\?.*$/, '') // remove query string to find the handler properly
  258. // const loader = (options.fileHandler as ILoader) ?? this._getLoader(path2) ??
  259. // (file ? this._getLoader(file.name, file.ext, file.mime) : undefined)
  260. if (!loader) {
  261. throw new Error('AssetImporter: Unable to find loader for ' + path) // caught below
  262. }
  263. this._rootContext = {
  264. path,
  265. rootUrl: LoaderUtils.extractUrlBase(path),
  266. // baseUrl: LoaderUtils.extractUrlBase(url),
  267. }
  268. res = await loader.loadAsync(path + (options.queryString ? (path.includes('?') ? '&' : '?') + options.queryString : ''), (e)=>{
  269. if (onDownloadProgress) onDownloadProgress(e)
  270. this.dispatchEvent({
  271. type: 'importFile', path,
  272. state:'downloading',
  273. loadedBytes: e.loaded || undefined,
  274. totalBytes: e.total || undefined,
  275. progress: e.total > 0 ? e.loaded / e.total : 1,
  276. })
  277. })
  278. if (loader.transform) res = await loader.transform(res, options)
  279. this._rootContext = undefined
  280. this.dispatchEvent({type: 'importFile', path, state:'downloading', progress: 1})
  281. this.dispatchEvent({type: 'importFile', path, state: 'adding'})
  282. if (file)
  283. this._logger('AssetImporter: loaded', path)
  284. else
  285. this._logger('AssetImporter: downloaded', path)
  286. if (file)
  287. this.unregisterFile(path)
  288. } catch (e: any) {
  289. console.error('AssetImporter: Unable to import file', path, file)
  290. console.error(e)
  291. console.error(e?.stack)
  292. // throw e
  293. this.dispatchEvent({type: 'importFile', path, state: 'error', error: e})
  294. if (file)
  295. this.unregisterFile(path)
  296. return []
  297. }
  298. this.dispatchEvent({type: 'importFile', path, state: 'done'}) // todo: do this after processing?
  299. if (file) {
  300. file.__loadedAsset = res
  301. // todo: recheck below code after dispose logic change
  302. // Clear the reference __loadedAsset when any one asset is disposed.
  303. // it's a bit hacky to do this here, but it works for now. todo: move to a better place
  304. let ress: any[] = []
  305. if (Array.isArray(res)) ress = res.flat(2)
  306. else if ((<IObject3D>res)?.userData?.rootSceneModelRoot) ress.push(...(<IObject3D>res).children)
  307. else ress.push(res)
  308. for (const r of ress) r?.addEventListener?.('dispose', () => file.__loadedAsset = undefined)
  309. }
  310. if (res && typeof res === 'object' && !Array.isArray(res)) {
  311. res.__rootPath = path
  312. const f = file || this._fileDatabase.get(path)
  313. if (f) res.__rootBlob = f
  314. }
  315. return res
  316. }
  317. // endregion
  318. // region file database
  319. /**
  320. * Register a file in the database and return a loader for it. If the loader does not exist, it will be created.
  321. * @param path
  322. * @param file
  323. */
  324. registerFile(path: string, file?: IFile): ILoader | undefined {
  325. const isData = path.startsWith('data:') || false
  326. if (!isData) path = path.replace(/\?.*$/, '') // remove query string
  327. const ext = isData ? undefined : file?.ext ?? parseFileExtension(file?.name ?? path.trim())?.toLowerCase()
  328. const mime = file?.mime ?? isData ? path.slice(0, path.indexOf(';')).split(':')[1] || undefined : undefined
  329. if (file) {
  330. if (file.name === undefined) (file as any).name = path
  331. if (!file.ext) file.ext = ext
  332. if (!file.mime) file.mime = mime
  333. if (this._fileDatabase.has(path)) {
  334. console.warn('AssetImporter: File already registered, replacing', path)
  335. this.unregisterFile(path)
  336. }
  337. this._fileDatabase.set(path, file)
  338. }
  339. return this._getLoader(path) || this._createLoader(path, ext, mime)
  340. }
  341. /**
  342. * Remove a file from the database and revoke the object url if it exists.
  343. * @param path
  344. */
  345. unregisterFile(path: string) {
  346. path = path.replace(/\?.*$/, '') // remove query string
  347. const file = this._fileDatabase.get(path)
  348. if (file?.objectUrl) {
  349. URL.revokeObjectURL(file.objectUrl)
  350. file.objectUrl = undefined
  351. }
  352. if (file) this._fileDatabase.delete(path)
  353. }
  354. // endregion
  355. // region processRaw
  356. public async processRaw<T extends (ImportResult|undefined) = ImportResult>(res: T|T[], options: ProcessRawOptions, path?: string): Promise<T[]> {
  357. if (!res) return []
  358. // legacy
  359. if (options.processImported !== undefined) {
  360. console.error('AssetImporter: processImported is deprecated, use processRaw instead')
  361. options.processRaw = options.processImported
  362. }
  363. if (Array.isArray(res)) {
  364. const r: any[] = []
  365. for (const re of res) { // todo: can we parallelize?
  366. r.push(...await this.processRaw(re, options, path))
  367. }
  368. return r
  369. }
  370. if (options.processRaw === false) return [res]
  371. if (res.assetImporterProcessed && !options.forceImporterReprocess) return [res]
  372. this.dispatchEvent({type: 'processRawStart', data: res, options, path})
  373. // for testing only
  374. if (res.isTexture && options._testDataTextureComplete) {
  375. // if some data textures are not loading correctly, should not ideally be required
  376. if (res.isDataTexture && res.image?.data) res.image.complete = true
  377. if (res.image?.complete) res.needsUpdate = true
  378. }
  379. if (res.userData) {
  380. const userData: IImportResultUserData = res.userData
  381. const rootPath = res.__rootPath
  382. if (!userData.rootPath && rootPath && !rootPath.startsWith('blob:') && !rootPath.startsWith('/'))
  383. userData.rootPath = rootPath
  384. if (res.__rootBlob) {
  385. userData.__sourceBlob = res.__rootBlob
  386. if (userData.__needsSourceBuffer) { // set __sourceBuffer here if required during serialize later on, __needsSourceBuffer can be set in asset loaders
  387. userData.__sourceBuffer = await res.__rootBlob.arrayBuffer()
  388. delete userData.__needsSourceBuffer
  389. }
  390. }
  391. }
  392. // if (res.assetType) // todo: why if?
  393. res.assetImporterProcessed = true // this should not be put in userData
  394. this.dispatchEvent({type: 'processRaw', data: res, options, path})
  395. // special for zip files. ZipLoader gives this
  396. if ((<any>res) instanceof Map && options.autoImportZipContents !== false) {
  397. // todo: should we pass in onProgress from outside?
  398. return [...(await this.importFiles<T>(<any>res, options)).values()].flat()
  399. }
  400. return [res]
  401. }
  402. public async processRawSingle<T extends (ImportResult|undefined) = ImportResult>(res: T, options: ProcessRawOptions, path?: string): Promise<T> {
  403. return (await this.processRaw(res, options, path))[0]
  404. }
  405. // endregion
  406. // region disposal
  407. dispose(): void {
  408. this.clearCache()
  409. // this._processors?.dispose()
  410. // this._loadingManager.dispose // todo
  411. }
  412. /**
  413. * Clear memory asset and loader cache. Browser cache and custom cache storage is not cleared with this.
  414. */
  415. clearCache(): void {
  416. this._cachedAssets = []
  417. this.unregisterAllFiles()
  418. this.clearLoaderCache()
  419. }
  420. unregisterAllFiles(): void {
  421. const keys = [...this._fileDatabase.keys()]
  422. for (const key of keys) {
  423. this.unregisterFile(key)
  424. }
  425. }
  426. clearLoaderCache(): void {
  427. for (const lc of this._loaderCache) {
  428. lc.loader?.dispose && lc.loader?.dispose()
  429. }
  430. this._loaderCache = []
  431. }
  432. // endregion
  433. // region utils
  434. resolveURL(url: string): string {
  435. return this._loadingManager.resolveURL(url)
  436. }
  437. protected _urlModifier(url: string) {
  438. let normalizedURL = decodeURI(url)
  439. const rootUrl = this._rootContext?.rootUrl
  440. if (!normalizedURL.includes('://') && rootUrl && !normalizedURL.startsWith(rootUrl))
  441. normalizedURL = rootUrl + normalizedURL
  442. normalizedURL = normalizedURL.replace('./', '') // remove ./
  443. normalizedURL = normalizedURL.replace(/^(\/\/)/, '/') // fix for start with //
  444. // remove query string
  445. normalizedURL = normalizedURL.replace(/\?.*$/, '')
  446. const file = this._fileDatabase.get(normalizedURL)
  447. if (!file) return url
  448. const ext = file.ext
  449. if (!ext) {
  450. console.error('Unable to determine file extension', file)
  451. return url
  452. }
  453. if (!file.objectUrl) file.objectUrl = URL.createObjectURL(file) + '#' + normalizedURL
  454. return file.objectUrl
  455. }
  456. private _isRootFile(ext?: string, mime?: string) {
  457. mime = mime?.toLowerCase()
  458. ext = ext?.toLowerCase()
  459. return this.importers.find(value => value.root && (
  460. ext && value.ext.includes(ext.toLowerCase()) ||
  461. mime && value.mime.includes(mime.toLowerCase())
  462. )) != null
  463. }
  464. // get an importer that can create a loader
  465. private _getImporter(name:string, ext?:string, mime?: string, isRoot = false): IImporter | undefined {
  466. mime = mime?.toLowerCase()
  467. ext = ext?.toLowerCase()
  468. return this.importers.find(importer => {
  469. if (isRoot && !importer.root) return false
  470. if (mime && importer.mime?.find(m => mime === m)) return true
  471. if (importer.ext.find(iext =>
  472. ext && iext === ext
  473. || name?.toLowerCase()?.endsWith('.' + iext)
  474. || iext?.startsWith('data:') && name?.startsWith(iext))) return true
  475. return false
  476. })
  477. }
  478. // get a loader that can load a file.
  479. private _getLoader(name?:string, ext?:string, mime?: string): ILoader | undefined {
  480. if (!ext && !mime && name) ext = parseFileExtension(name).toLowerCase()
  481. mime = mime?.toLowerCase().trim()
  482. ext = ext?.toLowerCase().trim()
  483. return (name ? this._loadingManager.getHandler(name.trim()) as ILoader : undefined)
  484. || this._loaderCache.find((lc)=> ext && lc.ext.includes(ext) || mime && lc.mime.includes(mime))?.loader
  485. }
  486. private _createLoader(name:string, ext?:string, mime?: string): ILoader | undefined { // todo: remove/destroy loader.
  487. const importer = this._getImporter(name, ext, mime)
  488. if (!importer) return undefined
  489. const loader = importer.ctor(this)
  490. if (!loader) return undefined
  491. importer.ext.forEach(iext => {
  492. const regex = new RegExp(iext.startsWith('data:') ? '^' + iext + '\\/' : '\\.' + iext + '$', 'i')
  493. this._loadingManager.addHandler(regex, loader)
  494. })
  495. importer.mime?.forEach(imime => {
  496. const regex = new RegExp('^data:' + imime + '$', 'i')
  497. this._loadingManager.addHandler(regex, loader)
  498. })
  499. this._loaderCache.push({loader, ext: importer.ext, mime: importer.mime})
  500. this.dispatchEvent({type: 'loaderCreate', loader})
  501. return loader
  502. }
  503. addEventListener<T extends keyof IAssetImporterEventMap>(type: T, listener: EventListener<IAssetImporterEventMap[T], T, this>): void {
  504. super.addEventListener(type, listener)
  505. if (type === 'loaderCreate') {
  506. for (const loaderCacheElement of this._loaderCache) {
  507. this.dispatchEvent({type: 'loaderCreate', loader: loaderCacheElement.loader})
  508. }
  509. }
  510. }
  511. // endregion
  512. // region Loader Event Dispatchers
  513. protected _onLoad() {
  514. this.dispatchEvent({type: 'onLoad'})
  515. }
  516. protected _onProgress(url: string, loaded: number, total: number) {
  517. this.dispatchEvent({type: 'onProgress', url, loaded, total})
  518. }
  519. protected _onError(url: string) {
  520. this.dispatchEvent({type: 'onError', url})
  521. }
  522. protected _onStart(url: string, loaded: number, total: number) {
  523. this.dispatchEvent({type: 'onStart', url, loaded, total})
  524. }
  525. // endregion
  526. // region deprecated
  527. /**
  528. * @deprecated use {@link processRaw} instead
  529. * @param res
  530. * @param options
  531. */
  532. public async processImported(res: any, options: ProcessRawOptions, path?: string): Promise<any[]> {
  533. console.error('processImported is deprecated. Use processRaw instead.')
  534. return await this.processRaw(res, options, path)
  535. }
  536. // endregion
  537. }