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

ThreeViewer.ts 50KB

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