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.

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