index.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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);
  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 && extension.toLowerCase() === "dds") {
  204. BABYLON.FilesInput.FilesToLoad[name] = file;
  205. skyboxPath = "file:" + file.correctName;
  206. return false;
  207. }
  208. return true;
  209. }).bind(this);
  210. filesInput.monitorElementForDragNDrop(canvas);
  211. htmlInput.addEventListener('change', function (event) {
  212. var filestoLoad;
  213. // Handling data transfer via drag'n'drop
  214. if (event && event.dataTransfer && event.dataTransfer.files) {
  215. filesToLoad = event.dataTransfer.files;
  216. }
  217. // Handling files from input files
  218. if (event && event.target && event.target.files) {
  219. filesToLoad = event.target.files;
  220. }
  221. filesInput.loadFiles(event);
  222. }, false);
  223. }
  224. window.addEventListener("keydown", function (event) {
  225. // Press R to reload
  226. if (event.keyCode === 82 && event.target.nodeName !== "INPUT") {
  227. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  228. if (assetUrl) {
  229. loadFromAssetUrl();
  230. }
  231. else {
  232. filesInput.reload();
  233. }
  234. }
  235. });
  236. if (kiosk) {
  237. footer.style.display = "none";
  238. }
  239. btnFullScreen.addEventListener('click', function () {
  240. engine.switchFullscreen(true);
  241. }, false);
  242. btnInspector.addEventListener('click', function () {
  243. if (currentScene) {
  244. if (currentScene.debugLayer.isVisible()) {
  245. debugLayerEnabled = false;
  246. debugLayerLastActiveTab = currentScene.debugLayer.getActiveTab();
  247. currentScene.debugLayer.hide();
  248. }
  249. else {
  250. currentScene.debugLayer.show({ initialTab: debugLayerLastActiveTab });
  251. debugLayerEnabled = true;
  252. }
  253. }
  254. }, false);
  255. window.addEventListener("keydown", function (event) {
  256. // Press space to toggle footer
  257. if (event.keyCode === 32 && event.target.nodeName !== "INPUT") {
  258. if (footer.style.display === "none") {
  259. footer.style.display = "block";
  260. }
  261. else {
  262. footer.style.display = "none";
  263. errorZone.style.display = "none";
  264. if (enableDebugLayer) {
  265. currentScene.debugLayer.hide();
  266. enableDebugLayer = false;
  267. }
  268. }
  269. }
  270. });
  271. sizeScene();
  272. window.onresize = function () {
  273. sizeScene();
  274. }
  275. }
  276. function sizeScene() {
  277. let divInspWrapper = document.getElementsByClassName('insp-wrapper')[0];
  278. if (divInspWrapper) {
  279. let divFooter = document.getElementsByClassName('footer')[0];
  280. divInspWrapper.style.height = (document.body.clientHeight - divFooter.clientHeight) + "px";
  281. divInspWrapper.style['max-width'] = document.body.clientWidth + "px";
  282. }
  283. }
  284. // animation
  285. // event on the dropdown
  286. function formatId(name) {
  287. return "data-" + name.replace(/\s/g, '');
  288. }
  289. function displayDropdownContent(display) {
  290. if (display) {
  291. dropdownContent.style.display = "flex";
  292. chevronDown.style.display = "inline";
  293. chevronUp.style.display = "none";
  294. }
  295. else {
  296. dropdownContent.style.display = "none";
  297. chevronDown.style.display = "none";
  298. chevronUp.style.display = "inline";
  299. }
  300. }
  301. dropdownBtn.addEventListener("click", function () {
  302. if (dropdownContent.style.display === "flex") {
  303. displayDropdownContent(false);
  304. }
  305. else {
  306. displayDropdownContent(true);
  307. }
  308. });
  309. function createDropdownLink(group, index) {
  310. var animation = document.createElement("a");
  311. animation.innerHTML = group.name;
  312. animation.setAttribute("id", formatId(group.name + "-" + index));
  313. animation.addEventListener("click", function () {
  314. // stop the current animation group
  315. currentGroup.reset();
  316. currentGroup.stop();
  317. document.getElementById(formatId(currentGroup.name + "-" + currentGroupIndex)).classList.remove("active");
  318. playBtn.classList.remove("play");
  319. playBtn.classList.add("pause");
  320. // start the new animation group
  321. currentGroup = group;
  322. currentGroupIndex = index;
  323. currentGroup.start(true);
  324. this.classList.add("active");
  325. dropdownLabel.innerHTML = currentGroup.name;
  326. // set the slider
  327. slider.setAttribute("min", currentGroup.from);
  328. slider.setAttribute("max", currentGroup.to);
  329. currentSliderValue = currentGroup.from;
  330. slider.value = currentGroup.from;
  331. // hide the content of the dropdown
  332. displayDropdownContent(false);
  333. });
  334. dropdownContent.appendChild(animation);
  335. }
  336. // event on the play/pause button
  337. playBtn.addEventListener("click", function () {
  338. // click on the button to run the animation
  339. if (this.classList.contains("play")) {
  340. this.classList.remove("play");
  341. this.classList.add("pause");
  342. var currentFrame = slider.value;
  343. currentGroup.play(true);
  344. }
  345. // click on the button to pause the animation
  346. else {
  347. this.classList.add("play");
  348. this.classList.remove("pause");
  349. currentGroup.pause();
  350. }
  351. });
  352. // event on the slider
  353. slider.addEventListener("input", function () {
  354. if (playBtn.classList.contains("play")) {
  355. currentGroup.play(true);
  356. currentGroup.goToFrame(this.value);
  357. currentGroup.pause();
  358. } else {
  359. currentGroup.goToFrame(this.value);
  360. }
  361. });
  362. var sliderPause = false;
  363. slider.addEventListener("mousedown", function () {
  364. if (playBtn.classList.contains("pause")) {
  365. sliderPause = true;
  366. playBtn.click();
  367. }
  368. });
  369. slider.addEventListener("mouseup", function () {
  370. if (sliderPause) {
  371. sliderPause = false;
  372. playBtn.click();
  373. }
  374. });