index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. variantBar.style.display = "none";
  81. currentGroup = null;
  82. babylonScene.skipFrustumClipping = true;
  83. if (babylonScene.animationGroups.length > 0) {
  84. animationBar.style.display = "flex";
  85. for (var index = 0; index < babylonScene.animationGroups.length; index++) {
  86. var group = babylonScene.animationGroups[index];
  87. createDropdownLink(group, index);
  88. }
  89. currentGroupIndex = playFirstAnimationGroup ? 0 : babylonScene.animationGroups.length - 1;
  90. currentGroup = babylonScene.animationGroups[currentGroupIndex];
  91. currentGroup.play(true);
  92. }
  93. if (babylonScene.meshes.length > 0) {
  94. let root = babylonScene.meshes[0];
  95. let variants = BABYLON.GLTF2.Loader.Extensions.KHR_materials_variants.GetAvailableVariants(root);
  96. if (variants && variants.length > 0) {
  97. variantBar.style.display = "flex";
  98. variantDropdownContent.innerHTML = "";
  99. variantDropdownLabel.innerHTML = "Default";
  100. variantDropdownLabel.title = "Default";
  101. for (var index = 0; index < variants.length; index++) {
  102. createVariantDropdownLink(variants[index], root);
  103. }
  104. }
  105. }
  106. // Sync the slider with the current frame
  107. babylonScene.registerBeforeRender(function() {
  108. if (currentGroup) {
  109. var targetedAnimations = currentGroup.targetedAnimations;
  110. if (targetedAnimations.length > 0) {
  111. var runtimeAnimations = currentGroup.targetedAnimations[0].animation.runtimeAnimations;
  112. if (runtimeAnimations.length > 0) {
  113. slider.value = runtimeAnimations[0].currentFrame;
  114. }
  115. }
  116. }
  117. });
  118. // Clear the error
  119. errorZone.style.display = 'none';
  120. }
  121. var assetContainerLoaded = function (sceneFile, babylonScene) {
  122. anyLoaded(babylonScene);
  123. }
  124. var sceneLoaded = function (sceneFile, babylonScene) {
  125. engine.clearInternalTexturesCache();
  126. anyLoaded(babylonScene, true);
  127. // Fix for IE, otherwise it will change the default filter for files selection after first use
  128. htmlInput.value = "";
  129. currentScene = babylonScene;
  130. babylonScene.onAnimationFileImportedObservable.add(function (scene) {
  131. anyLoaded(scene, false);
  132. });
  133. document.title = "Babylon.js - " + sceneFile.name;
  134. btnInspector.classList.remove("hidden");
  135. btnEnvironment.classList.remove("hidden");
  136. // Attach camera to canvas inputs
  137. if (!currentScene.activeCamera || currentScene.lights.length === 0) {
  138. currentScene.createDefaultCamera(true);
  139. if (cameraPosition) {
  140. currentScene.activeCamera.setPosition(cameraPosition);
  141. }
  142. else {
  143. if (currentPluginName === "gltf") {
  144. // glTF assets use a +Z forward convention while the default camera faces +Z. Rotate the camera to look at the front of the asset.
  145. currentScene.activeCamera.alpha += Math.PI;
  146. }
  147. // Enable camera's behaviors
  148. currentScene.activeCamera.useFramingBehavior = true;
  149. var framingBehavior = currentScene.activeCamera.getBehaviorByName("Framing");
  150. framingBehavior.framingTime = 0;
  151. framingBehavior.elevationReturnTime = -1;
  152. if (currentScene.meshes.length) {
  153. currentScene.activeCamera.lowerRadiusLimit = null;
  154. var worldExtends = currentScene.getWorldExtends(function (mesh) {
  155. return mesh.isVisible && mesh.isEnabled();
  156. });
  157. framingBehavior.zoomOnBoundingInfo(worldExtends.min, worldExtends.max);
  158. }
  159. }
  160. currentScene.activeCamera.pinchPrecision = 200 / currentScene.activeCamera.radius;
  161. currentScene.activeCamera.upperRadiusLimit = 5 * currentScene.activeCamera.radius;
  162. currentScene.activeCamera.wheelDeltaPercentage = 0.01;
  163. currentScene.activeCamera.pinchDeltaPercentage = 0.01;
  164. }
  165. currentScene.activeCamera.attachControl(canvas);
  166. // Lighting
  167. if (currentPluginName === "gltf") {
  168. if (!currentScene.environmentTexture) {
  169. currentScene.environmentTexture = loadSkyboxPathTexture(skyboxPath, currentScene);
  170. }
  171. currentSkybox = currentScene.createDefaultSkybox(currentScene.environmentTexture, true, (currentScene.activeCamera.maxZ - currentScene.activeCamera.minZ) / 2, 0.3, false);
  172. }
  173. else {
  174. var pbrPresent = false;
  175. for (var i = 0; i < currentScene.materials.length; i++) {
  176. if (currentScene.materials[i]._transparencyMode !== undefined) {
  177. pbrPresent = true;
  178. break;
  179. }
  180. }
  181. if (pbrPresent) {
  182. if (!currentScene.environmentTexture) {
  183. currentScene.environmentTexture = loadSkyboxPathTexture(skyboxPath, currentScene);
  184. }
  185. }
  186. else {
  187. currentScene.createDefaultLight();
  188. }
  189. }
  190. // In case of error during loading, meshes will be empty and clearColor is set to red
  191. if (currentScene.meshes.length === 0 && currentScene.clearColor.r === 1 && currentScene.clearColor.g === 0 && currentScene.clearColor.b === 0) {
  192. document.getElementById("logo").className = "";
  193. canvas.style.opacity = 0;
  194. debugLayerEnabled = true;
  195. }
  196. else {
  197. if (BABYLON.Tools.errorsCount > 0) {
  198. debugLayerEnabled = true;
  199. }
  200. document.getElementById("logo").className = "hidden";
  201. document.getElementById("droptext").className = "hidden";
  202. canvas.style.opacity = 1;
  203. if (currentScene.activeCamera.keysUp) {
  204. currentScene.activeCamera.keysUp.push(90); // Z
  205. currentScene.activeCamera.keysUp.push(87); // W
  206. currentScene.activeCamera.keysDown.push(83); // S
  207. currentScene.activeCamera.keysLeft.push(65); // A
  208. currentScene.activeCamera.keysLeft.push(81); // Q
  209. currentScene.activeCamera.keysRight.push(69); // E
  210. currentScene.activeCamera.keysRight.push(68); // D
  211. }
  212. }
  213. if (debugLayerEnabled) {
  214. currentScene.debugLayer.show();
  215. }
  216. };
  217. var sceneError = function(sceneFile, babylonScene, message) {
  218. document.title = "Babylon.js - " + sceneFile.name;
  219. document.getElementById("logo").className = "";
  220. canvas.style.opacity = 0;
  221. 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>';
  222. errorZone.style.display = 'block';
  223. errorZone.innerHTML = errorContent;
  224. // Close button error
  225. errorZone.querySelector('.close').addEventListener('click', function() {
  226. errorZone.style.display = 'none';
  227. });
  228. };
  229. var loadFromAssetUrl = function() {
  230. var rootUrl = BABYLON.Tools.GetFolderPath(assetUrl);
  231. var fileName = BABYLON.Tools.GetFilename(assetUrl);
  232. BABYLON.SceneLoader.LoadAsync(rootUrl, fileName, engine).then(function(scene) {
  233. if (currentScene) {
  234. currentScene.dispose();
  235. }
  236. sceneLoaded({ name: fileName }, scene);
  237. scene.whenReadyAsync().then(function() {
  238. engine.runRenderLoop(function() {
  239. scene.render();
  240. });
  241. });
  242. }).catch(function(reason) {
  243. sceneError({ name: fileName }, null, reason.message || reason);
  244. });
  245. };
  246. if (assetUrl) {
  247. loadFromAssetUrl();
  248. }
  249. else {
  250. var startProcessingFiles = function() {
  251. BABYLON.Tools.ClearLogCache();
  252. };
  253. filesInput = new BABYLON.FilesInput(engine, null, sceneLoaded, null, null, null, startProcessingFiles, null, sceneError);
  254. filesInput.onProcessFileCallback = (function(file, name, extension) {
  255. if (filesInput._filesToLoad && filesInput._filesToLoad.length === 1 && extension) {
  256. if (extension.toLowerCase() === "dds" ||
  257. extension.toLowerCase() === "env" ||
  258. extension.toLowerCase() === "hdr") {
  259. BABYLON.FilesInput.FilesToLoad[name] = file;
  260. skyboxPath = "file:" + file.correctName;
  261. return false;
  262. }
  263. }
  264. return true;
  265. }).bind(this);
  266. filesInput.monitorElementForDragNDrop(canvas);
  267. htmlInput.addEventListener('change', function(event) {
  268. // Handling data transfer via drag'n'drop
  269. if (event && event.dataTransfer && event.dataTransfer.files) {
  270. filesToLoad = event.dataTransfer.files;
  271. }
  272. // Handling files from input files
  273. if (event && event.target && event.target.files) {
  274. filesToLoad = event.target.files;
  275. }
  276. filesInput.loadFiles(event);
  277. }, false);
  278. }
  279. window.addEventListener("keydown", function(event) {
  280. // Press R to reload
  281. if (event.keyCode === 82 && event.target.nodeName !== "INPUT" && currentScene) {
  282. if (assetUrl) {
  283. loadFromAssetUrl();
  284. }
  285. else {
  286. filesInput.reload();
  287. }
  288. }
  289. });
  290. btnInspector.addEventListener('click', function() {
  291. if (currentScene) {
  292. if (currentScene.debugLayer.isVisible()) {
  293. debugLayerEnabled = false;
  294. currentScene.debugLayer.hide();
  295. }
  296. else {
  297. currentScene.debugLayer.show();
  298. debugLayerEnabled = true;
  299. }
  300. }
  301. }, false);
  302. window.addEventListener("keydown", function(event) {
  303. // Press space to toggle footer
  304. if (event.keyCode === 32 && event.target.nodeName !== "INPUT") {
  305. if (footer.style.display === "none") {
  306. footer.style.display = "block";
  307. canvasZone.style.height = "calc(100% - 56px)";
  308. if (debugLayerEnabled) {
  309. currentScene.debugLayer.show();
  310. }
  311. engine.resize();
  312. }
  313. else {
  314. footer.style.display = "none";
  315. canvasZone.style.height = "100%";
  316. errorZone.style.display = "none";
  317. engine.resize();
  318. if (currentScene.debugLayer.isVisible()) {
  319. currentScene.debugLayer.hide();
  320. }
  321. }
  322. }
  323. });
  324. sizeScene();
  325. window.onresize = function() {
  326. sizeScene();
  327. }
  328. }
  329. function sizeScene() {
  330. let divInspWrapper = document.getElementsByClassName('insp-wrapper')[0];
  331. if (divInspWrapper) {
  332. let divFooter = document.getElementsByClassName('footer')[0];
  333. divInspWrapper.style.height = (document.body.clientHeight - divFooter.clientHeight) + "px";
  334. divInspWrapper.style['max-width'] = document.body.clientWidth + "px";
  335. }
  336. }