threepipe
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

AssetManager.ts 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. import {ImportAssetOptions, ImportResult, ProcessRawOptions, RootSceneImportResult} from './IAssetImporter'
  2. import {
  3. BaseEvent,
  4. Cache as threeCache,
  5. Camera,
  6. EventDispatcher,
  7. Light,
  8. LinearFilter,
  9. LinearMipmapLinearFilter,
  10. LoadingManager,
  11. PerspectiveCamera,
  12. TextureLoader,
  13. } from 'three'
  14. import {ISerializedConfig, IViewerPlugin, ThreeViewer} from '../viewer'
  15. import {AssetImporter} from './AssetImporter'
  16. import {generateUUID, getTextureDataType, overrideThreeCache} from '../three'
  17. import {IAsset} from './IAsset'
  18. import {
  19. AddObjectOptions,
  20. AmbientLight2,
  21. DirectionalLight2,
  22. HemisphereLight2,
  23. ICamera,
  24. iCameraCommons,
  25. ILight,
  26. iLightCommons,
  27. IMaterial,
  28. iMaterialCommons,
  29. IObject3D,
  30. iObjectCommons,
  31. ISceneEvent,
  32. ITexture,
  33. PerspectiveCamera2,
  34. PointLight2,
  35. RectAreaLight2,
  36. SpotLight2,
  37. upgradeTexture,
  38. } from '../core'
  39. import {Importer} from './Importer'
  40. import {MaterialManager} from './MaterialManager'
  41. import {DRACOLoader2, GLTFLoader2, JSONMaterialLoader, MTLLoader2, OBJLoader2, ZipLoader} from './import'
  42. import {RGBELoader} from 'three/examples/jsm/loaders/RGBELoader.js'
  43. import {FBXLoader} from 'three/examples/jsm/loaders/FBXLoader.js'
  44. import {EXRLoader} from 'three/examples/jsm/loaders/EXRLoader.js'
  45. import {Class, ValOrArr} from 'ts-browser-helpers'
  46. import {ILoader} from './IImporter'
  47. import {AssetExporter} from './AssetExporter'
  48. import {IExporter} from './IExporter'
  49. import {GLTFExporter2} from './export'
  50. export interface AssetManagerOptions{
  51. /**
  52. * simple memory based cache for downloaded files, default = false
  53. */
  54. simpleCache?: boolean
  55. /**
  56. * Cache Storage for downloaded files, can use with `caches.open`
  57. * When true and by default uses `caches.open('threepipe-assetmanager')`, set to false to disable
  58. * @default true
  59. */
  60. storage?: Cache | Storage | boolean
  61. }
  62. export interface AddAssetOptions extends AddObjectOptions{
  63. /**
  64. * Automatically set any loaded HDR, EXR file as the scene environment map
  65. * @default true
  66. */
  67. autoSetEnvironment?: boolean
  68. /**
  69. * Automatically set any loaded image(ITexture) file as the scene background
  70. */
  71. autoSetBackground?: boolean
  72. }
  73. export type ImportAddOptions = ImportAssetOptions & AddAssetOptions
  74. export type AddRawOptions = ProcessRawOptions & AddAssetOptions
  75. /**
  76. * Asset Manager
  77. *
  78. * Utility class to manage import, export, and material management.
  79. * @category Asset Manager
  80. */
  81. export class AssetManager extends EventDispatcher<BaseEvent&{data: ImportResult}, 'loadAsset'> {
  82. readonly viewer: ThreeViewer
  83. readonly importer: AssetImporter
  84. readonly exporter: AssetExporter
  85. readonly materials: MaterialManager
  86. private _storage?: Cache | Storage
  87. get storage() {return this._storage}
  88. constructor(viewer: ThreeViewer, {simpleCache = false, storage}: AssetManagerOptions = {}) {
  89. super()
  90. this._sceneUpdated = this._sceneUpdated.bind(this)
  91. this.addAsset = this.addAsset.bind(this)
  92. this.addRaw = this.addRaw.bind(this)
  93. this.addImported = this.addImported.bind(this)
  94. this.importer = new AssetImporter(!!viewer.getPlugin('debug'))
  95. this.exporter = new AssetExporter()
  96. this.materials = new MaterialManager()
  97. this.viewer = viewer
  98. this.viewer.scene.addEventListener('addSceneObject', this._sceneUpdated)
  99. this.viewer.scene.addEventListener('materialChanged', this._sceneUpdated)
  100. this.viewer.scene.addEventListener('beforeDeserialize', this._sceneUpdated)
  101. this._initCacheStorage(simpleCache, storage ?? true)
  102. this.importer.addEventListener('processRaw', (event)=>{
  103. // console.log('preprocess mat', mat)
  104. const mat = event.data as IMaterial
  105. if (!mat || !mat.isMaterial || !mat.uuid) return
  106. if (this.materials?.findMaterial(mat.uuid)) {
  107. console.warn('imported material uuid already exists, creating new uuid')
  108. mat.uuid = generateUUID()
  109. if (mat.userData.uuid) mat.userData.uuid = mat.uuid
  110. }
  111. // todo: check for name exists also
  112. this.materials.registerMaterial(mat)
  113. })
  114. this.importer.addEventListener('processRawStart', (event)=>{
  115. // console.log('preprocess mat', mat)
  116. const res = event.data!
  117. const options = event.options! as ProcessRawOptions
  118. // if (!res.assetType) {
  119. // if (res.isBufferGeometry) { // for eg stl todo
  120. // res = new Mesh(res, new MeshStandardMaterial())
  121. // }
  122. // if (res.isObject3D) {
  123. // }
  124. // }
  125. if (res.isObject3D) {
  126. const cameras: Camera[] = []
  127. const lights: Light[] = []
  128. res.traverse((obj: any) => {
  129. if (obj.material) {
  130. const materials = Array.isArray(obj.material) ? obj.material : [obj.material]
  131. const newMaterials = []
  132. for (const material of materials) {
  133. const mat = this.materials.convertToIMaterial(material, {createFromTemplate: options.replaceMaterials !== false}) || material
  134. mat.uuid = material.uuid
  135. mat.userData.uuid = material.uuid
  136. newMaterials.push(mat)
  137. }
  138. if (Array.isArray(obj.material)) obj.material = newMaterials
  139. else obj.material = newMaterials[0]
  140. }
  141. if (obj.isCamera) cameras.push(obj)
  142. if (obj.isLight) lights.push(obj)
  143. })
  144. for (const camera of cameras) {
  145. if ((camera as PerspectiveCamera2).assetType === 'camera') continue
  146. // todo: OrthographicCamera
  147. if (!(camera as PerspectiveCamera).isPerspectiveCamera || !camera.parent || options.replaceCameras === false) {
  148. iCameraCommons.upgradeCamera.call(camera)
  149. } else {
  150. const newCamera: ICamera = (camera as any).iCamera ??
  151. new PerspectiveCamera2('', this.viewer.canvas)
  152. if (camera === newCamera) continue
  153. camera.parent.children.splice(camera.parent.children.indexOf(camera), 1, newCamera)
  154. newCamera.parent = camera.parent as any
  155. newCamera.copy(camera as any)
  156. camera.parent = null
  157. ;(newCamera as any).uuid = camera.uuid
  158. newCamera.userData.uuid = camera.uuid
  159. ;(camera as any).iCamera = newCamera
  160. // console.log('replacing camera', camera, newCamera)
  161. }
  162. }
  163. for (const light of lights) {
  164. // @ts-expect-error update three-ts-types
  165. if ((light as ILight).assetType === 'light') continue
  166. if (!light.parent || options.replaceLights === false) {
  167. iLightCommons.upgradeLight.call(light)
  168. } else {
  169. const newLight: ILight|undefined = (light as any).iLight ??
  170. (light as any).isDirectionalLight ? new DirectionalLight2() :
  171. (light as any).isPointLight ? new PointLight2() :
  172. (light as any).isSpotLight ? new SpotLight2() :
  173. (light as any).isAmbientLight ? new AmbientLight2() :
  174. (light as any).isHemisphereLight ? new HemisphereLight2() :
  175. (light as any).isRectAreaLight ? new RectAreaLight2() :
  176. undefined
  177. // @ts-expect-error update three-ts-types
  178. if (light === newLight || !newLight) continue
  179. light.parent.children.splice(light.parent.children.indexOf(light), 1, newLight)
  180. newLight.parent = light.parent as any
  181. newLight.copy(light as any)
  182. light.parent = null
  183. ;(newLight as any).uuid = light.uuid
  184. newLight.userData.uuid = light.uuid
  185. ;(light as any).iLight = newLight
  186. }
  187. }
  188. iObjectCommons.upgradeObject3D.call(res)
  189. } else if (res.isMaterial) {
  190. iMaterialCommons.upgradeMaterial.call(res)
  191. // todo update res by generating new material?
  192. } else if (res.isTexture) {
  193. upgradeTexture.call(res)
  194. if (event?.options?.generateMipmaps !== undefined)
  195. res.generateMipmaps = event?.options.generateMipmaps
  196. if (!res.generateMipmaps && !res.isRenderTargetTexture) { // todo: do we need to check more?
  197. res.minFilter = res.minFilter === LinearMipmapLinearFilter ? LinearFilter : res.minFilter
  198. res.magFilter = res.magFilter === LinearMipmapLinearFilter ? LinearFilter : res.magFilter
  199. }
  200. }
  201. // todo other asset/object types?
  202. })
  203. this._addImporters()
  204. this._addExporters()
  205. }
  206. async addAsset<T extends ImportResult = ImportResult>(assetOrPath?: string | IAsset | IAsset[] | File | File[], options?: ImportAddOptions): Promise<(T|undefined)[]> {
  207. if (!this.importer || !this.viewer) return []
  208. const imported = await this.importer.import<T>(assetOrPath, options)
  209. if (!imported) {
  210. console.warn('Unable to import', assetOrPath, imported)
  211. return []
  212. }
  213. return this.loadImported<(T|undefined)[]>(imported, options)
  214. }
  215. // materials: IMaterial[] = []
  216. // textures: ITexture[] = []
  217. async loadImported<T extends ValOrArr<ImportResult|undefined> = ImportResult>(imported: T, {autoSetEnvironment = true, autoSetBackground = false, ...options}: AddAssetOptions = {}): Promise<T | never[]> {
  218. const arr: (ImportResult|undefined)[] = Array.isArray(imported) ? imported : [imported]
  219. let ret: T = Array.isArray(imported) ? [] : undefined as any
  220. for (const obj of arr) {
  221. if (!obj) {
  222. if (Array.isArray(ret)) ret.push(undefined)
  223. continue
  224. }
  225. let r = obj
  226. switch (obj.assetType) {
  227. case 'material':
  228. this.materials.registerMaterial(<IMaterial>obj)
  229. break
  230. case 'texture':
  231. if (autoSetEnvironment && (
  232. obj.__rootPath?.endsWith('.hdr') || obj.__rootPath?.endsWith('.exr')
  233. )) this.viewer.scene.environment = <ITexture>obj
  234. if (autoSetBackground) this.viewer.scene.background = <ITexture>obj
  235. break
  236. case 'model':
  237. case 'light':
  238. case 'camera':
  239. r = await this.viewer.addSceneObject(<IObject3D|RootSceneImportResult>obj, options) // todo update references in scene update event
  240. break
  241. case 'config':
  242. if (options?.importConfig !== false) await this.viewer.importConfig(<ISerializedConfig>obj)
  243. break
  244. default:
  245. // legacy
  246. if (obj.type && typeof obj.type === 'string' && (Array.isArray((obj as any).plugins) ||
  247. (obj as any).type === 'ThreeViewer' || this.viewer.getPlugin((obj as any).type))) {
  248. await this.viewer.importConfig(<ISerializedConfig>obj)
  249. }
  250. break
  251. }
  252. this.dispatchEvent({type: 'loadAsset', data: obj})
  253. if (Array.isArray(ret)) ret.push(r)
  254. else ret = r as T
  255. }
  256. return ret || []
  257. }
  258. /**
  259. * same as {@link loadImported}
  260. * @param imported
  261. * @param options
  262. */
  263. async addProcessedAssets<T extends ImportResult|undefined = ImportResult>(imported: (T|undefined)[], options?: AddAssetOptions): Promise<(T | undefined)[]> {
  264. return this.loadImported(imported, options)
  265. }
  266. async addAssetSingle<T extends ImportResult = ImportResult>(asset?: string | IAsset | File, options?: ImportAssetOptions): Promise<T|undefined> {
  267. return !asset ? undefined : (await this.addAsset<T>(asset, options))?.[0]
  268. }
  269. // processAndAddObjects
  270. async addRaw<T extends (ImportResult|undefined) = ImportResult>(res: T|T[], options: AddRawOptions = {}): Promise<(T|undefined)[]> {
  271. const r = await this.importer.processRaw<T>(res, options)
  272. return this.loadImported<T[]>(r, options)
  273. }
  274. async addRawSingle<T extends ImportResult|undefined = ImportResult|undefined>(res: T, options: AddRawOptions = {}): Promise<T|undefined> {
  275. return (await this.addRaw<T>(res, options))?.[0]
  276. }
  277. private _sceneUpdated(event: ISceneEvent) { // todo: check if objects are added some other way.
  278. if (event.type === 'addSceneObject') {
  279. const target = event.object as ImportResult
  280. switch (target.assetType) {
  281. case 'material':
  282. this.materials.registerMaterial(<IMaterial>target)
  283. break
  284. case 'texture':
  285. break
  286. case 'model':
  287. case 'light':
  288. case 'camera':
  289. break
  290. default:
  291. break
  292. }
  293. } else if (event.type === 'materialChanged') {
  294. const target = event.material as IMaterial | IMaterial[] | undefined
  295. const targets = Array.isArray(target) ? target : target ? [target] : []
  296. for (const t of targets) {
  297. this.materials.registerMaterial(t)
  298. }
  299. } else if (event.type === 'beforeDeserialize') {
  300. // object/material/texture to be deserialized
  301. const data = event.data
  302. const meta = event.meta
  303. if (!data.metadata) {
  304. console.warn('Invalid data(no metadata)', data)
  305. }
  306. if (event.material) {
  307. if (data.metadata?.type !== 'Material') {
  308. console.warn('Invalid material data', data)
  309. }
  310. JSONMaterialLoader.DeserializeMaterialJSON(data, this.viewer, meta, event.material).then(()=>{
  311. //
  312. })
  313. }
  314. } else {
  315. console.error('Unexpected')
  316. }
  317. }
  318. dispose() {
  319. this.importer.dispose()
  320. this.materials.dispose()
  321. this.viewer.scene.removeEventListener('addSceneObject', this._sceneUpdated)
  322. this.viewer.scene.removeEventListener('materialChanged', this._sceneUpdated)
  323. this.exporter.dispose()
  324. }
  325. protected _addImporters() {
  326. const viewer = this.viewer
  327. if (!viewer) return
  328. const importers: Importer[] = [
  329. new Importer(TextureLoader, ['webp', 'png', 'jpeg', 'jpg', 'svg', 'ico', 'data:image', 'avif'], [
  330. 'image/webp', 'image/png', 'image/jpeg', 'image/svg+xml', 'image/gif', 'image/bmp', 'image/tiff', 'image/x-icon', 'image/avif',
  331. ], false), // todo: use ImageBitmapLoader if supported (better performance)
  332. new Importer<JSONMaterialLoader>(JSONMaterialLoader,
  333. ['mat', ...this.materials.templates.map(t=>t.typeSlug!).filter(v=>v)], // todo add others
  334. [], false, (loader)=>{
  335. if (loader) loader.viewer = this.viewer
  336. return loader
  337. }),
  338. new Importer(class extends RGBELoader {
  339. constructor(manager: LoadingManager) {
  340. super(manager)
  341. this.setDataType(getTextureDataType(viewer.renderManager.renderer))
  342. }
  343. }, ['hdr'], ['image/vnd.radiance'], false),
  344. new Importer(class extends EXRLoader {
  345. constructor(manager: LoadingManager) {
  346. super(manager)
  347. this.setDataType(getTextureDataType(viewer.renderManager.renderer))
  348. }
  349. }, ['exr'], ['image/x-exr'], false),
  350. new Importer(FBXLoader, ['fbx'], ['model/fbx'], true),
  351. new Importer(ZipLoader, ['zip', 'glbz', 'gltfz'], ['application/zip', 'data:model/gltf+zip'], true), // gltfz and glbz are invented zip files with gltf/glb inside along with resources
  352. new Importer(OBJLoader2 as any as Class<ILoader>, ['obj'], ['model/obj'], true),
  353. new Importer(MTLLoader2 as any as Class<ILoader>, ['mtl'], ['model/mtl'], false),
  354. new Importer<GLTFLoader2>(GLTFLoader2, ['gltf', 'glb', 'data:model/gltf'], ['model/gltf', 'model/gltf+json', 'model/gltf-binary'], true, (l, _, i) => l?.setup(this.viewer, i.extensions)),
  355. new Importer(DRACOLoader2, ['drc'], ['model/mesh+draco'], true),
  356. ]
  357. this.importer.addImporter(...importers)
  358. }
  359. protected _addExporters() {
  360. const exporters: IExporter[] = [
  361. {ext: ['gltf', 'glb'], extensions: [], ctor: (_, exporter)=>{
  362. const ex = new GLTFExporter2()
  363. // This should be added at the end.
  364. ex.setup(this.viewer, exporter.extensions)
  365. return ex
  366. }},
  367. ]
  368. this.exporter.addExporter(...exporters)
  369. }
  370. private _initCacheStorage(simpleCache?: boolean, storage?: Cache | Storage | boolean) {
  371. if (storage === true && window?.caches) {
  372. window.caches.open?.('threepipe-assetmanager').then(c => {
  373. this._initCacheStorage(simpleCache, c)
  374. this._storage = c
  375. })
  376. return
  377. }
  378. if (simpleCache || storage) {
  379. // three.js built-in simple memory cache. used in FileLoader.js todo: use local storage somehow
  380. if (simpleCache) threeCache.enabled = true
  381. if (storage && window.Cache && typeof window.Cache === 'function' && storage instanceof window.Cache) {
  382. overrideThreeCache(storage)
  383. // todo: clear cache
  384. }
  385. }
  386. this._storage = typeof storage === 'boolean' ? undefined : storage
  387. }
  388. // region deprecated
  389. /**
  390. * @deprecated use addRaw instead
  391. * @param res
  392. * @param options
  393. */
  394. async addImported<T extends (ImportResult|undefined) = ImportResult>(res: T|T[], options: AddRawOptions = {}): Promise<(T|undefined)[]> {
  395. console.error('addImported is deprecated, use addRaw instead')
  396. return this.addRaw(res, options)
  397. }
  398. /**
  399. * @deprecated use addAsset instead
  400. * @param path
  401. * @param options
  402. */
  403. public async addFromPath(path: string, options: ImportAddOptions = {}): Promise<any[]> {
  404. console.error('addFromPath is deprecated, use addAsset instead')
  405. return this.addAsset(path, options)
  406. }
  407. /**
  408. * @deprecated use {@link ThreeViewer.exportConfig} instead
  409. * @param binary - if set to false, encodes all the array buffers to base64
  410. */
  411. exportViewerConfig(binary = true): Record<string, any> {
  412. if (!this.viewer) return {}
  413. console.error('exportViewerConfig is deprecated, use viewer.toJSON instead')
  414. return this.viewer.toJSON(binary, undefined)
  415. }
  416. /**
  417. * @deprecated use {@link ThreeViewer.exportPluginsConfig} instead
  418. * @param filter
  419. */
  420. exportPluginPresets(filter?: string[]) {
  421. console.error('exportPluginPresets is deprecated, use viewer.exportPluginsConfig instead')
  422. return this.viewer?.exportPluginsConfig(filter)
  423. }
  424. /**
  425. * @deprecated use {@link ThreeViewer.exportPluginConfig} instead
  426. * @param plugin
  427. */
  428. exportPluginPreset(plugin: IViewerPlugin) {
  429. console.error('exportPluginPreset is deprecated, use viewer.exportPluginConfig instead')
  430. return this.viewer?.exportPluginConfig(plugin)
  431. }
  432. /**
  433. * @deprecated use {@link ThreeViewer.importPluginConfig} instead
  434. * @param json
  435. * @param plugin
  436. */
  437. async importPluginPreset(json: any, plugin?: IViewerPlugin) {
  438. console.error('importPluginPreset is deprecated, use viewer.importPluginConfig instead')
  439. return this.viewer?.importPluginConfig(json, plugin)
  440. }
  441. // todo continue from here by moving functions to the viewer.
  442. /**
  443. * @deprecated use {@link ThreeViewer.importConfig} instead
  444. * @param viewerConfig
  445. */
  446. async importViewerConfig(viewerConfig: any) {
  447. return this.viewer?.importConfig(viewerConfig)
  448. }
  449. /**
  450. * @deprecated use {@link ThreeViewer.fromJSON} instead
  451. * @param viewerConfig
  452. */
  453. applyViewerConfig(viewerConfig: any, resources?: any) {
  454. console.error('applyViewerConfig is deprecated, use viewer.fromJSON instead')
  455. return this.viewer?.fromJSON(viewerConfig, resources)
  456. }
  457. /**
  458. * @deprecated moved to {@link ThreeViewer.loadConfigResources}
  459. * @param json
  460. * @param extraResources - preloaded resources in the format of viewer config resources.
  461. */
  462. async importConfigResources(json: any, extraResources?: any) {
  463. if (!this.importer) throw 'Importer not initialized yet.'
  464. if (json.__isLoadedResources) return json
  465. return this.viewer?.loadConfigResources(json, extraResources)
  466. }
  467. /**
  468. * @deprecated not a plugin anymore
  469. */
  470. static readonly PluginType = 'AssetManager'
  471. // endregion
  472. }