index.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. if (babylonScene.animationGroups.length > 0) {
  82. animationBar.style.display = "flex";
  83. for (var index = 0; index < babylonScene.animationGroups.length; index++) {
  84. var group = babylonScene.animationGroups[index];
  85. createDropdownLink(group, index);
  86. }
  87. currentGroupIndex = playFirstAnimationGroup ? 0 : babylonScene.animationGroups.length - 1;
  88. currentGroup = babylonScene.animationGroups[currentGroupIndex];
  89. currentGroup.play(true);
  90. }
  91. // Sync the slider with the current frame
  92. babylonScene.registerBeforeRender(function() {
  93. if (currentGroup) {
  94. var targetedAnimations = currentGroup.targetedAnimations;
  95. if (targetedAnimations.length > 0) {
  96. var runtimeAnimations = currentGroup.targetedAnimations[0].animation.runtimeAnimations;
  97. if (runtimeAnimations.length > 0) {
  98. slider.value = runtimeAnimations[0].currentFrame;
  99. }
  100. }
  101. }
  102. });
  103. // Clear the error
  104. errorZone.style.display = 'none';
  105. }
  106. var assetContainerLoaded = function (sceneFile, babylonScene) {
  107. anyLoaded(babylonScene);
  108. }
  109. var sceneLoaded = function (sceneFile, babylonScene) {
  110. engine.clearInternalTexturesCache();
  111. anyLoaded(babylonScene, true);
  112. // Fix for IE, otherwise it will change the default filter for files selection after first use
  113. htmlInput.value = "";
  114. currentScene = babylonScene;
  115. babylonScene.onAnimationFileImportedObservable.add((scene) => {
  116. anyLoaded(scene, false);
  117. });
  118. document.title = "Babylon.js - " + sceneFile.name;
  119. btnInspector.classList.remove("hidden");
  120. btnEnvironment.classList.remove("hidden");
  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. var pbrPresent = false;
  158. for (var i = 0; i < currentScene.materials.length; i++) {
  159. if (currentScene.materials[i]._transparencyMode !== undefined) {
  160. pbrPresent = true;
  161. break;
  162. }
  163. }
  164. if (pbrPresent) {
  165. if (!currentScene.environmentTexture) {
  166. currentScene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(skyboxPath, currentScene);
  167. }
  168. }
  169. else {
  170. currentScene.createDefaultLight();
  171. }
  172. }
  173. // In case of error during loading, meshes will be empty and clearColor is set to red
  174. if (currentScene.meshes.length === 0 && currentScene.clearColor.r === 1 && currentScene.clearColor.g === 0 && currentScene.clearColor.b === 0) {
  175. document.getElementById("logo").className = "";
  176. canvas.style.opacity = 0;
  177. debugLayerEnabled = true;
  178. }
  179. else {
  180. if (BABYLON.Tools.errorsCount > 0) {
  181. debugLayerEnabled = true;
  182. }
  183. document.getElementById("logo").className = "hidden";
  184. document.getElementById("droptext").className = "hidden";
  185. canvas.style.opacity = 1;
  186. if (currentScene.activeCamera.keysUp) {
  187. currentScene.activeCamera.keysUp.push(90); // Z
  188. currentScene.activeCamera.keysUp.push(87); // W
  189. currentScene.activeCamera.keysDown.push(83); // S
  190. currentScene.activeCamera.keysLeft.push(65); // A
  191. currentScene.activeCamera.keysLeft.push(81); // Q
  192. currentScene.activeCamera.keysRight.push(69); // E
  193. currentScene.activeCamera.keysRight.push(68); // D
  194. }
  195. }
  196. if (debugLayerEnabled) {
  197. currentScene.debugLayer.show();
  198. }
  199. };
  200. var sceneError = function(sceneFile, babylonScene, message) {
  201. document.title = "Babylon.js - " + sceneFile.name;
  202. document.getElementById("logo").className = "";
  203. canvas.style.opacity = 0;
  204. 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>';
  205. errorZone.style.display = 'block';
  206. errorZone.innerHTML = errorContent;
  207. // Close button error
  208. errorZone.querySelector('.close').addEventListener('click', function() {
  209. errorZone.style.display = 'none';
  210. });
  211. };
  212. var loadFromAssetUrl = function() {
  213. var rootUrl = BABYLON.Tools.GetFolderPath(assetUrl);
  214. var fileName = BABYLON.Tools.GetFilename(assetUrl);
  215. BABYLON.SceneLoader.LoadAsync(rootUrl, fileName, engine).then(function(scene) {
  216. if (currentScene) {
  217. currentScene.dispose();
  218. }
  219. sceneLoaded({ name: fileName }, scene);
  220. scene.whenReadyAsync().then(function() {
  221. engine.runRenderLoop(function() {
  222. scene.render();
  223. });
  224. });
  225. }).catch(function(reason) {
  226. sceneError({ name: fileName }, null, reason.message || reason);
  227. });
  228. };
  229. if (assetUrl) {
  230. loadFromAssetUrl();
  231. }
  232. else {
  233. var startProcessingFiles = function() {
  234. BABYLON.Tools.ClearLogCache();
  235. };
  236. filesInput = new BABYLON.FilesInput(engine, null, sceneLoaded, null, null, null, startProcessingFiles, null, sceneError);
  237. filesInput.onProcessFileCallback = (function(file, name, extension) {
  238. if (filesInput._filesToLoad && filesInput._filesToLoad.length === 1 && extension) {
  239. if (extension.toLowerCase() === "dds" || extension.toLowerCase() === "env") {
  240. BABYLON.FilesInput.FilesToLoad[name] = file;
  241. skyboxPath = "file:" + file.correctName;
  242. return false;
  243. }
  244. }
  245. return true;
  246. }).bind(this);
  247. filesInput.monitorElementForDragNDrop(canvas);
  248. htmlInput.addEventListener('change', function(event) {
  249. // Handling data transfer via drag'n'drop
  250. if (event && event.dataTransfer && event.dataTransfer.files) {
  251. filesToLoad = event.dataTransfer.files;
  252. }
  253. // Handling files from input files
  254. if (event && event.target && event.target.files) {
  255. filesToLoad = event.target.files;
  256. }
  257. filesInput.loadFiles(event);
  258. }, false);
  259. }
  260. window.addEventListener("keydown", function(event) {
  261. // Press R to reload
  262. if (event.keyCode === 82 && event.target.nodeName !== "INPUT" && currentScene) {
  263. if (assetUrl) {
  264. loadFromAssetUrl();
  265. }
  266. else {
  267. filesInput.reload();
  268. }
  269. }
  270. });
  271. btnInspector.addEventListener('click', function() {
  272. if (currentScene) {
  273. if (currentScene.debugLayer.isVisible()) {
  274. debugLayerEnabled = false;
  275. currentScene.debugLayer.hide();
  276. }
  277. else {
  278. currentScene.debugLayer.show();
  279. debugLayerEnabled = true;
  280. }
  281. }
  282. }, false);
  283. window.addEventListener("keydown", function(event) {
  284. // Press space to toggle footer
  285. if (event.keyCode === 32 && event.target.nodeName !== "INPUT") {
  286. if (footer.style.display === "none") {
  287. footer.style.display = "block";
  288. canvasZone.style.height = "calc(100% - 56px)";
  289. if (debugLayerEnabled) {
  290. currentScene.debugLayer.show();
  291. }
  292. engine.resize();
  293. }
  294. else {
  295. footer.style.display = "none";
  296. canvasZone.style.height = "100%";
  297. errorZone.style.display = "none";
  298. engine.resize();
  299. if (currentScene.debugLayer.isVisible()) {
  300. currentScene.debugLayer.hide();
  301. }
  302. }
  303. }
  304. });
  305. sizeScene();
  306. window.onresize = function() {
  307. sizeScene();
  308. }
  309. }
  310. function sizeScene() {
  311. let divInspWrapper = document.getElementsByClassName('insp-wrapper')[0];
  312. if (divInspWrapper) {
  313. let divFooter = document.getElementsByClassName('footer')[0];
  314. divInspWrapper.style.height = (document.body.clientHeight - divFooter.clientHeight) + "px";
  315. divInspWrapper.style['max-width'] = document.body.clientWidth + "px";
  316. }
  317. }