index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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 tags
  9. var footer = document.getElementById("footer");
  10. var canvas = document.getElementById("renderCanvas");
  11. var canvasZone = document.getElementById("canvasZone");
  12. // Check URL
  13. var indexOf = location.href.indexOf("?");
  14. if (indexOf !== -1) {
  15. var params = location.href.substr(indexOf + 1).split("&");
  16. for (var index = 0; index < params.length; index++) {
  17. var param = params[index].split("=");
  18. var name = param[0];
  19. var value = param[1];
  20. switch (name) {
  21. case "assetUrl": {
  22. assetUrl = value;
  23. break;
  24. }
  25. case "cameraPosition": {
  26. cameraPosition = BABYLON.Vector3.FromArray(value.split(",").map(function(component) { return +component; }));
  27. break;
  28. }
  29. case "kiosk": {
  30. kiosk = value === "true" ? true : false;
  31. break;
  32. }
  33. }
  34. }
  35. }
  36. if (kiosk) {
  37. footer.style.display = "none";
  38. canvasZone.style.height = "100%";
  39. }
  40. if (BABYLON.Engine.isSupported()) {
  41. var engine = new BABYLON.Engine(canvas, true, { premultipliedAlpha: false, preserveDrawingBuffer: true });
  42. var htmlInput = document.getElementById("files");
  43. var btnInspector = document.getElementById("btnInspector");
  44. var errorZone = document.getElementById("errorZone");
  45. var filesInput;
  46. var currentScene;
  47. var currentSkybox;
  48. var currentPluginName;
  49. var skyboxPath = skyboxes[defaultSkyboxIndex];
  50. var debugLayerEnabled = false;
  51. engine.loadingUIBackgroundColor = "#2A2342";
  52. btnInspector.classList.add("hidden");
  53. btnEnvironment.classList.add("hidden");
  54. canvas.addEventListener("contextmenu", function(evt) {
  55. evt.preventDefault();
  56. }, false);
  57. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  58. // This is really important to tell Babylon.js to use decomposeLerp and matrix interpolation
  59. BABYLON.Animation.AllowMatricesInterpolation = true;
  60. // Setting up some GLTF values
  61. BABYLON.GLTFFileLoader.IncrementalLoading = false;
  62. BABYLON.SceneLoader.OnPluginActivatedObservable.add(function(plugin) {
  63. currentPluginName = plugin.name;
  64. if (currentPluginName === "gltf") {
  65. plugin.onValidatedObservable.add(function(results) {
  66. if (results.issues.numErrors > 0) {
  67. debugLayerEnabled = true;
  68. }
  69. });
  70. }
  71. });
  72. // Resize
  73. window.addEventListener("resize", function() {
  74. engine.resize();
  75. });
  76. var anyLoaded = function(babylonScene, playFirstAnimationGroup) {
  77. // Clear dropdown that contains animation names
  78. dropdownContent.innerHTML = "";
  79. animationBar.style.display = "none";
  80. currentGroup = null;
  81. babylonScene.skipFrustumClipping = true;
  82. if (babylonScene.animationGroups.length > 0) {
  83. animationBar.style.display = "flex";
  84. for (var index = 0; index < babylonScene.animationGroups.length; index++) {
  85. var group = babylonScene.animationGroups[index];
  86. createDropdownLink(group, index);
  87. }
  88. currentGroupIndex = playFirstAnimationGroup ? 0 : babylonScene.animationGroups.length - 1;
  89. currentGroup = babylonScene.animationGroups[currentGroupIndex];
  90. currentGroup.play(true);
  91. }
  92. // Sync the slider with the current frame
  93. babylonScene.registerBeforeRender(function() {
  94. if (currentGroup) {
  95. var targetedAnimations = currentGroup.targetedAnimations;
  96. if (targetedAnimations.length > 0) {
  97. var runtimeAnimations = currentGroup.targetedAnimations[0].animation.runtimeAnimations;
  98. if (runtimeAnimations.length > 0) {
  99. slider.value = runtimeAnimations[0].currentFrame;
  100. }
  101. }
  102. }
  103. });
  104. // Clear the error
  105. errorZone.style.display = 'none';
  106. }
  107. var assetContainerLoaded = function (sceneFile, babylonScene) {
  108. anyLoaded(babylonScene);
  109. }
  110. var sceneLoaded = function (sceneFile, babylonScene) {
  111. engine.clearInternalTexturesCache();
  112. anyLoaded(babylonScene, true);
  113. // Fix for IE, otherwise it will change the default filter for files selection after first use
  114. htmlInput.value = "";
  115. currentScene = babylonScene;
  116. babylonScene.onAnimationFileImportedObservable.add(function (scene) {
  117. anyLoaded(scene, false);
  118. });
  119. document.title = "Babylon.js - " + sceneFile.name;
  120. btnInspector.classList.remove("hidden");
  121. btnEnvironment.classList.remove("hidden");
  122. // Attach camera to canvas inputs
  123. if (!currentScene.activeCamera || currentScene.lights.length === 0) {
  124. currentScene.createDefaultCamera(true);
  125. if (cameraPosition) {
  126. currentScene.activeCamera.setPosition(cameraPosition);
  127. }
  128. else {
  129. if (currentPluginName === "gltf") {
  130. // glTF assets use a +Z forward convention while the default camera faces +Z. Rotate the camera to look at the front of the asset.
  131. currentScene.activeCamera.alpha += Math.PI;
  132. }
  133. // Enable camera's behaviors
  134. currentScene.activeCamera.useFramingBehavior = true;
  135. var framingBehavior = currentScene.activeCamera.getBehaviorByName("Framing");
  136. framingBehavior.framingTime = 0;
  137. framingBehavior.elevationReturnTime = -1;
  138. if (currentScene.meshes.length) {
  139. currentScene.activeCamera.lowerRadiusLimit = null;
  140. var worldExtends = currentScene.getWorldExtends(function (mesh) {
  141. return mesh.isVisible && mesh.isEnabled();
  142. });
  143. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  144. }
  145. }
  146. currentScene.activeCamera.pinchPrecision = 200 / currentScene.activeCamera.radius;
  147. currentScene.activeCamera.upperRadiusLimit = 5 * currentScene.activeCamera.radius;
  148. currentScene.activeCamera.wheelDeltaPercentage = 0.01;
  149. currentScene.activeCamera.pinchDeltaPercentage = 0.01;
  150. }
  151. currentScene.activeCamera.attachControl(canvas);
  152. // Lighting
  153. if (currentPluginName === "gltf") {
  154. if (!currentScene.environmentTexture) {
  155. currentScene.environmentTexture = loadSkyboxPathTexture(skyboxPath, currentScene);
  156. }
  157. currentSkybox = currentScene.createDefaultSkybox(currentScene.environmentTexture, true, (currentScene.activeCamera.maxZ - currentScene.activeCamera.minZ) / 2, 0.3, false);
  158. }
  159. else {
  160. var pbrPresent = false;
  161. for (var i = 0; i < currentScene.materials.length; i++) {
  162. if (currentScene.materials[i]._transparencyMode !== undefined) {
  163. pbrPresent = true;
  164. break;
  165. }
  166. }
  167. if (pbrPresent) {
  168. if (!currentScene.environmentTexture) {
  169. currentScene.environmentTexture = loadSkyboxPathTexture(skyboxPath, currentScene);
  170. }
  171. }
  172. else {
  173. currentScene.createDefaultLight();
  174. }
  175. }
  176. // In case of error during loading, meshes will be empty and clearColor is set to red
  177. if (currentScene.meshes.length === 0 && currentScene.clearColor.r === 1 && currentScene.clearColor.g === 0 && currentScene.clearColor.b === 0) {
  178. document.getElementById("logo").className = "";
  179. canvas.style.opacity = 0;
  180. debugLayerEnabled = true;
  181. }
  182. else {
  183. if (BABYLON.Tools.errorsCount > 0) {
  184. debugLayerEnabled = true;
  185. }
  186. document.getElementById("logo").className = "hidden";
  187. document.getElementById("droptext").className = "hidden";
  188. canvas.style.opacity = 1;
  189. if (currentScene.activeCamera.keysUp) {
  190. currentScene.activeCamera.keysUp.push(90); // Z
  191. currentScene.activeCamera.keysUp.push(87); // W
  192. currentScene.activeCamera.keysDown.push(83); // S
  193. currentScene.activeCamera.keysLeft.push(65); // A
  194. currentScene.activeCamera.keysLeft.push(81); // Q
  195. currentScene.activeCamera.keysRight.push(69); // E
  196. currentScene.activeCamera.keysRight.push(68); // D
  197. }
  198. }
  199. if (debugLayerEnabled) {
  200. currentScene.debugLayer.show();
  201. }
  202. };
  203. var sceneError = function(sceneFile, babylonScene, message) {
  204. document.title = "Babylon.js - " + sceneFile.name;
  205. document.getElementById("logo").className = "";
  206. canvas.style.opacity = 0;
  207. 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>';
  208. errorZone.style.display = 'block';
  209. errorZone.innerHTML = errorContent;
  210. // Close button error
  211. errorZone.querySelector('.close').addEventListener('click', function() {
  212. errorZone.style.display = 'none';
  213. });
  214. };
  215. var loadFromAssetUrl = function() {
  216. var rootUrl = BABYLON.Tools.GetFolderPath(assetUrl);
  217. var fileName = BABYLON.Tools.GetFilename(assetUrl);
  218. BABYLON.SceneLoader.LoadAsync(rootUrl, fileName, engine).then(function(scene) {
  219. if (currentScene) {
  220. currentScene.dispose();
  221. }
  222. sceneLoaded({ name: fileName }, scene);
  223. scene.whenReadyAsync().then(function() {
  224. engine.runRenderLoop(function() {
  225. scene.render();
  226. });
  227. });
  228. }).catch(function(reason) {
  229. sceneError({ name: fileName }, null, reason.message || reason);
  230. });
  231. };
  232. if (assetUrl) {
  233. loadFromAssetUrl();
  234. }
  235. else {
  236. var startProcessingFiles = function() {
  237. BABYLON.Tools.ClearLogCache();
  238. };
  239. filesInput = new BABYLON.FilesInput(engine, null, sceneLoaded, null, null, null, startProcessingFiles, null, sceneError);
  240. filesInput.onProcessFileCallback = (function(file, name, extension) {
  241. if (filesInput._filesToLoad && filesInput._filesToLoad.length === 1 && extension) {
  242. if (extension.toLowerCase() === "dds" ||
  243. extension.toLowerCase() === "env" ||
  244. extension.toLowerCase() === "hdr") {
  245. BABYLON.FilesInput.FilesToLoad[name] = file;
  246. skyboxPath = "file:" + file.correctName;
  247. return false;
  248. }
  249. }
  250. return true;
  251. }).bind(this);
  252. filesInput.monitorElementForDragNDrop(canvas);
  253. htmlInput.addEventListener('change', function(event) {
  254. // Handling data transfer via drag'n'drop
  255. if (event && event.dataTransfer && event.dataTransfer.files) {
  256. filesToLoad = event.dataTransfer.files;
  257. }
  258. // Handling files from input files
  259. if (event && event.target && event.target.files) {
  260. filesToLoad = event.target.files;
  261. }
  262. filesInput.loadFiles(event);
  263. }, false);
  264. }
  265. window.addEventListener("keydown", function(event) {
  266. // Press R to reload
  267. if (event.keyCode === 82 && event.target.nodeName !== "INPUT" && currentScene) {
  268. if (assetUrl) {
  269. loadFromAssetUrl();
  270. }
  271. else {
  272. filesInput.reload();
  273. }
  274. }
  275. });
  276. btnInspector.addEventListener('click', function() {
  277. if (currentScene) {
  278. if (currentScene.debugLayer.isVisible()) {
  279. debugLayerEnabled = false;
  280. currentScene.debugLayer.hide();
  281. }
  282. else {
  283. currentScene.debugLayer.show();
  284. debugLayerEnabled = true;
  285. }
  286. }
  287. }, false);
  288. window.addEventListener("keydown", function(event) {
  289. // Press space to toggle footer
  290. if (event.keyCode === 32 && event.target.nodeName !== "INPUT") {
  291. if (footer.style.display === "none") {
  292. footer.style.display = "block";
  293. canvasZone.style.height = "calc(100% - 56px)";
  294. if (debugLayerEnabled) {
  295. currentScene.debugLayer.show();
  296. }
  297. engine.resize();
  298. }
  299. else {
  300. footer.style.display = "none";
  301. canvasZone.style.height = "100%";
  302. errorZone.style.display = "none";
  303. engine.resize();
  304. if (currentScene.debugLayer.isVisible()) {
  305. currentScene.debugLayer.hide();
  306. }
  307. }
  308. }
  309. });
  310. sizeScene();
  311. window.onresize = function() {
  312. sizeScene();
  313. }
  314. }
  315. function sizeScene() {
  316. let divInspWrapper = document.getElementsByClassName('insp-wrapper')[0];
  317. if (divInspWrapper) {
  318. let divFooter = document.getElementsByClassName('footer')[0];
  319. divInspWrapper.style.height = (document.body.clientHeight - divFooter.clientHeight) + "px";
  320. divInspWrapper.style['max-width'] = document.body.clientWidth + "px";
  321. }
  322. }