threepipe
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ThreeViewer.ts 43KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097
  1. import {BaseEvent, Color, Event, EventDispatcher, LinearSRGBColorSpace, Object3D, Vector2} from 'three'
  2. import {Class, createCanvasElement, onChange, serialize} from 'ts-browser-helpers'
  3. import {TViewerScreenShader} from '../postprocessing'
  4. import {
  5. AddObjectOptions,
  6. IAnimationLoopEvent,
  7. IMaterial,
  8. IObject3D,
  9. IObjectProcessor,
  10. ITexture,
  11. PerspectiveCamera2,
  12. RootScene,
  13. } from '../core'
  14. import {ViewerRenderManager} from './ViewerRenderManager'
  15. import {
  16. convertArrayBufferToStringsInMeta,
  17. getEmptyMeta,
  18. GLStatsJS,
  19. IDialogWrapper,
  20. jsonToBlob,
  21. metaFromResources,
  22. MetaImporter,
  23. metaToResources,
  24. SerializationMetaType,
  25. SerializationResourcesType,
  26. ThreeSerialization,
  27. windowDialogWrapper,
  28. } from '../utils'
  29. import {
  30. AssetManager,
  31. AssetManagerOptions,
  32. BlobExt,
  33. ExportFileOptions,
  34. IAsset,
  35. ImportAddOptions,
  36. ImportAssetOptions,
  37. ImportResult,
  38. RootSceneImportResult,
  39. } from '../assetmanager'
  40. import {IViewerPlugin, IViewerPluginSync} from './IViewerPlugin'
  41. // noinspection ES6PreferShortImport
  42. import {DropzonePlugin, DropzonePluginOptions} from '../plugins/interaction/DropzonePlugin'
  43. import {uiConfig, uiFolderContainer, UiObjectConfig} from 'uiconfig.js'
  44. import {IRenderTarget} from '../rendering'
  45. export type IViewerEvent = BaseEvent & {
  46. type: 'update'|'preRender'|'postRender'|'preFrame'|'postFrame'|'dispose'|'addPlugin'|'renderEnabled'|'renderDisabled'
  47. }
  48. export type IViewerEventTypes = IViewerEvent['type']
  49. export interface ISerializedConfig {
  50. assetType: 'config',
  51. type: string,
  52. metadata?: {
  53. generator: string,
  54. version: number,
  55. [key: string]: any
  56. },
  57. [key: string]: any
  58. }
  59. export interface ISerializedViewerConfig extends ISerializedConfig{
  60. type: 'ThreeViewer'|'ViewerApp',
  61. version: string,
  62. plugins: ISerializedConfig[],
  63. resources?: Partial<SerializationResourcesType> | SerializationMetaType
  64. renderManager?: any // todo
  65. scene?: any
  66. [key: string]: any
  67. }
  68. export type IConsoleWrapper = Partial<Console> & Pick<Console, 'log'|'warn'|'error'>
  69. /**
  70. * Options for the ThreeViewer creation.
  71. * @category Viewer
  72. */
  73. export interface ThreeViewerOptions {
  74. /**
  75. * The canvas element to use for rendering. Only one of container and canvas must be specified.
  76. */
  77. canvas?: HTMLCanvasElement,
  78. /**
  79. * The container for the canvas. A new canvas will be created in this container. Only one of container and canvas must be specified.
  80. */
  81. container?: HTMLElement,
  82. /**
  83. * The fragment shader snippet to render on screen.
  84. */
  85. screenShader?: TViewerScreenShader,
  86. /**
  87. * Use MSAA.
  88. */
  89. msaa?: boolean,
  90. /**
  91. * Use RGBM HDR Pipeline
  92. */
  93. rgbm?: boolean
  94. /**
  95. * Use rendered gbuffer as depth-prepass / z-prepass.
  96. */
  97. zPrepass?: boolean
  98. debug?: boolean
  99. /**
  100. * Options for the asset manager.
  101. */
  102. assetManager?: AssetManagerOptions
  103. /**
  104. * Add the dropzone plugin to the viewer, allowing to drag and drop files into the viewer over the canvas/container.
  105. * Set to true/false to enable/disable the plugin, or pass options to configure the plugin. Assuming true if options are passed.
  106. * @default - false
  107. */
  108. dropzone?: boolean|DropzonePluginOptions
  109. /**
  110. * @deprecated use {@link msaa} instead
  111. */
  112. isAntialiased?: boolean,
  113. /**
  114. * @deprecated use {@link rgbm} instead
  115. */
  116. useRgbm?: boolean
  117. /**
  118. * @deprecated use {@link zPrepass} instead
  119. */
  120. useGBufferDepth?: boolean
  121. }
  122. const VIEWER_VERSION = '0.0.1'
  123. /**
  124. * The ThreeViewer is the main class in the framework.
  125. * @category Viewer
  126. */
  127. @uiFolderContainer('Viewer')
  128. export class ThreeViewer extends EventDispatcher<IViewerEvent, IViewerEventTypes> {
  129. public static readonly VERSION = VIEWER_VERSION
  130. public static readonly ConfigTypeSlug = 'vjson'
  131. uiConfig!: UiObjectConfig
  132. static Console: IConsoleWrapper = {
  133. log: console.log.bind(console),
  134. warn: console.warn.bind(console),
  135. error: console.error.bind(console),
  136. }
  137. static Dialog: IDialogWrapper = windowDialogWrapper
  138. renderStats: GLStatsJS
  139. readonly assetManager: AssetManager
  140. get console(): IConsoleWrapper {
  141. return ThreeViewer.Console
  142. }
  143. get dialog(): IDialogWrapper {
  144. return ThreeViewer.Dialog
  145. }
  146. @serialize() readonly type = 'ThreeViewer'
  147. private readonly _canvas: HTMLCanvasElement
  148. // this can be used by other plugins to add ui elements alongside the canvas
  149. private readonly _container: HTMLElement // todo: add a way to move the canvas to a new container... and dispatch event...
  150. @uiConfig() @serialize('renderManager')
  151. readonly renderManager: ViewerRenderManager
  152. /**
  153. * The Scene attached to the viewer, this cannot be changed.
  154. * @type {RootScene}
  155. */
  156. @uiConfig() @serialize('scene')
  157. private readonly _scene: RootScene
  158. public readonly plugins: Record<string, IViewerPlugin> = {}
  159. private _needsResize = false
  160. /**
  161. * If the viewer is enabled. Set this `false` to disable RAF loop.
  162. * @type {boolean}
  163. */
  164. enabled = true
  165. /**
  166. * Enable or disable all rendering, Animation loop including any frame/render events won't be fired when this is false.
  167. */
  168. @onChange(ThreeViewer.prototype._renderEnabledChanged)
  169. renderEnabled = true
  170. private _isRenderingFrame = false
  171. /**
  172. * Specifies how many frames to render in a single request animation frame. Keep to 1 for realtime rendering.
  173. * Note: should be max (screen refresh rate / animation frame rate) like 60Hz / 30fps
  174. * @type {number}
  175. */
  176. public maxFramePerLoop = 1
  177. get scene(): RootScene {
  178. return this._scene
  179. }
  180. /**
  181. * The ResizeObserver observing the canvas element. Add more elements to this observer to resize viewer on their size change.
  182. * @type {ResizeObserver | undefined}
  183. */
  184. readonly resizeObserver = window?.ResizeObserver ? new window.ResizeObserver(_ => this.resize()) : undefined
  185. readonly debug: boolean
  186. /**
  187. * Create a viewer instance for using the webgi viewer SDK.
  188. * @param options - {@link ThreeViewerOptions}
  189. */
  190. constructor({debug = true, ...options}: ThreeViewerOptions) {
  191. super()
  192. this.debug = debug
  193. this._canvas = options.canvas || createCanvasElement()
  194. let container = options.container
  195. if (container && !options.canvas) container.appendChild(this._canvas)
  196. if (!container) container = this._canvas.parentElement ?? undefined
  197. if (!container) throw new Error('No container.')
  198. this._container = container
  199. this.setDirty = this.setDirty.bind(this)
  200. this._animationLoop = this._animationLoop.bind(this)
  201. this._setActiveCameraView = this._setActiveCameraView.bind(this)
  202. this.renderStats = new GLStatsJS(this._container)
  203. if (debug) this.renderStats.show()
  204. if (!(window as any).threeViewers) (window as any).threeViewers = [];
  205. (window as any).threeViewers.push(this)
  206. // camera
  207. const camera = new PerspectiveCamera2('orbit', this._canvas)
  208. camera.name = 'Default Camera'
  209. camera.position.set(0, 0, 5)
  210. camera.userData.autoLookAtTarget = true
  211. this.addEventListener('postFrame', () => { // todo: move inside RootScene.
  212. const cam = this._scene.mainCamera
  213. if (cam && cam.canUserInteract) {
  214. // todo
  215. // const d = this.getPluginByType<ProgressivePlugin>('Progressive')?.postFrameConvergedRecordingDelta()
  216. // // if (d && d > 0) delta = d
  217. // if (d !== undefined && d === 0) return // not converged yet.
  218. // // if d < 0 or undefined: not recording, do nothing
  219. cam.controls?.update()
  220. }
  221. })
  222. // scene
  223. this._scene = new RootScene(camera, this._objectProcessor)
  224. this._scene.setBackgroundColor('#ffffff')
  225. // this._scene.addEventListener('addSceneObject', this._addSceneObject)
  226. this._scene.addEventListener('setView', this._setActiveCameraView)
  227. this._scene.addEventListener('activateMain', this._setActiveCameraView)
  228. this._scene.addEventListener('materialUpdate', (e) => this.setDirty(this._scene, e))
  229. this._scene.addEventListener('materialChanged', (e) => this.setDirty(this._scene, e))
  230. this._scene.addEventListener('objectUpdate', (e) => this.setDirty(this._scene, e))
  231. this._scene.addEventListener('textureUpdate', (e) => this.setDirty(this._scene, e))
  232. this._scene.addEventListener('sceneUpdate', (e) => {
  233. this.setDirty(this._scene, e)
  234. if (e.geometryChanged === false) return
  235. this.renderManager.resetShadows()
  236. })
  237. // render manager
  238. if (options.isAntialiased !== undefined || options.useRgbm !== undefined || options.useGBufferDepth !== undefined) {
  239. this.console.warn('isAntialiased, useRgbm and useGBufferDepth are deprecated, use msaa, rgbm and zPrepass instead.')
  240. }
  241. this.renderManager = new ViewerRenderManager({
  242. canvas: this._canvas,
  243. msaa: options.msaa ?? options.isAntialiased ?? false,
  244. rgbm: options.rgbm ?? options.useRgbm ?? false,
  245. zPrepass: options.zPrepass ?? options.useGBufferDepth ?? false,
  246. depthBuffer: !(options.zPrepass ?? options.useGBufferDepth ?? false),
  247. screenShader: options.screenShader,
  248. })
  249. this.renderManager.addEventListener('animationLoop', this._animationLoop as any)
  250. this.renderManager.addEventListener('resize', ()=> this._scene.mainCamera.refreshAspect())
  251. this.renderManager.addEventListener('update', (e) => {
  252. if (e.change === 'registerPass' && e.pass?.materialExtension)
  253. this.assetManager.materials.registerMaterialExtension(e.pass.materialExtension)
  254. else if (e.change === 'unregisterPass' && e.pass?.materialExtension)
  255. this.assetManager.materials.unregisterMaterialExtension(e.pass.materialExtension)
  256. this.setDirty(this.renderManager, e)
  257. })
  258. this.assetManager = new AssetManager(this, options.assetManager)
  259. if (this.resizeObserver) this.resizeObserver.observe(this._canvas)
  260. // sometimes resize observer is late, so extra check
  261. window && window.addEventListener('resize', this.resize)
  262. this._canvas.addEventListener('webglcontextrestored', this._onContextRestore, false)
  263. this._canvas.addEventListener('webglcontextlost', this._onContextLost, false)
  264. if (options.dropzone) {
  265. this.addPluginSync(new DropzonePlugin(typeof options.dropzone === 'object' ? options.dropzone : undefined))
  266. }
  267. this.console.log('ThreePipe Viewer instance initialized, version: ', ThreeViewer.VERSION)
  268. }
  269. private _objectProcessor: IObjectProcessor = {
  270. processObject: (object: IObject3D)=>{
  271. if (object.material) {
  272. if (Array.isArray(object.material)) this.assetManager.materials.registerMaterials(object.material)
  273. else this.assetManager.materials.registerMaterial(object.material)
  274. }
  275. },
  276. }
  277. // todo: find a better fix for context loss and restore?
  278. private _lastSize = new Vector2()
  279. private _onContextRestore = (_: Event) => {
  280. this.enabled = true
  281. this._canvas.width = this._lastSize.width
  282. this._canvas.height = this._lastSize.height
  283. this.resize()
  284. this._scene.setDirty({refreshScene: true, frameFade: false})
  285. }
  286. private _onContextLost = (_: Event) => {
  287. this._lastSize.set(this._canvas.width, this._canvas.height)
  288. this._canvas.width = 2
  289. this._canvas.height = 2
  290. this.resize()
  291. this.enabled = false
  292. }
  293. /**
  294. * Mark that the canvas is resized. If the size is changed, the renderer and all render targets are resized. This happens before the render of the next frame.
  295. */
  296. resize = () => {
  297. this._needsResize = true
  298. this.setDirty()
  299. }
  300. private _needsReset = true // renderer reset
  301. /**
  302. * Set the viewer to dirty and trigger render of the next frame.
  303. * @param source - The source of the dirty event. like plugin or 3d object
  304. * @param event - The event that triggered the dirty event.
  305. */
  306. setDirty(source?: any, event?: Event): void {
  307. this._needsReset = true
  308. source = source ?? this
  309. this.dispatchEvent({...event ?? {}, type: 'update', source})
  310. }
  311. /**
  312. * The renderer for the viewer that's attached to the canvas. This is wrapper around WebGLRenderer and EffectComposer and manages post-processing passes and rendering logic
  313. * @deprecated - use {@link renderManager} instead
  314. */
  315. get renderer(): ViewerRenderManager {
  316. this.console.error('renderer is deprecated, use renderManager instead')
  317. return this.renderManager
  318. }
  319. /**
  320. * Add an object/model/material/viewer-config/plugin-preset/... to the viewer scene from url or an {@link IAsset} object.
  321. * Same as {@link AssetManager.addAssetSingle}
  322. * @param obj
  323. * @param options
  324. */
  325. async load<T extends ImportResult = ImportResult>(obj: string | IAsset | null, options?: ImportAddOptions) {
  326. if (!obj) return
  327. return await this.assetManager.addAssetSingle<T>(obj, options)
  328. }
  329. /**
  330. * Imports an object/model/material/texture/viewer-config/plugin-preset/... to the viewer scene from url or an {@link IAsset} object.
  331. * Same as {@link AssetImporter.importSingle}
  332. * @param obj
  333. * @param options
  334. */
  335. async import<T extends ImportResult = ImportResult>(obj: string | IAsset | null, options?: ImportAddOptions) {
  336. if (!obj) return
  337. return await this.assetManager.importer.importSingle<T>(obj, options)
  338. }
  339. /**
  340. * Exports an object/mesh/material/texture/render-target/plugin-preset/viewer to a blob.
  341. * If no object is given, a glb is exported with the current viewer state.
  342. * @param obj
  343. * @param options
  344. */
  345. async export(obj?: IObject3D|IMaterial|ITexture|IRenderTarget|IViewerPlugin|(typeof this), options?: ExportFileOptions) {
  346. if (!obj) obj = this._scene // this will export the glb with the scene and viewer config
  347. if ((<typeof this>obj).type === this.type) return jsonToBlob((<typeof this>obj).exportConfig())
  348. if ((<IViewerPlugin>obj).constructor?.PluginType) return jsonToBlob(this.exportPluginConfig(<IViewerPlugin>obj))
  349. return await this.assetManager.exporter.exportObject(<IObject3D|IMaterial|ITexture|IRenderTarget>obj, options)
  350. }
  351. /**
  352. * Set the environment map of the scene from url or an {@link IAsset} object.
  353. * @param map
  354. * @param setBackground - Set the background image of the scene from the same map.
  355. * @param options - Options for importing the asset. See {@link ImportAssetOptions}
  356. */
  357. async setEnvironmentMap(map: string | IAsset | null | ITexture, {setBackground = false, ...options}: ImportAssetOptions&{setBackground?: boolean} = {}): Promise<ITexture | null> {
  358. this._scene.environment = map && !(<ITexture>map).isTexture ? await this.assetManager.importer.importSingle<ITexture>(map as string|IAsset, options) || null : <ITexture>map || null
  359. if (setBackground) return this.setBackgroundMap(this._scene.environment)
  360. return this._scene.environment
  361. }
  362. /**
  363. * Set the background image of the scene from url or an {@link IAsset} object.
  364. * @param map
  365. * @param setEnvironment - Set the environment map of the scene from the same map.
  366. * @param options - Options for importing the asset. See {@link ImportAssetOptions}
  367. */
  368. async setBackgroundMap(map: string | IAsset | null | ITexture, {setEnvironment = false, ...options}: ImportAssetOptions&{setBackground?: boolean} = {}): Promise<ITexture | null> {
  369. this._scene.background = map && !(<ITexture>map).isTexture ? await this.assetManager.importer.importSingle<ITexture>(map as string|IAsset, options) || null : <ITexture>map || null
  370. if (setEnvironment) return this.setEnvironmentMap(this._scene.background)
  371. return this._scene.background
  372. }
  373. /**
  374. * Disposes the viewer and frees up all resource and events. Do not use the viewer after calling dispose.
  375. * @note - If you want to reuse the viewer, set viewer.enabled to false instead, then set it to true again when required. To dispose all the objects, materials in the scene use `viewer.scene.disposeSceneModels()`
  376. * This function is not fully implemented yet. There might be some memory leaks.
  377. * @todo - return promise?
  378. */
  379. public dispose(): void {
  380. // todo: dispose stuff from constructor etc
  381. for (const plugin of [...Object.values(this.plugins)]) {
  382. this.removePlugin(plugin, true)
  383. }
  384. this._scene.dispose()
  385. this.renderManager.dispose()
  386. this._canvas.removeEventListener('webglcontextrestored', this._onContextRestore, false)
  387. this._canvas.removeEventListener('webglcontextlost', this._onContextLost, false)
  388. ;(window as any).threeViewers?.splice((window as any).threeViewers.indexOf(this), 1)
  389. if (this.resizeObserver) this.resizeObserver.unobserve(this._canvas)
  390. else window.removeEventListener('resize', this.resize)
  391. this.dispatchEvent({type: 'dispose'})
  392. }
  393. private _animationLoop(event: IAnimationLoopEvent): void {
  394. if (!this.enabled || !this.renderEnabled) return
  395. if (this._isRenderingFrame) {
  396. this.console.warn('animation loop: frame skip') // not possible actually, since this is not async
  397. return
  398. }
  399. this._isRenderingFrame = true
  400. this.renderStats.begin()
  401. for (let i = 0; i < this.maxFramePerLoop; i++) {
  402. if (this._needsReset) {
  403. this.renderManager.reset()
  404. this._needsReset = false
  405. }
  406. if (this._needsResize) {
  407. const size = [this._canvas.clientWidth, this._canvas.clientHeight]
  408. if (event.xrFrame) { // todo: find a better way to resize for XR.
  409. const cam = this.renderManager.webglRenderer.xr.getCamera()?.cameras[0]?.viewport
  410. if (cam) {
  411. if (cam.x !== 0 || cam.y !== 0) {
  412. this.console.warn('x and y must be 0?')
  413. }
  414. size[0] = cam.width
  415. size[1] = cam.height
  416. this.console.log('resize for xr', size)
  417. } else {
  418. this._needsResize = false
  419. }
  420. }
  421. if (this._needsResize) {
  422. this.renderManager.setSize(...size)
  423. this._needsResize = false
  424. }
  425. }
  426. this.dispatchEvent({...event, type: 'preFrame', target: this}) // event will have time, deltaTime and xrFrame
  427. const dirtyPlugins = Object.values(this.plugins).filter(value => value.dirty)
  428. if (dirtyPlugins.length > 0) {
  429. // console.log('dirty plugins', dirtyPlugins)
  430. this.setDirty(dirtyPlugins)
  431. }
  432. if (this._needsReset) {
  433. this.renderManager.reset()
  434. this._needsReset = false
  435. }
  436. // Check if the renderManger is dirty, which happens when it's reset above or if any pass in the composer is dirty
  437. const needsRender = this.renderManager.needsRender
  438. if (needsRender) {
  439. this.dispatchEvent({type: 'preRender', target: this})
  440. if (this.debug) this.renderManager.render(this._scene)
  441. else {
  442. try {
  443. this.renderManager.render(this._scene)
  444. } catch (e) {
  445. this.console.error(e)
  446. // this.enabled = false
  447. }
  448. }
  449. this.dispatchEvent({type: 'postRender', target: this})
  450. }
  451. this.dispatchEvent({type: 'postFrame', target: this})
  452. this.renderManager.onPostFrame()
  453. if (!needsRender) // break if no frame rendered
  454. break
  455. }
  456. this.renderStats.end()
  457. this._isRenderingFrame = false
  458. }
  459. /**
  460. * Get the HTML Element containing the canvas
  461. * @returns {HTMLElement}
  462. */
  463. get container(): HTMLElement {
  464. return this._container
  465. }
  466. /**
  467. * Get the HTML Canvas Element where the viewer is rendering
  468. * @returns {HTMLCanvasElement}
  469. */
  470. get canvas(): HTMLCanvasElement {
  471. return this._canvas
  472. }
  473. /**
  474. * Get the Plugin by a constructor type or by the string type.
  475. * Use string type if the plugin is not a dependency and you don't want to bundle the plugin.
  476. * @param type - The class of the plugin to get, or the string type of the plugin to get which is in the static PluginType property of the plugin
  477. * @returns {T | undefined} - The plugin of the specified type.
  478. */
  479. getPlugin<T extends IViewerPlugin>(type: Class<T>|string): T | undefined {
  480. return this.plugins[typeof type === 'string' ? type : (type as any).PluginType] as T | undefined
  481. }
  482. /**
  483. * Get the Plugin by the string type.
  484. * @deprecated - Use {@link getPlugin} instead.
  485. * @param type
  486. * @returns {T | undefined}
  487. */
  488. getPluginByType<T extends IViewerPlugin>(type: string): T | undefined {
  489. return this.plugins[type] as T | undefined
  490. }
  491. async getOrAddPlugin<T extends IViewerPlugin>(type: Class<T>, ...args: ConstructorParameters<Class<T>>): Promise<T> {
  492. const plugin = this.getPlugin(type)
  493. if (plugin) return plugin
  494. return this.addPlugin(type, ...args)
  495. }
  496. getOrAddPluginSync<T extends IViewerPluginSync>(type: Class<T>, ...args: ConstructorParameters<Class<T>>): T {
  497. const plugin = this.getPlugin(type)
  498. if (plugin) return plugin
  499. return this.addPluginSync(type, ...args)
  500. }
  501. /**
  502. * Add a plugin to the viewer.
  503. * @param plugin - The instance of the plugin to add or the class of the plugin to add.
  504. * @param args - Arguments for the constructor of the plugin, in case a class is passed.
  505. * @returns {Promise<T>} - The plugin added.
  506. */
  507. async addPlugin<T extends IViewerPlugin>(plugin: T | Class<T>, ...args: ConstructorParameters<Class<T>>): Promise<T> {
  508. const p = this._resolvePluginOrClass(plugin, ...args)
  509. const type = p.constructor.PluginType
  510. if (!p.constructor.PluginType) {
  511. this.console.error('PluginType is not defined for', p)
  512. return p
  513. }
  514. for (const d of p.dependencies || []) {
  515. await this.getOrAddPlugin(d)
  516. }
  517. if (this.plugins[type]) {
  518. this.console.error(`Plugin of type ${type} already exists, removing and disposing old plugin. This might break functionality, ensure only one plugin of a type is added`, this.plugins[type], p)
  519. await this.removePlugin(this.plugins[type])
  520. }
  521. this.plugins[type] = p
  522. await p.onAdded(this)
  523. this.dispatchEvent({type: 'addPlugin', target: this, plugin: p})
  524. this.setDirty(p)
  525. return p
  526. }
  527. /**
  528. * Add a plugin to the viewer(sync).
  529. * @param plugin
  530. * @param args
  531. */
  532. addPluginSync<T extends IViewerPluginSync>(plugin: T|Class<T>, ...args: ConstructorParameters<Class<T>>): T {
  533. const p = this._resolvePluginOrClass(plugin, ...args)
  534. const type = p.constructor.PluginType
  535. if (!p.constructor.PluginType) {
  536. this.console.error('PluginType is not defined for', p)
  537. return p
  538. }
  539. for (const d of p.dependencies || []) {
  540. this.getOrAddPluginSync(d)
  541. }
  542. if (this.plugins[type]) {
  543. this.console.error(`Plugin of type ${type} already exists, removing and disposing old plugin. This might break functionality, ensure only one plugin of a type is added`, this.plugins[type], p)
  544. this.removePluginSync(this.plugins[type])
  545. }
  546. this.plugins[type] = p
  547. p.onAdded(this)
  548. this.dispatchEvent({type: 'addPlugin', target: this, plugin: p})
  549. this.setDirty(p)
  550. return p
  551. }
  552. async addPlugins(plugins: (IViewerPlugin | Class<IViewerPlugin>)[]): Promise<void> {
  553. for (const p of plugins) await this.addPlugin(p)
  554. }
  555. async addPluginsSync(plugins: (IViewerPluginSync | Class<IViewerPluginSync>)[]): Promise<void> {
  556. for (const p of plugins) this.addPluginSync(p)
  557. }
  558. /**
  559. * Remove a plugin instance or a plugin class. Works similar to {@link ThreeViewer.addPlugin}
  560. * @param p
  561. * @param dispose
  562. * @returns {Promise<void>}
  563. */
  564. async removePlugin(p: IViewerPlugin<ThreeViewer, false>, dispose = true): Promise<void> {
  565. const type = p.constructor.PluginType
  566. if (!this.plugins[type]) return
  567. await p.onRemove(this)
  568. delete this.plugins[type]
  569. if (dispose) await p.dispose() // todo await?
  570. this.setDirty(p)
  571. }
  572. removePluginSync(p: IViewerPluginSync, dispose = true): void {
  573. const type = p.constructor.PluginType
  574. if (!this.plugins[type]) return
  575. p.onRemove(this)
  576. delete this.plugins[type]
  577. if (dispose) p.dispose()
  578. this.setDirty(p)
  579. }
  580. /**
  581. * Set size of the canvas and update the renderer.
  582. * If no width/height is passed, canvas is set to 100% of the container.
  583. * @param size
  584. */
  585. setSize(size?: {width?: number, height?: number}) {
  586. this._canvas.style.width = size?.width ? size.width + 'px' : '100%'
  587. this._canvas.style.height = size?.height ? size.height + 'px' : '100%'
  588. // this._canvas.style.maxWidth = '100%' // this is upto the app to do.
  589. // this._canvas.style.maxHeight = '100%'
  590. this.resize()
  591. }
  592. // private _addSceneObject = (e: IEvent<any>) => {
  593. // if (!e || !e.object) return
  594. // const config = e.object.__importedViewerConfig // this is set in gltf.ts when gltf file is imported. This is done here so that scene settings are applied whenever the imported object is added to scene.
  595. // if (!config) return
  596. // this.fromJSON(config, config.resources)
  597. // }
  598. /**
  599. * @deprecated use {@link assetManager} instead.
  600. * Gets the Asset manager, contains useful functions for managing, loading and inserting assets.
  601. */
  602. getManager(): AssetManager|undefined {
  603. return this.assetManager
  604. }
  605. // todo
  606. // public async fitToView(selected?: Object3D, distanceMultiplier = 1.5, duration?: number, ease?: Easing|EasingFunctionType) {
  607. // const camViews = this.getPluginByType<CameraViewPlugin>('CameraViews')
  608. // if (!camViews) {
  609. // this.console.error('CameraViews plugin is required for fitToView to work')
  610. // return
  611. // }
  612. // await camViews?.animateToFitObject(selected, distanceMultiplier, duration, ease, {min: (this.scene.activeCamera.getControls<OrbitControls3>()?.minDistance ?? 0.5) + 0.5, max: 1000.0})
  613. // }
  614. /**
  615. * Traverse all objects in scene model root.
  616. * @param callback
  617. */
  618. traverseSceneObjects<T extends IObject3D = IObject3D>(callback: (o: T)=>void): void {
  619. this._scene.modelRoot.traverse(callback)
  620. }
  621. // todo: create/load texture utils
  622. /**
  623. * Serialize all the plugins and their settings to save or create presets. Used in {@link toJSON}.
  624. * @param meta - The meta object.
  625. * @param filter - List of PluginType for the to include. If empty, no plugins will be serialized. If undefined, all plugins will be serialized.
  626. * @returns {any[]}
  627. */
  628. serializePlugins(meta: SerializationMetaType, filter?: string[]): any[] {
  629. if (filter && filter.length === 0) return []
  630. return Object.entries(this.plugins).map(p=> {
  631. if (filter && !filter.includes(p[1].constructor.PluginType)) return
  632. // if (!p[1].toJSON) this.console.log(`Plugin of type ${p[0]} is not serializable`)
  633. return p[1].serializeWithViewer !== false ? p[1].toJSON?.(meta) : undefined
  634. }).filter(p=> !!p)
  635. }
  636. /**
  637. * Deserialize all the plugins and their settings from a preset. Used in {@link fromJSON}.
  638. * @param plugins - The output of {@link serializePlugins}.
  639. * @param meta - The meta object.
  640. * @returns {this}
  641. */
  642. deserializePlugins(plugins: any[], meta?: SerializationMetaType): this {
  643. plugins.forEach(p=>{
  644. if (!p.type) {
  645. this.console.warn('Invalid plugin to import ', p)
  646. return
  647. }
  648. const plugin = this.getPlugin(p.type)
  649. if (!plugin) {
  650. // this.console.warn(`Plugin of type ${p.type} is not added, cannot deserialize`)
  651. return
  652. }
  653. plugin.fromJSON?.(p, meta)
  654. })
  655. return this
  656. }
  657. /**
  658. * Serialize a single plugin settings.
  659. */
  660. exportPluginConfig(plugin?: string|Class<IViewerPlugin>|IViewerPlugin): ISerializedConfig | Record<string, never> {
  661. if (plugin && typeof plugin === 'string' || (plugin as any).PluginType) plugin = this.getPlugin(plugin as any)
  662. if (!plugin) return {}
  663. const meta = getEmptyMeta()
  664. const data = (<IViewerPlugin>plugin).toJSON?.(meta)
  665. if (!data) return {}
  666. data.resources = metaToResources(meta)
  667. return data
  668. }
  669. /**
  670. * Deserialize and import a single plugin settings.
  671. * Can also use {@link ThreeViewer.importConfig} to import only plugin config.
  672. * @param json
  673. * @param plugin
  674. */
  675. async importPluginConfig(json: ISerializedConfig, plugin?: IViewerPlugin) {
  676. // this.console.log('importing plugin preset', json, plugin)
  677. const type = json.type
  678. plugin = plugin || this.getPlugin(type)
  679. if (!plugin) {
  680. this.console.warn(`No plugin found for type ${type} to import config`)
  681. return undefined
  682. }
  683. if (!plugin.fromJSON) {
  684. this.console.warn(`Plugin ${type} does not support importing presets`)
  685. return undefined
  686. }
  687. const resources = json.resources || {}
  688. if (json.resources) delete json.resources
  689. const meta = await this.loadConfigResources(resources)
  690. await plugin.fromJSON(json, meta)
  691. if (meta) json.resources = meta
  692. return plugin
  693. }
  694. /**
  695. * Serialize multiple plugin settings.
  696. * @param filter - List of PluginType to include. If empty, no plugins will be serialized. If undefined, all plugins will be serialized.
  697. */
  698. exportPluginsConfig(filter?: string[]): ISerializedViewerConfig {
  699. const meta = getEmptyMeta()
  700. const plugins = this.serializePlugins(meta, filter)
  701. convertArrayBufferToStringsInMeta(meta) // assuming not binary
  702. return {
  703. ...this._defaultConfig,
  704. plugins, resources: metaToResources(meta),
  705. }
  706. }
  707. /**
  708. * Serialize all the viewer and plugin settings.
  709. * @param binary - Indicate that the output will be converted and saved as binary data. (default: false)
  710. * @param pluginFilter - List of PluginType to include. If empty, no plugins will be serialized. If undefined, all plugins will be serialized.
  711. */
  712. exportConfig(binary = false, pluginFilter?: string[]) {
  713. return this.toJSON(binary, pluginFilter)
  714. }
  715. /**
  716. * Deserialize and import all the viewer and plugin settings, exported with {@link exportConfig}.
  717. */
  718. async importConfig(json: ISerializedConfig|ISerializedViewerConfig) {
  719. if (json.type !== this.type && <string>json.type !== 'ViewerApp') {
  720. if (this.getPlugin(json.type)) {
  721. return this.importPluginConfig(json)
  722. } else {
  723. this.console.error(`Unknown config type ${json.type} to import`)
  724. return undefined
  725. }
  726. }
  727. const resources = await this.loadConfigResources(json.resources || {})
  728. this.fromJSON(<ISerializedViewerConfig>json, resources)
  729. }
  730. /**
  731. * Serialize all the viewer and plugin settings and versions.
  732. * @param binary - Indicate that the output will be converted and saved as binary data. (default: true)
  733. * @param pluginFilter - List of PluginType to include. If empty, no plugins will be serialized. If undefined, all plugins will be serialized.
  734. * @returns {any} - Serializable JSON object.
  735. */
  736. toJSON(binary = true, pluginFilter?: string[]): ISerializedViewerConfig {
  737. const meta = getEmptyMeta()
  738. const data: ISerializedViewerConfig = Object.assign({
  739. ...this._defaultConfig,
  740. plugins: this.serializePlugins(meta, pluginFilter),
  741. }, ThreeSerialization.Serialize(this, meta, true))
  742. // this.console.log(dat)
  743. if (!binary) convertArrayBufferToStringsInMeta(meta)
  744. data.resources = metaToResources(meta)
  745. return data
  746. }
  747. /**
  748. * Deserialize all the viewer and plugin settings.
  749. * @note use async {@link ThreeViewer.importConfig} to import a json/config exported with {@link ThreeViewer.exportConfig} or {@link ThreeViewer.toJSON}.
  750. * @param data - The serialized JSON object retured from {@link toJSON}.
  751. * @param meta - The meta object
  752. * @returns {this}
  753. */
  754. fromJSON(data: ISerializedViewerConfig, meta?: SerializationMetaType): this|null {
  755. const data2: Partial<ISerializedViewerConfig> = {...data} // shallow copy
  756. // region legacy
  757. if (data2.backgroundIntensity !== undefined && data2.scene?.backgroundIntensity === undefined) {
  758. this.console.warn('old file format, backgroundIntensity moved to RootScene')
  759. this._scene.backgroundIntensity = data2.backgroundIntensity
  760. delete data2.backgroundIntensity
  761. }
  762. if (data2.useLegacyLights !== undefined && data2.renderManager?.useLegacyLights === undefined) {
  763. this.console.warn('old file format, useLegacyLights moved to RenderManager')
  764. this.renderManager.useLegacyLights = data2.useLegacyLights
  765. delete data2.useLegacyLights
  766. }
  767. if (data2.background !== undefined && data2.scene?.background === undefined) {
  768. this.console.warn('old file format, background moved to RootScene')
  769. if (data2.background === 'envMapBackground') data2.background = 'environment'
  770. else if (typeof data2.background === 'number')
  771. data2.background = new Color().setHex(data2.background, LinearSRGBColorSpace)
  772. else if (typeof data2.background === 'string')
  773. data2.background = new Color().setStyle(data2.background, LinearSRGBColorSpace)
  774. else if (data2.background?.isColor) data2.background = new Color(data2.background)
  775. if (data2.background?.isColor) { // color
  776. this._scene.backgroundColor = data2.background
  777. this._scene.background = null
  778. } else if (!data2.background) { // null
  779. this._scene.backgroundColor = null
  780. this._scene.background = null
  781. } else { // texture or 'environment'
  782. this._scene.backgroundColor = new Color('#ffffff')
  783. if (!data2.scene) data2.scene = {}
  784. data2.scene.background = data2.background
  785. }
  786. delete data2.background
  787. }
  788. // endregion
  789. if (!meta && data2.resources && data2.resources.__isLoadedResources) {
  790. meta = data2.resources as SerializationMetaType
  791. delete data2.resources
  792. }
  793. if (!meta?.__isLoadedResources) {
  794. this.console.error('meta in fromJSON is not available or is not loaded resources, call viewer.loadConfigResources first, or directly use viewer.importConfig')
  795. return null
  796. }
  797. if (Array.isArray(data2.plugins)) {
  798. this.deserializePlugins(data2.plugins, meta)
  799. delete data2.plugins
  800. }
  801. // meta = meta || data.resources
  802. ThreeSerialization.Deserialize(data2, this, meta, true)
  803. // todo: handle
  804. // __useCount set in ThreeSerialization while deserializing resources
  805. // for (const mat of Object.values(resources.materials) as any) {
  806. // if (!mat.__useCount) this.materialManager?.unregisterMaterial(mat) // todo: also dispose?
  807. // else delete mat.__useCount
  808. // }
  809. // for (const tex of Object.values(resources.textures) as any) {
  810. // if (!tex.__useCount) {
  811. // // todo: dispose?
  812. // } else {
  813. // delete tex.__useCount
  814. // }
  815. // }
  816. return this
  817. }
  818. loadConfigResources = async(json: Partial<SerializationMetaType>, extraResources?: Partial<SerializationResourcesType>): Promise<any> => {
  819. // this.console.log(json)
  820. if (json.__isLoadedResources) return json
  821. const meta = metaFromResources(json, this)
  822. return await MetaImporter.ImportMeta(meta, extraResources)
  823. }
  824. async addSceneObject<T extends IObject3D|Object3D|RootSceneImportResult = RootSceneImportResult>(imported: T, options?: AddObjectOptions): Promise<T> {
  825. if (imported.userData?.rootSceneModelRoot) {
  826. const obj = <RootSceneImportResult>imported
  827. if (obj.importedViewerConfig && options?.importConfig !== false) await this.importConfig(obj.importedViewerConfig)
  828. this._scene.loadModelRoot(obj, options)
  829. return this._scene.modelRoot as T
  830. }
  831. this._scene.addObject(imported, options)
  832. return imported
  833. }
  834. private _setActiveCameraView(event: any = {}): void {
  835. if (event.type === 'setView') {
  836. if (!event.camera) {
  837. this.console.warn('Cannot find camera', event)
  838. return
  839. }
  840. this._scene.mainCamera.copy(event.camera)
  841. } else if (event.type === 'activateMain')
  842. this._scene.mainCamera = event.camera || undefined // event.camera should have been upgraded when added to the scene.
  843. }
  844. private _resolvePluginOrClass<T extends IViewerPlugin>(plugin: T | Class<T>, ...args: ConstructorParameters<Class<T>>): T {
  845. let p: T
  846. if ((plugin as Class<IViewerPlugin>).prototype) p = new (plugin as Class<T>)(...args)
  847. else p = plugin as T
  848. if ((plugin as Class<IViewerPlugin>).prototype) {
  849. const p1 = this.getPlugin(plugin as Class<T>)
  850. if (p1) {
  851. this.console.error(`Plugin of type ${p1.constructor.PluginType} already exists, no new plugin created`, p1)
  852. return p1
  853. }
  854. p = new (plugin as Class<T>)(...args)
  855. } else p = plugin as T
  856. return p
  857. }
  858. async doOnce<TRet>(event: IViewerEventTypes, func: (...args: any[]) => TRet): Promise<TRet> {
  859. return new Promise((resolve) => {
  860. const listener = async(...args: any[]) => {
  861. this.removeEventListener(event, listener)
  862. resolve(await func(...args))
  863. }
  864. this.addEventListener(event, listener)
  865. })
  866. }
  867. /**
  868. * Export the scene to a file (default: glb with viewer config) and return a blob
  869. * @param options
  870. */
  871. async exportScene(options?: ExportFileOptions): Promise<BlobExt | undefined> {
  872. return this.assetManager.exporter.exportObject(this._scene.modelRoot, options)
  873. }
  874. async getScreenshotBlob({mimeType = 'image/jpeg', quality = 90} = {}): Promise<Blob | null> {
  875. const blobPromise = async()=> new Promise<Blob|null>((resolve) => {
  876. this._canvas.toBlob((blob) => {
  877. resolve(blob)
  878. }, mimeType, quality)
  879. })
  880. if (!this.renderEnabled) return blobPromise()
  881. return await this.doOnce('postFrame', async() => {
  882. this.renderEnabled = false
  883. const blob = await blobPromise()
  884. this.renderEnabled = true
  885. return blob
  886. })
  887. }
  888. async getScreenshotDataUrl({mimeType = 'image/jpeg', quality = 90} = {}): Promise<string | null> {
  889. if (!this.renderEnabled) return this._canvas.toDataURL(mimeType, quality)
  890. return await this.doOnce('postFrame', () => this._canvas.toDataURL(mimeType, quality))
  891. }
  892. private _renderEnabledChanged(): void {
  893. this.dispatchEvent({type: this.renderEnabled ? 'renderEnabled' : 'renderDisabled'})
  894. }
  895. private readonly _defaultConfig: ISerializedViewerConfig = {
  896. assetType: 'config',
  897. type: this.type,
  898. version: ThreeViewer.VERSION,
  899. metadata: {
  900. generator: 'ThreePipe',
  901. version: 1,
  902. },
  903. plugins: [],
  904. }
  905. // region legacy creation functions
  906. // /**
  907. // * Converts a three.js Camera instance to be used in the viewer.
  908. // * @param camera - The three.js OrthographicCamera or PerspectiveCamera instance
  909. // * @returns {CameraController} - A wrapper around the camera with some useful methods and properties.
  910. // */
  911. // createCamera(camera: OrthographicCamera | PerspectiveCamera): CameraController {
  912. // const cam: CameraController = camera.userData.iCamera ?? new CameraController(camera, {
  913. // controlsMode: '',
  914. // controlsEnabled: false,
  915. // }, this._canvas)
  916. // if (camera.userData.autoLookAtTarget === undefined) {
  917. // cam.autoLookAtTarget = false
  918. // camera.userData.autoLookAtTarget = false
  919. // } else {
  920. // cam.autoLookAtTarget = camera.userData.autoLookAtTarget
  921. // }
  922. // return cam
  923. // }
  924. // /**
  925. // * Create a new empty object in the scene or add an existing three.js object to the scene.
  926. // * @param object
  927. // */
  928. // async createObject3D(object?: Object3D): Promise<Object3DModel | undefined> {
  929. // return this.getManager()?.addImportedSingle<Object3DModel>(object || new Object3D(), {autoScale: false, pseudoCenter: false})
  930. // }
  931. // /**
  932. // * Create a new physical material from a template or another material. It returns the same material if a material is passed created by the material manager.
  933. // * @param material
  934. // */
  935. // createPhysicalMaterial(material?: Material|MeshPhysicalMaterialParameters): MeshStandardMaterial2 | undefined {
  936. // return this.createMaterial<MeshStandardMaterial2>('standard', material)
  937. // }
  938. // /**
  939. // * Create a new material from a template or another material. It returns the same material if a material is passed created by the material manager.
  940. // * @param template - template name registered in MaterialManager
  941. // * @param material - three.js material object or material params to create a new material
  942. // */
  943. // createMaterial<T extends IMaterial<any>>(template: 'standard' | 'basic' | 'diamond' | string, material?: Material|any): T | undefined {
  944. // if ((material as Material)?.isMaterial) {
  945. // const f = this.getManager()?.materials?.findMaterial((material as Material).uuid)
  946. // if (f) return f as T
  947. // }
  948. // return this.getManager()?.materials?.generateFromTemplate(template, material) as T
  949. // }
  950. // endregion
  951. }