index.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  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. // Update the defaults of the GLTFTab in the inspector.
  66. INSPECTOR.GLTFTab._GetLoaderDefaultsAsync().then(function(defaults) {
  67. defaults.validate = true;
  68. });
  69. // Setting up some GLTF values
  70. BABYLON.GLTFFileLoader.IncrementalLoading = false;
  71. BABYLON.SceneLoader.OnPluginActivatedObservable.add(function(plugin) {
  72. currentPluginName = plugin.name;
  73. if (currentPluginName === "gltf") {
  74. plugin.onValidatedObservable.add(function(results) {
  75. if (results.issues.numErrors > 0) {
  76. debugLayerEnabled = true;
  77. debugLayerLastActiveTab = "GLTF";
  78. }
  79. });
  80. }
  81. });
  82. // Resize
  83. window.addEventListener("resize", function() {
  84. engine.resize();
  85. });
  86. var sceneLoaded = function(sceneFile, babylonScene) {
  87. engine.clearInternalTexturesCache();
  88. // Clear dropdown that contains animation names
  89. dropdownContent.innerHTML = "";
  90. animationBar.style.display = "none";
  91. currentGroup = null;
  92. if (babylonScene.animationGroups.length > 0) {
  93. animationBar.style.display = "flex";
  94. for (var index = 0; index < babylonScene.animationGroups.length; index++) {
  95. var group = babylonScene.animationGroups[index];
  96. createDropdownLink(group, index);
  97. }
  98. currentGroup = babylonScene.animationGroups[0];
  99. currentGroupIndex = 0;
  100. document.getElementById(formatId(currentGroup.name + "-" + currentGroupIndex)).click();
  101. }
  102. // Sync the slider with the current frame
  103. babylonScene.registerBeforeRender(function() {
  104. if (currentGroup != null && currentGroup.targetedAnimations[0].animation.runtimeAnimations[0] != null) {
  105. var currentValue = slider.valueAsNumber;
  106. var newValue = currentGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame;
  107. var range = Math.abs(currentGroup.from - currentGroup.to);
  108. slider.value = newValue;
  109. }
  110. });
  111. // Clear the error
  112. errorZone.style.display = 'none';
  113. btnFullScreen.classList.remove("hidden");
  114. btnInspector.classList.remove("hidden");
  115. currentScene = babylonScene;
  116. document.title = "BabylonJS - " + sceneFile.name;
  117. // Fix for IE, otherwise it will change the default filter for files selection after first use
  118. htmlInput.value = "";
  119. // Attach camera to canvas inputs
  120. if (!currentScene.activeCamera || currentScene.lights.length === 0) {
  121. currentScene.createDefaultCamera(true);
  122. if (cameraPosition) {
  123. currentScene.activeCamera.setPosition(cameraPosition);
  124. }
  125. else {
  126. if (currentPluginName === "gltf") {
  127. // glTF assets use a +Z forward convention while the default camera faces +Z. Rotate the camera to look at the front of the asset.
  128. currentScene.activeCamera.alpha += Math.PI;
  129. }
  130. // Enable camera's behaviors
  131. currentScene.activeCamera.useFramingBehavior = true;
  132. var framingBehavior = currentScene.activeCamera.getBehaviorByName("Framing");
  133. framingBehavior.framingTime = 0;
  134. framingBehavior.elevationReturnTime = -1;
  135. if (currentScene.meshes.length) {
  136. var worldExtends = currentScene.getWorldExtends();
  137. currentScene.activeCamera.lowerRadiusLimit = null;
  138. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  139. }
  140. }
  141. currentScene.activeCamera.pinchPrecision = 200 / currentScene.activeCamera.radius;
  142. currentScene.activeCamera.upperRadiusLimit = 5 * currentScene.activeCamera.radius;
  143. currentScene.activeCamera.wheelDeltaPercentage = 0.01;
  144. currentScene.activeCamera.pinchDeltaPercentage = 0.01;
  145. }
  146. currentScene.activeCamera.attachControl(canvas);
  147. // Lighting
  148. if (currentPluginName === "gltf") {
  149. if (!currentScene.environmentTexture) {
  150. currentScene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(skyboxPath, currentScene);
  151. }
  152. currentSkybox = currentScene.createDefaultSkybox(currentScene.environmentTexture, true, (currentScene.activeCamera.maxZ - currentScene.activeCamera.minZ) / 2, 0.3, false);
  153. }
  154. else {
  155. currentScene.createDefaultLight();
  156. }
  157. // In case of error during loading, meshes will be empty and clearColor is set to red
  158. if (currentScene.meshes.length === 0 && currentScene.clearColor.r === 1 && currentScene.clearColor.g === 0 && currentScene.clearColor.b === 0) {
  159. document.getElementById("logo").className = "";
  160. canvas.style.opacity = 0;
  161. debugLayerEnabled = true;
  162. }
  163. else {
  164. if (BABYLON.Tools.errorsCount > 0) {
  165. debugLayerEnabled = true;
  166. }
  167. document.getElementById("logo").className = "hidden";
  168. document.getElementById("droptext").className = "hidden";
  169. canvas.style.opacity = 1;
  170. if (currentScene.activeCamera.keysUp) {
  171. currentScene.activeCamera.keysUp.push(90); // Z
  172. currentScene.activeCamera.keysUp.push(87); // W
  173. currentScene.activeCamera.keysDown.push(83); // S
  174. currentScene.activeCamera.keysLeft.push(65); // A
  175. currentScene.activeCamera.keysLeft.push(81); // Q
  176. currentScene.activeCamera.keysRight.push(69); // E
  177. currentScene.activeCamera.keysRight.push(68); // D
  178. }
  179. }
  180. if (debugLayerEnabled) {
  181. currentScene.debugLayer.show({ initialTab: debugLayerLastActiveTab });
  182. }
  183. };
  184. var sceneError = function(sceneFile, babylonScene, message) {
  185. document.title = "BabylonJS - " + sceneFile.name;
  186. document.getElementById("logo").className = "";
  187. canvas.style.opacity = 0;
  188. 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>';
  189. errorZone.style.display = 'block';
  190. errorZone.innerHTML = errorContent;
  191. // Close button error
  192. errorZone.querySelector('.close').addEventListener('click', function() {
  193. errorZone.style.display = 'none';
  194. });
  195. };
  196. var loadFromAssetUrl = function() {
  197. var rootUrl = BABYLON.Tools.GetFolderPath(assetUrl);
  198. var fileName = BABYLON.Tools.GetFilename(assetUrl);
  199. BABYLON.SceneLoader.LoadAsync(rootUrl, fileName, engine).then(function(scene) {
  200. if (currentScene) {
  201. currentScene.dispose();
  202. }
  203. sceneLoaded({ name: fileName }, scene);
  204. scene.whenReadyAsync().then(function() {
  205. engine.runRenderLoop(function() {
  206. scene.render();
  207. });
  208. });
  209. }).catch(function(reason) {
  210. sceneError({ name: fileName }, null, reason.message || reason);
  211. });
  212. };
  213. if (assetUrl) {
  214. loadFromAssetUrl();
  215. }
  216. else {
  217. var startProcessingFiles = function() {
  218. BABYLON.Tools.ClearLogCache();
  219. if (currentScene) {
  220. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  221. }
  222. };
  223. filesInput = new BABYLON.FilesInput(engine, null, sceneLoaded, null, null, null, startProcessingFiles, null, sceneError);
  224. filesInput.onProcessFileCallback = (function(file, name, extension) {
  225. if (filesInput._filesToLoad && filesInput._filesToLoad.length === 1 && extension) {
  226. if (extension.toLowerCase() === "dds" || extension.toLowerCase() === "env") {
  227. BABYLON.FilesInput.FilesToLoad[name] = file;
  228. skyboxPath = "file:" + file.correctName;
  229. return false;
  230. }
  231. }
  232. return true;
  233. }).bind(this);
  234. filesInput.monitorElementForDragNDrop(canvas);
  235. htmlInput.addEventListener('change', function(event) {
  236. var filestoLoad;
  237. // Handling data transfer via drag'n'drop
  238. if (event && event.dataTransfer && event.dataTransfer.files) {
  239. filesToLoad = event.dataTransfer.files;
  240. }
  241. // Handling files from input files
  242. if (event && event.target && event.target.files) {
  243. filesToLoad = event.target.files;
  244. }
  245. filesInput.loadFiles(event);
  246. }, false);
  247. }
  248. window.addEventListener("keydown", function(event) {
  249. // Press R to reload
  250. if (event.keyCode === 82 && event.target.nodeName !== "INPUT" && currentScene) {
  251. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  252. if (assetUrl) {
  253. loadFromAssetUrl();
  254. }
  255. else {
  256. filesInput.reload();
  257. }
  258. }
  259. });
  260. if (kiosk) {
  261. footer.style.display = "none";
  262. }
  263. btnFullScreen.addEventListener('click', function() {
  264. engine.switchFullscreen(true);
  265. }, false);
  266. btnInspector.addEventListener('click', function() {
  267. if (currentScene) {
  268. if (currentScene.debugLayer.isVisible()) {
  269. debugLayerEnabled = false;
  270. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  271. currentScene.debugLayer.hide();
  272. }
  273. else {
  274. currentScene.debugLayer.show({ initialTab: debugLayerLastActiveTab });
  275. debugLayerEnabled = true;
  276. }
  277. }
  278. }, false);
  279. window.addEventListener("keydown", function(event) {
  280. // Press space to toggle footer
  281. if (event.keyCode === 32 && event.target.nodeName !== "INPUT") {
  282. if (footer.style.display === "none") {
  283. footer.style.display = "block";
  284. }
  285. else {
  286. footer.style.display = "none";
  287. errorZone.style.display = "none";
  288. if (debugLayerEnabled) {
  289. currentScene.debugLayer.hide();
  290. debugLayerEnabled = false;
  291. }
  292. }
  293. }
  294. });
  295. sizeScene();
  296. window.onresize = function() {
  297. sizeScene();
  298. }
  299. }
  300. function sizeScene() {
  301. let divInspWrapper = document.getElementsByClassName('insp-wrapper')[0];
  302. if (divInspWrapper) {
  303. let divFooter = document.getElementsByClassName('footer')[0];
  304. divInspWrapper.style.height = (document.body.clientHeight - divFooter.clientHeight) + "px";
  305. divInspWrapper.style['max-width'] = document.body.clientWidth + "px";
  306. }
  307. }
  308. // animation
  309. // event on the dropdown
  310. function formatId(name) {
  311. return "data-" + name.replace(/\s/g, '');
  312. }
  313. function displayDropdownContent(display) {
  314. if (display) {
  315. dropdownContent.style.display = "flex";
  316. chevronDown.style.display = "inline";
  317. chevronUp.style.display = "none";
  318. }
  319. else {
  320. dropdownContent.style.display = "none";
  321. chevronDown.style.display = "none";
  322. chevronUp.style.display = "inline";
  323. }
  324. }
  325. dropdownBtn.addEventListener("click", function() {
  326. if (dropdownContent.style.display === "flex") {
  327. displayDropdownContent(false);
  328. }
  329. else {
  330. displayDropdownContent(true);
  331. }
  332. });
  333. function createDropdownLink(group, index) {
  334. var animation = document.createElement("a");
  335. animation.innerHTML = group.name;
  336. animation.title = group.name;
  337. animation.setAttribute("id", formatId(group.name + "-" + index));
  338. animation.addEventListener("click", function() {
  339. // stop the current animation group
  340. currentGroup.reset();
  341. currentGroup.stop();
  342. document.getElementById(formatId(currentGroup.name + "-" + currentGroupIndex)).classList.remove("active");
  343. playBtn.classList.remove("play");
  344. playBtn.classList.add("pause");
  345. // start the new animation group
  346. currentGroup = group;
  347. currentGroupIndex = index;
  348. currentGroup.start(true);
  349. this.classList.add("active");
  350. dropdownLabel.innerHTML = currentGroup.name;
  351. dropdownLabel.title = currentGroup.name;
  352. // set the slider
  353. slider.setAttribute("min", currentGroup.from);
  354. slider.setAttribute("max", currentGroup.to);
  355. currentSliderValue = currentGroup.from;
  356. slider.value = currentGroup.from;
  357. // hide the content of the dropdown
  358. displayDropdownContent(false);
  359. });
  360. dropdownContent.appendChild(animation);
  361. }
  362. // event on the play/pause button
  363. playBtn.addEventListener("click", function() {
  364. // click on the button to run the animation
  365. if (this.classList.contains("play")) {
  366. this.classList.remove("play");
  367. this.classList.add("pause");
  368. var currentFrame = slider.value;
  369. currentGroup.play(true);
  370. }
  371. // click on the button to pause the animation
  372. else {
  373. this.classList.add("play");
  374. this.classList.remove("pause");
  375. currentGroup.pause();
  376. }
  377. });
  378. // event on the slider
  379. slider.addEventListener("input", function() {
  380. if (playBtn.classList.contains("play")) {
  381. currentGroup.play(true);
  382. currentGroup.goToFrame(this.value);
  383. currentGroup.pause();
  384. } else {
  385. currentGroup.goToFrame(this.value);
  386. }
  387. });
  388. var sliderPause = false;
  389. slider.addEventListener("mousedown", function() {
  390. if (playBtn.classList.contains("pause")) {
  391. sliderPause = true;
  392. playBtn.click();
  393. }
  394. });
  395. slider.addEventListener("mouseup", function() {
  396. if (sliderPause) {
  397. sliderPause = false;
  398. playBtn.click();
  399. }
  400. });