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

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