defaultViewer.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. import { ViewerConfiguration, IModelConfiguration, ILightConfiguration } from './../configuration';
  2. import { Template, EventCallback, TemplateManager } from '../templating/templateManager';
  3. import { AbstractViewer } from './viewer';
  4. import { SpotLight, MirrorTexture, Plane, ShadowGenerator, Texture, BackgroundMaterial, Observable, ShadowLight, CubeTexture, BouncingBehavior, FramingBehavior, Behavior, Light, Engine, Scene, AutoRotationBehavior, AbstractMesh, Quaternion, StandardMaterial, ArcRotateCamera, ImageProcessingConfiguration, Color3, Vector3, SceneLoader, Mesh, HemisphericLight, FilesInput } from 'babylonjs';
  5. import { CameraBehavior } from '../interfaces';
  6. import { ViewerModel } from '../model/viewerModel';
  7. import { extendClassWithConfig } from '../helper';
  8. import { IModelAnimation, AnimationState } from '../model/modelAnimation';
  9. /**
  10. * The Default viewer is the default implementation of the AbstractViewer.
  11. * It uses the templating system to render a new canvas and controls.
  12. */
  13. export class DefaultViewer extends AbstractViewer {
  14. /**
  15. * Create a new default viewer
  16. * @param containerElement the element in which the templates will be rendered
  17. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  18. */
  19. constructor(public containerElement: HTMLElement, initialConfiguration: ViewerConfiguration = { extends: 'default' }) {
  20. super(containerElement, initialConfiguration);
  21. this.onModelLoadedObservable.add(this._onModelLoaded);
  22. this.onModelRemovedObservable.add(() => {
  23. this._configureTemplate();
  24. })
  25. this.onEngineInitObservable.add(() => {
  26. this.sceneManager.onLightsConfiguredObservable.add((data) => {
  27. this._configureLights(data.newConfiguration, data.model!);
  28. })
  29. });
  30. }
  31. /**
  32. * This will be executed when the templates initialize.
  33. */
  34. protected _onTemplatesLoaded() {
  35. this.showLoadingScreen();
  36. // navbar
  37. this._initNavbar();
  38. // close overlay button
  39. let closeButton = document.getElementById('close-button');
  40. if (closeButton) {
  41. closeButton.addEventListener('pointerdown', () => {
  42. this.hideOverlayScreen();
  43. });
  44. }
  45. if (this.configuration.templates && this.configuration.templates.viewer) {
  46. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  47. let filesInput = new FilesInput(this.engine, this.sceneManager.scene, () => {
  48. }, () => {
  49. }, () => {
  50. }, () => {
  51. }, function () {
  52. }, (file: File) => {
  53. this.loadModel(file);
  54. }, () => {
  55. });
  56. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas()!);
  57. }
  58. }
  59. return super._onTemplatesLoaded();
  60. }
  61. private _dropped(evt: EventCallback) {
  62. }
  63. private _initNavbar() {
  64. let navbar = this.templateManager.getTemplate('navBar');
  65. if (navbar) {
  66. this.onFrameRenderedObservable.add(this._updateProgressBar);
  67. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  68. // an example how to trigger the help button. publiclly available
  69. this.templateManager.eventManager.registerCallback("navBar", () => {
  70. // do your thing
  71. }, "pointerdown", "#help-button");
  72. this.templateManager.eventManager.registerCallback("navBar", (event: EventCallback) => {
  73. const evt = event.event;
  74. const element = <HTMLInputElement>(evt.target);
  75. if (!this._currentAnimation) return;
  76. const gotoFrame = +element.value / 100 * this._currentAnimation.frames;
  77. if (isNaN(gotoFrame)) return;
  78. this._currentAnimation.goToFrame(gotoFrame);
  79. }, "input");
  80. this.templateManager.eventManager.registerCallback("navBar", (e) => {
  81. if (this._resumePlay) {
  82. this._togglePlayPause(true);
  83. }
  84. this._resumePlay = false;
  85. }, "pointerup", "#progress-wrapper");
  86. }
  87. }
  88. private _animationList: string[];
  89. private _currentAnimation: IModelAnimation;
  90. private _isAnimationPaused: boolean;
  91. private _resumePlay: boolean;
  92. private _handlePointerDown = (event: EventCallback) => {
  93. let pointerDown = <PointerEvent>event.event;
  94. if (pointerDown.button !== 0) return;
  95. var element = (<HTMLElement>event.event.target);
  96. if (!element) {
  97. return;
  98. }
  99. let parentClasses = element.parentElement!.classList;
  100. switch (element.id) {
  101. case "speed-button":
  102. case "types-button":
  103. if (parentClasses.contains("open")) {
  104. parentClasses.remove("open");
  105. } else {
  106. parentClasses.add("open");
  107. }
  108. break;
  109. case "play-pause-button":
  110. this._togglePlayPause();
  111. break;
  112. case "label-option-button":
  113. var label = element.dataset["value"];
  114. if (label) {
  115. this._updateAnimationType(label);
  116. }
  117. break;
  118. case "speed-option-button":
  119. if (!this._currentAnimation) {
  120. return;
  121. }
  122. var speed = element.dataset["value"];
  123. if (speed)
  124. this._updateAnimationSpeed(speed);
  125. break;
  126. case "progress-wrapper":
  127. this._resumePlay = !this._isAnimationPaused;
  128. if (this._resumePlay) {
  129. this._togglePlayPause(true);
  130. }
  131. break;
  132. case "fullscreen-button":
  133. this.toggleFullscreen();
  134. break;
  135. case "hd-button":
  136. this.toggleHD();
  137. break;
  138. default:
  139. return;
  140. }
  141. }
  142. /**
  143. * Plays or Pauses animation
  144. */
  145. private _togglePlayPause = (noUiUpdate?: boolean) => {
  146. if (!this._currentAnimation) {
  147. return;
  148. }
  149. if (this._isAnimationPaused) {
  150. this._currentAnimation.restart();
  151. } else {
  152. this._currentAnimation.pause();
  153. }
  154. this._isAnimationPaused = !this._isAnimationPaused;
  155. if (noUiUpdate) return;
  156. let navbar = this.templateManager.getTemplate('navBar');
  157. if (!navbar) return;
  158. navbar.updateParams({
  159. paused: this._isAnimationPaused,
  160. });
  161. }
  162. private _oldIdleRotationValue: number;
  163. /**
  164. * Control progress bar position based on animation current frame
  165. */
  166. private _updateProgressBar = () => {
  167. let navbar = this.templateManager.getTemplate('navBar');
  168. if (!navbar) return;
  169. var progressSlider = <HTMLInputElement>navbar.parent.querySelector("input#progress-wrapper");
  170. if (progressSlider && this._currentAnimation) {
  171. const progress = this._currentAnimation.currentFrame / this._currentAnimation.frames * 100;
  172. var currentValue = progressSlider.valueAsNumber;
  173. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  174. progressSlider.value = '' + progress;
  175. }
  176. if (this._currentAnimation.state === AnimationState.PLAYING) {
  177. if (this.sceneManager.camera.autoRotationBehavior && !this._oldIdleRotationValue) {
  178. this._oldIdleRotationValue = this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  179. this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  180. }
  181. } else {
  182. if (this.sceneManager.camera.autoRotationBehavior && this._oldIdleRotationValue) {
  183. this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = this._oldIdleRotationValue;
  184. this._oldIdleRotationValue = 0;
  185. }
  186. }
  187. }
  188. }
  189. /**
  190. * Update Current Animation Speed
  191. */
  192. private _updateAnimationSpeed = (speed: string, paramsObject?: any) => {
  193. let navbar = this.templateManager.getTemplate('navBar');
  194. if (!navbar) return;
  195. if (speed && this._currentAnimation) {
  196. this._currentAnimation.speedRatio = parseFloat(speed);
  197. if (!this._isAnimationPaused) {
  198. this._currentAnimation.restart();
  199. }
  200. if (paramsObject) {
  201. paramsObject.selectedSpeed = speed + "x"
  202. } else {
  203. navbar.updateParams({
  204. selectedSpeed: speed + "x",
  205. });
  206. }
  207. }
  208. }
  209. /**
  210. * Update Current Animation Type
  211. */
  212. private _updateAnimationType = (label: string, paramsObject?: any) => {
  213. let navbar = this.templateManager.getTemplate('navBar');
  214. if (!navbar) return;
  215. if (label) {
  216. this._currentAnimation = this.sceneManager.models[0].setCurrentAnimationByName(label);
  217. }
  218. if (paramsObject) {
  219. paramsObject.selectedAnimation = (this._animationList.indexOf(label) + 1);
  220. paramsObject.selectedAnimationName = label;
  221. } else {
  222. navbar.updateParams({
  223. selectedAnimation: (this._animationList.indexOf(label) + 1),
  224. selectedAnimationName: label
  225. });
  226. }
  227. this._updateAnimationSpeed("1.0", paramsObject);
  228. }
  229. public toggleHD() {
  230. super.toggleHD();
  231. // update UI element
  232. let navbar = this.templateManager.getTemplate('navBar');
  233. if (!navbar) return;
  234. if (navbar.configuration.params) {
  235. navbar.configuration.params.hdEnabled = this._hdToggled;
  236. }
  237. let span = navbar.parent.querySelector("button.hd-button span");
  238. if (span) {
  239. span.classList.remove(this._hdToggled ? "hd-icon" : "sd-icon");
  240. span.classList.add(!this._hdToggled ? "hd-icon" : "sd-icon")
  241. }
  242. }
  243. /**
  244. * Toggle fullscreen of the entire viewer
  245. */
  246. public toggleFullscreen = () => {
  247. let viewerTemplate = this.templateManager.getTemplate('viewer');
  248. let viewerElement = viewerTemplate && viewerTemplate.parent;
  249. if (viewerElement) {
  250. let fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || (<any>document).mozFullScreenElement || (<any>document).msFullscreenElement;
  251. if (!fullscreenElement) {
  252. let requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || (<any>viewerElement).msRequestFullscreen || (<any>viewerElement).mozRequestFullScreen;
  253. requestFullScreen.call(viewerElement);
  254. } else {
  255. let exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || (<any>document).msExitFullscreen || (<any>document).mozCancelFullScreen
  256. exitFullscreen.call(document);
  257. }
  258. }
  259. }
  260. /**
  261. * Preparing the container element to present the viewer
  262. */
  263. protected _prepareContainerElement() {
  264. this.containerElement.style.position = 'relative';
  265. this.containerElement.style.height = '100%';
  266. this.containerElement.style.display = 'flex';
  267. }
  268. /**
  269. * This function will configure the templates and update them after a model was loaded
  270. * It is mainly responsible to changing the title and subtitle etc'.
  271. * @param model the model to be used to configure the templates by
  272. */
  273. protected _configureTemplate(model?: ViewerModel) {
  274. let navbar = this.templateManager.getTemplate('navBar');
  275. if (!navbar) return;
  276. let newParams: any = navbar.configuration.params || {};
  277. if (!model) {
  278. newParams.animations = null;
  279. } else {
  280. let animationNames = model.getAnimationNames();
  281. newParams.animations = animationNames;
  282. if (animationNames.length) {
  283. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  284. this._animationList = animationNames;
  285. newParams.paused = this._isAnimationPaused;
  286. let animationIndex = 0;
  287. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  288. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  289. if (animationIndex === -1) {
  290. animationIndex = 0;
  291. }
  292. }
  293. this._updateAnimationType(animationNames[animationIndex], newParams);
  294. } else {
  295. newParams.animations = null;
  296. }
  297. if (model.configuration.thumbnail) {
  298. newParams.logoImage = model.configuration.thumbnail
  299. }
  300. }
  301. navbar.updateParams(newParams, false);
  302. }
  303. /**
  304. * This will load a new model to the default viewer
  305. * overriding the AbstractViewer's loadModel.
  306. * The scene will automatically be cleared of the old models, if exist.
  307. * @param model the configuration object (or URL) to load.
  308. */
  309. public loadModel(model?: string | File | IModelConfiguration): Promise<ViewerModel> {
  310. if (!model) {
  311. model = this.configuration.model;
  312. }
  313. this.showLoadingScreen();
  314. return super.loadModel(model!, true).catch((error) => {
  315. console.log(error);
  316. this.hideLoadingScreen();
  317. this.showOverlayScreen('error');
  318. return Promise.reject(error);
  319. });
  320. }
  321. private _onModelLoaded = (model: ViewerModel) => {
  322. this._configureTemplate(model);
  323. // with a short timeout, making sure everything is there already.
  324. let hideLoadingDelay = 20;
  325. if (this.configuration.lab && this.configuration.lab.hideLoadingDelay !== undefined) {
  326. hideLoadingDelay = this.configuration.lab.hideLoadingDelay;
  327. }
  328. setTimeout(() => {
  329. this.sceneManager.scene.executeWhenReady(() => {
  330. this.hideLoadingScreen();
  331. });
  332. }, hideLoadingDelay);
  333. return;
  334. }
  335. /**
  336. * Show the overlay and the defined sub-screen.
  337. * Mainly used for help and errors
  338. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  339. */
  340. public showOverlayScreen(subScreen: string) {
  341. let template = this.templateManager.getTemplate('overlay');
  342. if (!template) return Promise.resolve('Overlay template not found');
  343. return template.show((template => {
  344. var canvasRect = this.containerElement.getBoundingClientRect();
  345. template.parent.style.display = 'flex';
  346. template.parent.style.width = canvasRect.width + "px";
  347. template.parent.style.height = canvasRect.height + "px";
  348. template.parent.style.opacity = "1";
  349. let subTemplate = this.templateManager.getTemplate(subScreen);
  350. if (!subTemplate) {
  351. return Promise.reject(subScreen + ' template not found');
  352. }
  353. return subTemplate.show((template => {
  354. template.parent.style.display = 'flex';
  355. return Promise.resolve(template);
  356. }));
  357. }));
  358. }
  359. /**
  360. * Hide the overlay screen.
  361. */
  362. public hideOverlayScreen() {
  363. let template = this.templateManager.getTemplate('overlay');
  364. if (!template) return Promise.resolve('Overlay template not found');
  365. return template.hide((template => {
  366. template.parent.style.opacity = "0";
  367. let onTransitionEnd = () => {
  368. template.parent.removeEventListener("transitionend", onTransitionEnd);
  369. template.parent.style.display = 'none';
  370. }
  371. template.parent.addEventListener("transitionend", onTransitionEnd);
  372. let overlays = template.parent.querySelectorAll('.overlay');
  373. if (overlays) {
  374. for (let i = 0; i < overlays.length; ++i) {
  375. let htmlElement = <HTMLElement>overlays.item(i);
  376. htmlElement.style.display = 'none';
  377. }
  378. }
  379. return Promise.resolve(template);
  380. }));
  381. }
  382. /**
  383. * show the viewer (in case it was hidden)
  384. *
  385. * @param visibilityFunction an optional function to execute in order to show the container
  386. */
  387. public show(visibilityFunction?: ((template: Template) => Promise<Template>)): Promise<Template> {
  388. let template = this.templateManager.getTemplate('main');
  389. //not possible, but yet:
  390. if (!template) return Promise.reject('Main template not found');
  391. return template.show(visibilityFunction);
  392. }
  393. /**
  394. * hide the viewer (in case it is visible)
  395. *
  396. * @param visibilityFunction an optional function to execute in order to hide the container
  397. */
  398. public hide(visibilityFunction?: ((template: Template) => Promise<Template>)) {
  399. let template = this.templateManager.getTemplate('main');
  400. //not possible, but yet:
  401. if (!template) return Promise.reject('Main template not found');
  402. return template.hide(visibilityFunction);
  403. }
  404. /**
  405. * Show the loading screen.
  406. * The loading screen can be configured using the configuration object
  407. */
  408. public showLoadingScreen() {
  409. let template = this.templateManager.getTemplate('loadingScreen');
  410. if (!template) return Promise.resolve('Loading Screen template not found');
  411. return template.show((template => {
  412. var canvasRect = this.containerElement.getBoundingClientRect();
  413. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  414. template.parent.style.display = 'flex';
  415. template.parent.style.width = canvasRect.width + "px";
  416. template.parent.style.height = canvasRect.height + "px";
  417. template.parent.style.opacity = "1";
  418. // from the configuration!!!
  419. let color = "black";
  420. if (this.configuration.templates && this.configuration.templates.loadingScreen) {
  421. color = (this.configuration.templates.loadingScreen.params &&
  422. <string>this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  423. }
  424. template.parent.style.backgroundColor = color;
  425. return Promise.resolve(template);
  426. }));
  427. }
  428. /**
  429. * Hide the loading screen
  430. */
  431. public hideLoadingScreen() {
  432. let template = this.templateManager.getTemplate('loadingScreen');
  433. if (!template) return Promise.resolve('Loading Screen template not found');
  434. return template.hide((template => {
  435. template.parent.style.opacity = "0";
  436. let onTransitionEnd = () => {
  437. template.parent.removeEventListener("transitionend", onTransitionEnd);
  438. template.parent.style.display = 'none';
  439. }
  440. template.parent.addEventListener("transitionend", onTransitionEnd);
  441. return Promise.resolve(template);
  442. }));
  443. }
  444. public dispose() {
  445. this.templateManager.dispose();
  446. super.dispose();
  447. }
  448. protected _onConfigurationLoaded(configuration: ViewerConfiguration) {
  449. super._onConfigurationLoaded(configuration);
  450. // initialize the templates
  451. let templateConfiguration = this.configuration.templates || {};
  452. this.templateManager.initTemplate(templateConfiguration);
  453. // when done, execute onTemplatesLoaded()
  454. this.templateManager.onAllLoaded.add(() => {
  455. let canvas = this.templateManager.getCanvas();
  456. if (canvas) {
  457. this._canvas = canvas;
  458. }
  459. this._onTemplateLoaded();
  460. });
  461. }
  462. /**
  463. * An extension of the light configuration of the abstract viewer.
  464. * @param lightsConfiguration the light configuration to use
  465. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  466. */
  467. private _configureLights(lightsConfiguration: { [name: string]: ILightConfiguration | boolean | number } = {}, model?: ViewerModel) {
  468. // labs feature - flashlight
  469. if (this.configuration.lab && this.configuration.lab.flashlight) {
  470. let pointerPosition = Vector3.Zero();
  471. let lightTarget;
  472. let angle = 0.5;
  473. let exponent = Math.PI / 2;
  474. if (typeof this.configuration.lab.flashlight === "object") {
  475. exponent = this.configuration.lab.flashlight.exponent || exponent;
  476. angle = this.configuration.lab.flashlight.angle || angle;
  477. }
  478. var flashlight = new SpotLight("flashlight", Vector3.Zero(),
  479. Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  480. if (typeof this.configuration.lab.flashlight === "object") {
  481. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  482. if (this.configuration.lab.flashlight.diffuse) {
  483. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  484. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  485. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  486. }
  487. if (this.configuration.lab.flashlight.specular) {
  488. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  489. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  490. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  491. }
  492. }
  493. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  494. this.sceneManager.scene.onPointerObservable.add((eventData, eventState) => {
  495. if (eventData.type === 4 && eventData.pickInfo) {
  496. lightTarget = (eventData.pickInfo.pickedPoint);
  497. } else {
  498. lightTarget = undefined;
  499. }
  500. });
  501. let updateFlashlightFunction = () => {
  502. if (this.sceneManager.camera && flashlight) {
  503. flashlight.position.copyFrom(this.sceneManager.camera.position);
  504. if (lightTarget) {
  505. lightTarget.subtractToRef(flashlight.position, flashlight.direction);
  506. }
  507. }
  508. }
  509. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  510. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  511. }
  512. }
  513. }