index.js 16 KB

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