index.js 15 KB

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