index.js 17 KB

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