index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /// <reference path="../dist/preview release/babylon.d.ts" />
  2. /// <reference path="../dist/preview release/loaders/babylon.glTFFileLoader.d.ts" />
  3. var assetUrl;
  4. var cameraPosition;
  5. var kiosk;
  6. var currentGroup; // animation group
  7. var currentGroupIndex;
  8. var currentScene;
  9. // html balise
  10. var animationBar = document.getElementById("animationBar");
  11. var dropdownBtn = document.getElementById("dropdownBtn");
  12. var chevronUp = document.getElementById("chevronUp");
  13. var chevronDown = document.getElementById("chevronDown");
  14. var dropdownLabel = document.getElementById("dropdownLabel");
  15. var dropdownContent = document.getElementById("dropdownContent");
  16. var playBtn = document.getElementById("playBtn");
  17. var slider = document.getElementById("slider");
  18. var indexOf = location.href.indexOf("?");
  19. if (indexOf !== -1) {
  20. var params = location.href.substr(indexOf + 1).split("&");
  21. for (var index = 0; index < params.length; index++) {
  22. var param = params[index].split("=");
  23. var name = param[0];
  24. var value = param[1];
  25. switch (name) {
  26. case "assetUrl": {
  27. assetUrl = value;
  28. break;
  29. }
  30. case "cameraPosition": {
  31. cameraPosition = BABYLON.Vector3.FromArray(value.split(",").map(function (component) { return +component; }));
  32. break;
  33. }
  34. case "kiosk": {
  35. kiosk = value === "true" ? true : false;
  36. break;
  37. }
  38. }
  39. }
  40. }
  41. if (BABYLON.Engine.isSupported()) {
  42. var canvas = document.getElementById("renderCanvas");
  43. var engine = new BABYLON.Engine(canvas, true, { premultipliedAlpha: false, preserveDrawingBuffer: true });
  44. var htmlInput = document.getElementById("files");
  45. var footer = document.getElementById("footer");
  46. var btnFullScreen = document.getElementById("btnFullscreen");
  47. var btnInspector = document.getElementById("btnInspector");
  48. var errorZone = document.getElementById("errorZone");
  49. var filesInput;
  50. var currentScene;
  51. var currentSkybox;
  52. var currentPluginName;
  53. var skyboxPath = "Assets/environment.dds";
  54. var debugLayerEnabled = false;
  55. var debugLayerLastActiveTab = 0;
  56. engine.loadingUIBackgroundColor = "#a9b5bc";
  57. btnFullScreen.classList.add("hidden");
  58. btnInspector.classList.add("hidden");
  59. canvas.addEventListener("contextmenu", function (evt) {
  60. evt.preventDefault();
  61. }, false);
  62. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  63. // This is really important to tell Babylon.js to use decomposeLerp and matrix interpolation
  64. BABYLON.Animation.AllowMatricesInterpolation = true;
  65. // Setting up some GLTF values
  66. BABYLON.GLTFFileLoader.IncrementalLoading = false;
  67. BABYLON.SceneLoader.OnPluginActivatedObservable.add(function (plugin) {
  68. currentPluginName = plugin.name;
  69. });
  70. // Resize
  71. window.addEventListener("resize", function () {
  72. engine.resize();
  73. });
  74. var sceneLoaded = function (sceneFile, babylonScene) {
  75. engine.clearInternalTexturesCache();
  76. // Clear dropdown that contains animation names
  77. dropdownContent.innerHTML = "";
  78. animationBar.style.display = "none";
  79. currentGroup = null;
  80. if (babylonScene.animationGroups.length > 0) {
  81. animationBar.style.display = "flex";
  82. for (var index = 0; index < babylonScene.animationGroups.length; index++) {
  83. var group = babylonScene.animationGroups[index];
  84. createDropdownLink(group, index);
  85. }
  86. currentGroup = babylonScene.animationGroups[0];
  87. currentGroupIndex = 0;
  88. document.getElementById(formatId(currentGroup.name + "-" + currentGroupIndex)).click();
  89. }
  90. // Sync the slider with the current frame
  91. babylonScene.registerBeforeRender(function () {
  92. if (currentGroup != null && currentGroup.targetedAnimations[0].animation.runtimeAnimations[0] != null) {
  93. var currentValue = slider.valueAsNumber;
  94. var newValue = currentGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame;
  95. var range = Math.abs(currentGroup.from - currentGroup.to);
  96. if (Math.abs(currentValue - newValue) > range * 0.01) { // Only move if greater than a 1% change
  97. slider.value = newValue;
  98. }
  99. }
  100. });
  101. // Clear the error
  102. errorZone.style.display = 'none';
  103. btnFullScreen.classList.remove("hidden");
  104. btnInspector.classList.remove("hidden");
  105. currentScene = babylonScene;
  106. document.title = "BabylonJS - " + sceneFile.name;
  107. // Fix for IE, otherwise it will change the default filter for files selection after first use
  108. htmlInput.value = "";
  109. // Attach camera to canvas inputs
  110. if (!currentScene.activeCamera || currentScene.lights.length === 0) {
  111. currentScene.createDefaultCameraOrLight(true);
  112. if (cameraPosition) {
  113. currentScene.activeCamera.setPosition(cameraPosition);
  114. }
  115. else {
  116. if (currentPluginName === "gltf") {
  117. // glTF assets use a +Z forward convention while the default camera faces +Z. Rotate the camera to look at the front of the asset.
  118. currentScene.activeCamera.alpha += Math.PI;
  119. }
  120. // Enable camera's behaviors
  121. currentScene.activeCamera.useFramingBehavior = true;
  122. var framingBehavior = currentScene.activeCamera.getBehaviorByName("Framing");
  123. framingBehavior.framingTime = 0;
  124. framingBehavior.elevationReturnTime = -1;
  125. if (currentScene.meshes.length) {
  126. var worldExtends = currentScene.getWorldExtends();
  127. currentScene.activeCamera.lowerRadiusLimit = null;
  128. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  129. }
  130. }
  131. currentScene.activeCamera.pinchPrecision = 200 / currentScene.activeCamera.radius;
  132. currentScene.activeCamera.upperRadiusLimit = 5 * currentScene.activeCamera.radius;
  133. currentScene.activeCamera.wheelDeltaPercentage = 0.01;
  134. currentScene.activeCamera.pinchDeltaPercentage = 0.01;
  135. }
  136. currentScene.activeCamera.attachControl(canvas);
  137. // Environment
  138. if (currentPluginName === "gltf") {
  139. var hdrTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(skyboxPath, currentScene);
  140. currentSkybox = currentScene.createDefaultSkybox(hdrTexture, true, (currentScene.activeCamera.maxZ - currentScene.activeCamera.minZ) / 2, 0.3);
  141. }
  142. // In case of error during loading, meshes will be empty and clearColor is set to red
  143. if (currentScene.meshes.length === 0 && currentScene.clearColor.r === 1 && currentScene.clearColor.g === 0 && currentScene.clearColor.b === 0) {
  144. document.getElementById("logo").className = "";
  145. canvas.style.opacity = 0;
  146. debugLayerEnabled = true;
  147. }
  148. else {
  149. if (BABYLON.Tools.errorsCount > 0) {
  150. debugLayerEnabled = true;
  151. }
  152. document.getElementById("logo").className = "hidden";
  153. document.getElementById("droptext").className = "hidden";
  154. canvas.style.opacity = 1;
  155. if (currentScene.activeCamera.keysUp) {
  156. currentScene.activeCamera.keysUp.push(90); // Z
  157. currentScene.activeCamera.keysUp.push(87); // W
  158. currentScene.activeCamera.keysDown.push(83); // S
  159. currentScene.activeCamera.keysLeft.push(65); // A
  160. currentScene.activeCamera.keysLeft.push(81); // Q
  161. currentScene.activeCamera.keysRight.push(69); // E
  162. currentScene.activeCamera.keysRight.push(68); // D
  163. }
  164. }
  165. if (debugLayerEnabled) {
  166. currentScene.debugLayer.show({ initialTab: debugLayerLastActiveTab });
  167. }
  168. };
  169. var sceneError = function (sceneFile, babylonScene, message) {
  170. document.title = "BabylonJS - " + sceneFile.name;
  171. document.getElementById("logo").className = "";
  172. canvas.style.opacity = 0;
  173. var errorContent = '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button>' + message.replace("file:[object File]", "'" + sceneFile.name + "'") + '</div>';
  174. errorZone.style.display = 'block';
  175. errorZone.innerHTML = errorContent;
  176. // Close button error
  177. errorZone.querySelector('.close').addEventListener('click', function () {
  178. errorZone.style.display = 'none';
  179. });
  180. };
  181. var loadFromAssetUrl = function () {
  182. var rootUrl = BABYLON.Tools.GetFolderPath(assetUrl);
  183. var fileName = BABYLON.Tools.GetFilename(assetUrl);
  184. BABYLON.SceneLoader.LoadAsync(rootUrl, fileName, engine).then(function (scene) {
  185. if (currentScene) {
  186. currentScene.dispose();
  187. }
  188. sceneLoaded({ name: fileName }, scene);
  189. scene.whenReadyAsync().then(function () {
  190. engine.runRenderLoop(function () {
  191. scene.render();
  192. });
  193. });
  194. }).catch(function (reason) {
  195. sceneError({ name: fileName }, null, reason.message || reason);
  196. });
  197. };
  198. if (assetUrl) {
  199. loadFromAssetUrl();
  200. }
  201. else {
  202. filesInput = new BABYLON.FilesInput(engine, null, sceneLoaded, null, null, null, function () { BABYLON.Tools.ClearLogCache() }, null, sceneError);
  203. filesInput.onProcessFileCallback = (function (file, name, extension) {
  204. if (filesInput._filesToLoad && filesInput._filesToLoad.length === 1 && extension) {
  205. if (extension.toLowerCase() === "dds" || extension.toLowerCase() === "env") {
  206. BABYLON.FilesInput.FilesToLoad[name] = file;
  207. skyboxPath = "file:" + file.correctName;
  208. return false;
  209. }
  210. }
  211. return true;
  212. }).bind(this);
  213. filesInput.monitorElementForDragNDrop(canvas);
  214. htmlInput.addEventListener('change', function (event) {
  215. var filestoLoad;
  216. // Handling data transfer via drag'n'drop
  217. if (event && event.dataTransfer && event.dataTransfer.files) {
  218. filesToLoad = event.dataTransfer.files;
  219. }
  220. // Handling files from input files
  221. if (event && event.target && event.target.files) {
  222. filesToLoad = event.target.files;
  223. }
  224. filesInput.loadFiles(event);
  225. }, false);
  226. }
  227. window.addEventListener("keydown", function (event) {
  228. // Press R to reload
  229. if (event.keyCode === 82 && event.target.nodeName !== "INPUT") {
  230. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  231. if (assetUrl) {
  232. loadFromAssetUrl();
  233. }
  234. else {
  235. filesInput.reload();
  236. }
  237. }
  238. });
  239. if (kiosk) {
  240. footer.style.display = "none";
  241. }
  242. btnFullScreen.addEventListener('click', function () {
  243. engine.switchFullscreen(true);
  244. }, false);
  245. btnInspector.addEventListener('click', function () {
  246. if (currentScene) {
  247. if (currentScene.debugLayer.isVisible()) {
  248. debugLayerEnabled = false;
  249. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  250. currentScene.debugLayer.hide();
  251. }
  252. else {
  253. currentScene.debugLayer.show({ initialTab: debugLayerLastActiveTab });
  254. debugLayerEnabled = true;
  255. }
  256. }
  257. }, false);
  258. window.addEventListener("keydown", function (event) {
  259. // Press space to toggle footer
  260. if (event.keyCode === 32 && event.target.nodeName !== "INPUT") {
  261. if (footer.style.display === "none") {
  262. footer.style.display = "block";
  263. }
  264. else {
  265. footer.style.display = "none";
  266. errorZone.style.display = "none";
  267. if (enableDebugLayer) {
  268. currentScene.debugLayer.hide();
  269. enableDebugLayer = false;
  270. }
  271. }
  272. }
  273. });
  274. sizeScene();
  275. window.onresize = function () {
  276. sizeScene();
  277. }
  278. }
  279. function sizeScene() {
  280. let divInspWrapper = document.getElementsByClassName('insp-wrapper')[0];
  281. if (divInspWrapper) {
  282. let divFooter = document.getElementsByClassName('footer')[0];
  283. divInspWrapper.style.height = (document.body.clientHeight - divFooter.clientHeight) + "px";
  284. divInspWrapper.style['max-width'] = document.body.clientWidth + "px";
  285. }
  286. }
  287. // animation
  288. // event on the dropdown
  289. function formatId(name) {
  290. return "data-" + name.replace(/\s/g, '');
  291. }
  292. function displayDropdownContent(display) {
  293. if (display) {
  294. dropdownContent.style.display = "flex";
  295. chevronDown.style.display = "inline";
  296. chevronUp.style.display = "none";
  297. }
  298. else {
  299. dropdownContent.style.display = "none";
  300. chevronDown.style.display = "none";
  301. chevronUp.style.display = "inline";
  302. }
  303. }
  304. dropdownBtn.addEventListener("click", function () {
  305. if (dropdownContent.style.display === "flex") {
  306. displayDropdownContent(false);
  307. }
  308. else {
  309. displayDropdownContent(true);
  310. }
  311. });
  312. function createDropdownLink(group, index) {
  313. var animation = document.createElement("a");
  314. animation.innerHTML = group.name;
  315. animation.setAttribute("id", formatId(group.name + "-" + index));
  316. animation.addEventListener("click", function () {
  317. // stop the current animation group
  318. currentGroup.reset();
  319. currentGroup.stop();
  320. document.getElementById(formatId(currentGroup.name + "-" + currentGroupIndex)).classList.remove("active");
  321. playBtn.classList.remove("play");
  322. playBtn.classList.add("pause");
  323. // start the new animation group
  324. currentGroup = group;
  325. currentGroupIndex = index;
  326. currentGroup.start(true);
  327. this.classList.add("active");
  328. dropdownLabel.innerHTML = currentGroup.name;
  329. // set the slider
  330. slider.setAttribute("min", currentGroup.from);
  331. slider.setAttribute("max", currentGroup.to);
  332. currentSliderValue = currentGroup.from;
  333. slider.value = currentGroup.from;
  334. // hide the content of the dropdown
  335. displayDropdownContent(false);
  336. });
  337. dropdownContent.appendChild(animation);
  338. }
  339. // event on the play/pause button
  340. playBtn.addEventListener("click", function () {
  341. // click on the button to run the animation
  342. if (this.classList.contains("play")) {
  343. this.classList.remove("play");
  344. this.classList.add("pause");
  345. var currentFrame = slider.value;
  346. currentGroup.play(true);
  347. }
  348. // click on the button to pause the animation
  349. else {
  350. this.classList.add("play");
  351. this.classList.remove("pause");
  352. currentGroup.pause();
  353. }
  354. });
  355. // event on the slider
  356. slider.addEventListener("input", function () {
  357. if (playBtn.classList.contains("play")) {
  358. currentGroup.play(true);
  359. currentGroup.goToFrame(this.value);
  360. currentGroup.pause();
  361. } else {
  362. currentGroup.goToFrame(this.value);
  363. }
  364. });
  365. var sliderPause = false;
  366. slider.addEventListener("mousedown", function () {
  367. if (playBtn.classList.contains("pause")) {
  368. sliderPause = true;
  369. playBtn.click();
  370. }
  371. });
  372. slider.addEventListener("mouseup", function () {
  373. if (sliderPause) {
  374. sliderPause = false;
  375. playBtn.click();
  376. }
  377. });