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

ThreeViewer.ts 45KB

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