threepipe
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

AssetImporter.ts 22KB

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