defaultViewer.ts 24 KB

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