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

ThreeViewer.ts 48KB

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