index.js 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. var jsEditor;
  2. (function () {
  3. var multipleSize = [1600, 1475, 1030, 750];
  4. var setToMultipleID = function (id, thingToDo, param) {
  5. multipleSize.forEach(function (size) {
  6. if (thingToDo == "innerHTML") {
  7. document.getElementById(id + size).innerHTML = param
  8. }
  9. else if (thingToDo == "click") {
  10. document.getElementById(id + size).addEventListener("click", param);
  11. }
  12. else if (thingToDo == "addClass") {
  13. document.getElementById(id + size).classList.add(param);
  14. }
  15. else if (thingToDo == "removeClass") {
  16. document.getElementById(id + size).classList.remove(param);
  17. }
  18. else if (thingToDo == "display") {
  19. document.getElementById(id + size).style.display = param;
  20. }
  21. });
  22. };
  23. var editorOptions = {
  24. value: "",
  25. language: "javascript",
  26. lineNumbers: true,
  27. tabSize: "auto",
  28. insertSpaces: "auto",
  29. roundedSelection: true,
  30. automaticLayout: true,
  31. scrollBeyondLastLine: false,
  32. readOnly: false,
  33. theme: "vs",
  34. contextmenu: false,
  35. folding: true,
  36. showFoldingControls: "always",
  37. renderIndentGuides: true
  38. };
  39. var fontSize = 14;
  40. var splitInstance = Split(['#jsEditor', '#canvasZone']);
  41. var elementToTheme = [
  42. '.wrapper .gutter',
  43. '.wrapper #jsEditor',
  44. '.navbar',
  45. '.navbar .select .toDisplay .option',
  46. '.navbar .select .toDisplayBig',
  47. '.navbar .select .toDisplayBig a',
  48. '.navbar .select .toDisplayBig ul li',
  49. '.navbarBottom',
  50. '.navbarBottom .links .link',
  51. '.save-message'];
  52. var run = function () {
  53. var blockEditorChange = false;
  54. var markDirty = function () {
  55. if (blockEditorChange) {
  56. return;
  57. }
  58. setToMultipleID("currentScript", "innerHTML", "Custom");
  59. setToMultipleID("safemodeToggle", "addClass", "checked");
  60. setToMultipleID('safemodeToggle', 'innerHTML', 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  61. }
  62. jsEditor.onKeyUp(function (evt) {
  63. markDirty();
  64. });
  65. var snippetUrl = "//babylonjs-api2.azurewebsites.net/snippets";
  66. var currentSnippetToken;
  67. var currentSnippetTitle = null;
  68. var currentSnippetDescription = null;
  69. var currentSnippetTags = null;
  70. var engine;
  71. var fpsLabel = document.getElementById("fpsLabel");
  72. var scripts;
  73. var zipCode;
  74. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  75. if (location.href.indexOf("Stable") !== -1) {
  76. setToMultipleID("currentVersion", "innerHTML", "Version: Stable");
  77. } else {
  78. setToMultipleID("currentVersion", "innerHTML", "Version: Latest");
  79. }
  80. var loadScript = function (scriptURL, title) {
  81. var xhr = new XMLHttpRequest();
  82. xhr.open('GET', scriptURL, true);
  83. xhr.onreadystatechange = function () {
  84. if (xhr.readyState === 4) {
  85. if (xhr.status === 200) {
  86. xhr.onreadystatechange = null;
  87. blockEditorChange = true;
  88. jsEditor.setValue(xhr.responseText);
  89. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  90. blockEditorChange = false;
  91. compileAndRun();
  92. setToMultipleID("currentScript", "innerHTML", title);
  93. currentSnippetToken = null;
  94. }
  95. }
  96. };
  97. xhr.send(null);
  98. };
  99. var loadScriptFromIndex = function (index) {
  100. if (index === 0) {
  101. index = 1;
  102. }
  103. var script = scripts[index - 1].trim();
  104. loadScript("scripts/" + script + ".js", script);
  105. }
  106. var onScriptClick = function (evt) {
  107. loadScriptFromIndex(evt.target.scriptLinkIndex);
  108. };
  109. var loadScriptsList = function () {
  110. var xhr = new XMLHttpRequest();
  111. xhr.open('GET', 'scripts/scripts.txt', true);
  112. xhr.onreadystatechange = function () {
  113. if (xhr.readyState === 4) {
  114. if (xhr.status === 200) {
  115. scripts = xhr.responseText.split("\n");
  116. for (var i = 0; i < multipleSize.length; i++) {
  117. var ul = document.getElementById("scriptsList" + multipleSize[i]);
  118. var index;
  119. for (index = 0; index < scripts.length; index++) {
  120. var option = document.createElement("li");
  121. var a = document.createElement("a");
  122. a.href = "#";
  123. a.innerHTML = (index + 1) + " - " + scripts[index];
  124. a.scriptLinkIndex = index + 1;
  125. //a.onclick = onScriptClick;
  126. option.scriptLinkIndex = index + 1;
  127. option.onclick = onScriptClick;
  128. option.appendChild(a);
  129. ul.appendChild(option);
  130. }
  131. }
  132. if (!location.hash) {
  133. // Query string
  134. var queryString = window.location.search;
  135. if (queryString) {
  136. var query = queryString.replace("?", "");
  137. index = parseInt(query);
  138. if (!isNaN(index)) {
  139. loadScriptFromIndex(index);
  140. } else if (query.indexOf("=") === -1) {
  141. loadScript("scripts/" + query + ".js", query);
  142. } else {
  143. loadScript("scripts/basic scene.js", "Basic scene");
  144. }
  145. } else {
  146. loadScript("scripts/basic scene.js", "Basic scene");
  147. }
  148. }
  149. // Restore theme
  150. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  151. toggleTheme(theme);
  152. // Remove editor if window size is less than 850px
  153. var removeEditorForSmallScreen = function () {
  154. if (mq.matches) {
  155. splitInstance.collapse(0);
  156. } else {
  157. splitInstance.setSizes([50, 50]);
  158. }
  159. }
  160. var mq = window.matchMedia("(max-width: 850px)");
  161. mq.addListener(removeEditorForSmallScreen);
  162. }
  163. }
  164. };
  165. xhr.send(null);
  166. }
  167. var createNewScript = function () {
  168. // check if checked is on
  169. let iCanClear = checkSafeMode("Are you sure you want to create a new playground?");
  170. if (!iCanClear) return;
  171. location.hash = "";
  172. currentSnippetToken = null;
  173. currentSnippetTitle = null;
  174. currentSnippetDescription = null;
  175. currentSnippetTags = null;
  176. showNoMetadata();
  177. jsEditor.setValue('// You have to create a function called createScene. This function must return a BABYLON.Scene object\r\n// You can reference the following variables: scene, canvas\r\n// You must at least define a camera\r\n// More info here: https://doc.babylonjs.com/generals/The_Playground_Tutorial\r\n\r\nvar createScene = function() {\r\n\tvar scene = new BABYLON.Scene(engine);\r\n\tvar camera = new BABYLON.ArcRotateCamera("Camera", 0, Math.PI / 2, 12, BABYLON.Vector3.Zero(), scene);\r\n\tcamera.attachControl(canvas, true);\r\n\r\n\r\n\r\n\treturn scene;\r\n};');
  178. jsEditor.setPosition({ lineNumber: 11, column: 0 });
  179. jsEditor.focus();
  180. compileAndRun();
  181. }
  182. var clear = function () {
  183. // check if checked is on
  184. let iCanClear = checkSafeMode("Are you sure you want to clear the playground?");
  185. if (!iCanClear) return;
  186. location.hash = "";
  187. currentSnippetToken = null;
  188. jsEditor.setValue('');
  189. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  190. jsEditor.focus();
  191. }
  192. var checkSafeMode = function (message) {
  193. var safeToggle = document.getElementById("safemodeToggle1600");
  194. if (safeToggle.classList.contains('checked')) {
  195. let confirm = window.confirm(message);
  196. if (!confirm) {
  197. return false;
  198. } else {
  199. document.getElementById("safemodeToggle1600").classList.toggle('checked');
  200. return true;
  201. }
  202. } else {
  203. return true;
  204. }
  205. }
  206. var showError = function (errorMessage, errorEvent) {
  207. var errorContent =
  208. '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button>';
  209. if (errorEvent) {
  210. var regEx = /\(.+:(\d+):(\d+)\)\n/g;
  211. var match = regEx.exec(errorEvent.stack);
  212. if (match) {
  213. errorContent += "Line ";
  214. var lineNumber = match[1];
  215. var columnNumber = match[2];
  216. errorContent += lineNumber + ':' + columnNumber + ' - ';
  217. }
  218. }
  219. errorContent += errorMessage + '</div>';
  220. document.getElementById("errorZone").style.display = 'block';
  221. document.getElementById("errorZone").innerHTML = errorContent;
  222. // Close button error
  223. document.getElementById("errorZone").querySelector('.close').addEventListener('click', function () {
  224. document.getElementById("errorZone").style.display = 'none';
  225. });
  226. }
  227. var showNoMetadata = function () {
  228. if (currentSnippetTitle) {
  229. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  230. document.getElementById("saveFormTitle").readOnly = true;
  231. }
  232. else {
  233. document.getElementById("saveFormTitle").value = '';
  234. document.getElementById("saveFormTitle").readOnly = false;
  235. }
  236. if (currentSnippetDescription) {
  237. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  238. document.getElementById("saveFormDescription").readOnly = true;
  239. }
  240. else {
  241. document.getElementById("saveFormDescription").value = '';
  242. document.getElementById("saveFormDescription").readOnly = false;
  243. }
  244. if (currentSnippetTags) {
  245. document.getElementById("saveFormTags").value = currentSnippetTags;
  246. document.getElementById("saveFormTags").readOnly = true;
  247. }
  248. else {
  249. document.getElementById("saveFormTags").value = '';
  250. document.getElementById("saveFormTags").readOnly = false;
  251. }
  252. document.getElementById("saveFormButtons").style.display = "block";
  253. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  254. document.getElementById("saveMessage").style.display = "block";
  255. };
  256. showNoMetadata();
  257. document.getElementById("saveMessage").style.display = "none";
  258. var hideNoMetadata = function () {
  259. document.getElementById("saveFormTitle").readOnly = true;
  260. document.getElementById("saveFormDescription").readOnly = true;
  261. document.getElementById("saveFormTags").readOnly = true;
  262. document.getElementById("saveFormButtonOk").style.display = "none";
  263. document.getElementById("saveMessage").style.display = "none";
  264. setToMultipleID("metadataButton", "display", "inline-block");
  265. };
  266. compileAndRun = function () {
  267. try {
  268. var waitRing = document.getElementById("waitDiv");
  269. if (waitRing) {
  270. waitRing.style.display = "none";
  271. }
  272. if (!BABYLON.Engine.isSupported()) {
  273. showError("Your browser does not support WebGL", null);
  274. return;
  275. }
  276. var showInspector = false;
  277. var showDebugLayer = false;
  278. var initialTabIndex = 0;
  279. if (document.getElementsByClassName('insp-wrapper').length > 0) {
  280. for (var i = 0; i < engine.scenes.length; i++) {
  281. if (engine.scenes[i]._debugLayer) {
  282. //TODO: once inspector is updated on netlify, use getActiveTabIndex instead of the following loop
  283. //initialTabIndex = engine.scenes[i]._debugLayer._inspector.getActiveTabIndex();
  284. var tabs = engine.scenes[i]._debugLayer._inspector._tabbar._tabs;
  285. for (var j = 0; j < tabs.length; j++) {
  286. if (tabs[j].isActive()) {
  287. initialTabIndex = j;
  288. break;
  289. }
  290. }
  291. break;
  292. }
  293. }
  294. showInspector = true;
  295. } else if (document.getElementById('DebugLayer')) {
  296. showDebugLayer = true;
  297. }
  298. if (engine) {
  299. engine.dispose();
  300. engine = null;
  301. }
  302. var canvas = document.getElementById("renderCanvas");
  303. engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  304. document.getElementById("errorZone").style.display = 'none';
  305. document.getElementById("errorZone").innerHTML = "";
  306. document.getElementById("statusBar").innerHTML = "Loading assets...Please wait";
  307. var checkCamera = true;
  308. engine.runRenderLoop(function () {
  309. if (engine.scenes.length === 0) {
  310. return;
  311. }
  312. if (canvas.width !== canvas.clientWidth) {
  313. engine.resize();
  314. }
  315. var scene = engine.scenes[0];
  316. if (scene.activeCamera || scene.activeCameras.length > 0) {
  317. scene.render();
  318. }
  319. fpsLabel.style.right = document.body.clientWidth - (jsEditor.domElement.clientWidth + canvas.clientWidth) + "px";
  320. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  321. });
  322. var code = jsEditor.getValue();
  323. var scene;
  324. if (code.indexOf("delayCreateScene") !== -1) { // createScene
  325. eval(code);
  326. scene = delayCreateScene();
  327. checkCamera = false;
  328. if (!scene) {
  329. showError("delayCreateScene function must return a scene.", null);
  330. return;
  331. }
  332. zipCode = code + "\r\n\r\nvar scene = createScene();";
  333. } else if (code.indexOf("createScene") !== -1) { // createScene
  334. eval(code);
  335. scene = createScene();
  336. if (!scene) {
  337. showError("createScene function must return a scene.", null);
  338. return;
  339. }
  340. zipCode = code + "\r\n\r\nvar scene = createScene();";
  341. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  342. eval(code);
  343. scene = CreateScene();
  344. if (!scene) {
  345. showError("CreateScene function must return a scene.", null);
  346. return;
  347. }
  348. zipCode = code + "\r\n\r\nvar scene = CreateScene();";
  349. } else if (code.indexOf("createscene") !== -1) { // createscene
  350. eval(code);
  351. scene = createscene();
  352. if (!scene) {
  353. showError("createscene function must return a scene.", null);
  354. return;
  355. }
  356. zipCode = code + "\r\n\r\nvar scene = createscene();";
  357. } else { // Direct code
  358. scene = new BABYLON.Scene(engine);
  359. eval("runScript = function(scene, canvas) {" + code + "}");
  360. runScript(scene, canvas);
  361. zipCode = "var scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  362. }
  363. if (engine.scenes.length === 0) {
  364. showError("You must at least create a scene.", null);
  365. return;
  366. }
  367. if (checkCamera && engine.scenes[0].activeCamera == null) {
  368. showError("You must at least create a camera.", null);
  369. return;
  370. }
  371. engine.scenes[0].executeWhenReady(function () {
  372. document.getElementById("statusBar").innerHTML = "";
  373. });
  374. if (scene) {
  375. if (showInspector) {
  376. scene.debugLayer.show({ initialTab: initialTabIndex });
  377. scene.executeWhenReady(function () {
  378. scene.debugLayer._inspector.refresh();
  379. })
  380. } else if (showDebugLayer) {
  381. scene.debugLayer.show();
  382. }
  383. }
  384. } catch (e) {
  385. showError(e.message, e);
  386. }
  387. };
  388. window.addEventListener("resize",
  389. function () {
  390. if (engine) {
  391. engine.resize();
  392. }
  393. });
  394. // Load scripts list
  395. loadScriptsList();
  396. // Zip
  397. var addContentToZip = function (zip, name, url, replace, buffer, then) {
  398. var xhr = new XMLHttpRequest();
  399. xhr.open('GET', url, true);
  400. if (buffer) {
  401. xhr.responseType = "arraybuffer";
  402. }
  403. xhr.onreadystatechange = function () {
  404. if (xhr.readyState === 4) {
  405. if (xhr.status === 200) {
  406. var text;
  407. if (!buffer) {
  408. if (replace) {
  409. var splits = replace.split("\r\n");
  410. for (var index = 0; index < splits.length; index++) {
  411. splits[index] = " " + splits[index];
  412. }
  413. replace = splits.join("\r\n");
  414. text = xhr.responseText.replace("####INJECT####", replace);
  415. } else {
  416. text = xhr.responseText;
  417. }
  418. }
  419. zip.file(name, buffer ? xhr.response : text);
  420. then();
  421. }
  422. }
  423. };
  424. xhr.send(null);
  425. }
  426. var addTexturesToZip = function (zip, index, textures, folder, then) {
  427. if (index === textures.length) {
  428. then();
  429. return;
  430. }
  431. if (textures[index].isRenderTarget || textures[index] instanceof BABYLON.DynamicTexture || textures[index].name.indexOf("data:") !== -1) {
  432. addTexturesToZip(zip, index + 1, textures, folder, then);
  433. return;
  434. }
  435. if (textures[index].isCube) {
  436. if (textures[index]._extensions && textures[index].name.indexOf("dds") === -1) {
  437. for (var i = 0; i < 6; i++) {
  438. textures.push({ name: textures[index].name + textures[index]._extensions[i] });
  439. }
  440. }
  441. else {
  442. textures.push({ name: textures[index].name });
  443. }
  444. addTexturesToZip(zip, index + 1, textures, folder, then);
  445. return;
  446. }
  447. if (folder == null) {
  448. folder = zip.folder("textures");
  449. }
  450. var url;
  451. if (textures[index].video) {
  452. url = textures[index].video.currentSrc;
  453. } else {
  454. // url = textures[index].name;
  455. url = textures[index].url ? textures[index].url : textures[index].name;
  456. }
  457. var name = textures[index].name.replace("textures/", "");
  458. // var name = url.substr(url.lastIndexOf("/") + 1);
  459. if (url != null) {
  460. addContentToZip(folder,
  461. name,
  462. url,
  463. null,
  464. true,
  465. function () {
  466. addTexturesToZip(zip, index + 1, textures, folder, then);
  467. });
  468. }
  469. else {
  470. addTexturesToZip(zip, index + 1, textures, folder, then);
  471. }
  472. }
  473. var addImportedFilesToZip = function (zip, index, importedFiles, folder, then) {
  474. if (index === importedFiles.length) {
  475. then();
  476. return;
  477. }
  478. if (!folder) {
  479. folder = zip.folder("scenes");
  480. }
  481. var url = importedFiles[index];
  482. var name = url.substr(url.lastIndexOf("/") + 1);
  483. addContentToZip(folder,
  484. name,
  485. url,
  486. null,
  487. true,
  488. function () {
  489. addImportedFilesToZip(zip, index + 1, importedFiles, folder, then);
  490. });
  491. }
  492. var getZip = function () {
  493. if (engine.scenes.length === 0) {
  494. return;
  495. }
  496. var zip = new JSZip();
  497. var scene = engine.scenes[0];
  498. var textures = scene.textures;
  499. var importedFiles = scene.importedMeshesFiles;
  500. document.getElementById("statusBar").innerHTML = "Creating archive...Please wait";
  501. if (zipCode.indexOf("textures/worldHeightMap.jpg") !== -1) {
  502. textures.push({ name: "textures/worldHeightMap.jpg" });
  503. }
  504. addContentToZip(zip,
  505. "index.html",
  506. "zipContent/index.html",
  507. zipCode,
  508. false,
  509. function () {
  510. addTexturesToZip(zip,
  511. 0,
  512. textures,
  513. null,
  514. function () {
  515. addImportedFilesToZip(zip,
  516. 0,
  517. importedFiles,
  518. null,
  519. function () {
  520. var blob = zip.generate({ type: "blob" });
  521. saveAs(blob, "sample.zip");
  522. document.getElementById("statusBar").innerHTML = "";
  523. });
  524. });
  525. });
  526. }
  527. // Versions
  528. setVersion = function (version) {
  529. switch (version) {
  530. case "stable":
  531. location.href = "indexStable.html" + location.hash;
  532. break;
  533. default:
  534. location.href = "index.html" + location.hash;
  535. break;
  536. }
  537. }
  538. // Fonts
  539. setFontSize = function (size) {
  540. fontSize = size;
  541. document.querySelector(".view-lines").style.fontSize = size + "px";
  542. setToMultipleID("currentFontSize", "innerHTML", "Font: " + size);
  543. };
  544. // Fullscreen
  545. document.getElementById("renderCanvas").addEventListener("webkitfullscreenchange", function () {
  546. if (document.webkitIsFullScreen) goFullPage();
  547. else exitFullPage();
  548. }, false);
  549. var goFullPage = function () {
  550. var canvasElement = document.getElementById("renderCanvas");
  551. canvasElement.style.position = "absolute";
  552. canvasElement.style.top = 0;
  553. canvasElement.style.left = 0;
  554. canvasElement.style.zIndex = 100;
  555. }
  556. var exitFullPage = function () {
  557. document.getElementById("renderCanvas").style.position = "relative";
  558. document.getElementById("renderCanvas").style.zIndex = 0;
  559. }
  560. var goFullscreen = function () {
  561. if (engine) {
  562. engine.switchFullscreen(true);
  563. }
  564. }
  565. var editorGoFullscreen = function () {
  566. var editorDiv = document.getElementById("jsEditor");
  567. if (editorDiv.requestFullscreen) {
  568. editorDiv.requestFullscreen();
  569. } else if (editorDiv.mozRequestFullScreen) {
  570. editorDiv.mozRequestFullScreen();
  571. } else if (editorDiv.webkitRequestFullscreen) {
  572. editorDiv.webkitRequestFullscreen();
  573. }
  574. }
  575. var toggleEditor = function () {
  576. var editorButton = document.getElementById("editorButton1600");
  577. var scene = engine.scenes[0];
  578. // If the editor is present
  579. if (editorButton.classList.contains('checked')) {
  580. setToMultipleID("editorButton", "removeClass", 'checked');
  581. splitInstance.collapse(0);
  582. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square-o" aria-hidden="true"></i>');
  583. } else {
  584. setToMultipleID("editorButton", "addClass", 'checked');
  585. splitInstance.setSizes([50, 50]); // Reset
  586. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  587. }
  588. engine.resize();
  589. if (scene.debugLayer.isVisible()) {
  590. scene.debugLayer.hide();
  591. scene.debugLayer.show();
  592. }
  593. }
  594. /**
  595. * Toggle the dark theme
  596. */
  597. var toggleTheme = function (theme) {
  598. // Monaco
  599. var vsTheme;
  600. if (theme == 'dark') {
  601. vsTheme = 'vs-dark'
  602. } else {
  603. vsTheme = 'vs'
  604. }
  605. var oldCode = jsEditor.getValue();
  606. jsEditor.dispose();
  607. editorOptions.theme = vsTheme;
  608. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  609. jsEditor.setValue(oldCode);
  610. setFontSize(fontSize);
  611. jsEditor.onKeyUp(function (evt) {
  612. markDirty();
  613. });
  614. for (var index = 0; index < elementToTheme.length; index++) {
  615. var obj = elementToTheme[index];
  616. var domObjArr = document.querySelectorAll(obj);
  617. for (var domObjIndex = 0; domObjIndex < domObjArr.length; domObjIndex++) {
  618. var domObj = domObjArr[domObjIndex];
  619. domObj.classList.remove('light');
  620. domObj.classList.remove('dark');
  621. domObj.classList.add(theme);
  622. }
  623. }
  624. localStorage.setItem("bjs-playground-theme", theme);
  625. }
  626. var toggleDebug = function () {
  627. var debugButton = document.getElementById("debugButton1600");
  628. var scene = engine.scenes[0];
  629. if (debugButton.classList.contains('uncheck')) {
  630. setToMultipleID("debugButton", "removeClass", 'uncheck');
  631. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-check-square" aria-hidden="true"></i>');
  632. scene.debugLayer.show();
  633. } else {
  634. setToMultipleID("debugButton", "addClass", 'uncheck');
  635. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-square-o" aria-hidden="true"></i>');
  636. scene.debugLayer.hide();
  637. }
  638. }
  639. var toggleMetadata = function () {
  640. var scene = engine.scenes[0];
  641. document.getElementById("saveLayer").style.display = "block";
  642. }
  643. var formatCode = function () {
  644. jsEditor.getAction('editor.action.format').run();
  645. }
  646. //Navigation Overwrites
  647. var exitPrompt = function (e) {
  648. var safeToggle = document.getElementById("safemodeToggle1600");
  649. if (safeToggle.classList.contains('checked')) {
  650. e = e || window.event;
  651. var message =
  652. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  653. if (e) {
  654. e.returnValue = message;
  655. }
  656. return message;
  657. }
  658. };
  659. window.onbeforeunload = exitPrompt;
  660. // Snippet
  661. var save = function () {
  662. // Retrieve title if necessary
  663. if (document.getElementById("saveLayer")) {
  664. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  665. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  666. currentSnippetTags = document.getElementById("saveFormTags").value;
  667. }
  668. var xmlHttp = new XMLHttpRequest();
  669. xmlHttp.onreadystatechange = function () {
  670. if (xmlHttp.readyState === 4) {
  671. if (xmlHttp.status === 201) {
  672. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  673. var snippet = JSON.parse(xmlHttp.responseText);
  674. var newUrl = baseUrl + "#" + snippet.id;
  675. currentSnippetToken = snippet.id;
  676. if (snippet.version && snippet.version !== "0") {
  677. newUrl += "#" + snippet.version;
  678. }
  679. location.href = newUrl;
  680. // Hide the complete title & co message
  681. hideNoMetadata();
  682. compileAndRun();
  683. } else {
  684. showError("Unable to save your code. It may be too long.", null);
  685. }
  686. }
  687. }
  688. xmlHttp.open("POST", snippetUrl + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  689. xmlHttp.setRequestHeader("Content-Type", "application/json");
  690. var dataToSend = {
  691. payload: {
  692. code: jsEditor.getValue()
  693. },
  694. name: currentSnippetTitle,
  695. description: currentSnippetDescription,
  696. tags: currentSnippetTags
  697. };
  698. xmlHttp.send(JSON.stringify(dataToSend));
  699. }
  700. var askForSave = function () {
  701. if (currentSnippetTitle == null
  702. || currentSnippetDescription == null
  703. || currentSnippetTags == null) {
  704. document.getElementById("saveLayer").style.display = "block";
  705. }
  706. else {
  707. save();
  708. }
  709. };
  710. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  711. document.getElementById("saveLayer").style.display = "none";
  712. save();
  713. });
  714. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  715. document.getElementById("saveLayer").style.display = "none";
  716. });
  717. document.getElementById("saveMessage").addEventListener("click", function () {
  718. document.getElementById("saveMessage").style.display = "none";
  719. });
  720. document.getElementById("mainTitle").innerHTML = "v" + BABYLON.Engine.Version;
  721. var previousHash = "";
  722. var cleanHash = function () {
  723. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  724. if (splits.length > 2) {
  725. splits.splice(2, splits.length - 2);
  726. }
  727. location.hash = splits.join("#");
  728. }
  729. var checkHash = function (firstTime) {
  730. if (location.hash) {
  731. if (previousHash !== location.hash) {
  732. cleanHash();
  733. previousHash = location.hash;
  734. try {
  735. var xmlHttp = new XMLHttpRequest();
  736. xmlHttp.onreadystatechange = function () {
  737. if (xmlHttp.readyState === 4) {
  738. if (xmlHttp.status === 200) {
  739. var snippet = JSON.parse(xmlHttp.responseText)[0];
  740. blockEditorChange = true;
  741. jsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  742. // Check if title / descr / tags are already set
  743. if (snippet.name != null && snippet.name != "") {
  744. currentSnippetTitle = snippet.name;
  745. }
  746. else currentSnippetTitle = null;
  747. if (snippet.description != null && snippet.description != "") {
  748. currentSnippetDescription = snippet.description;
  749. }
  750. else currentSnippetDescription = null;
  751. if (snippet.tags != null && snippet.tags != "") {
  752. currentSnippetTags = snippet.tags;
  753. }
  754. else currentSnippetTags = null;
  755. if (currentSnippetTitle != null && currentSnippetTags != null && currentSnippetDescription) {
  756. if (document.getElementById("saveLayer")) {
  757. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  758. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  759. document.getElementById("saveFormTags").value = currentSnippetTags;
  760. hideNoMetadata();
  761. }
  762. }
  763. else {
  764. showNoMetadata();
  765. }
  766. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  767. blockEditorChange = false;
  768. compileAndRun();
  769. setToMultipleID("currentScript", "innerHTML", "Custom");
  770. } else if (firstTime) {
  771. location.href = location.href.replace(location.hash, "");
  772. if (scripts) {
  773. loadScriptFromIndex(0);
  774. }
  775. }
  776. }
  777. };
  778. var hash = location.hash.substr(1);
  779. currentSnippetToken = hash.split("#")[0];
  780. if (!hash.split("#")[1]) hash += "#0";
  781. xmlHttp.open("GET", snippetUrl + "/" + hash.replace("#", "/"));
  782. xmlHttp.send();
  783. } catch (e) {
  784. }
  785. }
  786. }
  787. setTimeout(checkHash, 200);
  788. }
  789. checkHash(true);
  790. // ---------- UI
  791. // Run
  792. setToMultipleID("runButton", "click", compileAndRun);
  793. // New
  794. setToMultipleID("newButton", "click", createNewScript);
  795. // Clear
  796. setToMultipleID("clearButton", "click", clear);
  797. // Save
  798. setToMultipleID("saveButton", "click", askForSave);
  799. // Zip
  800. setToMultipleID("zipButton", "click", getZip);
  801. // Themes
  802. setToMultipleID("darkTheme", "click", toggleTheme.bind(this, 'dark'));
  803. setToMultipleID("lightTheme", "click", toggleTheme.bind(this, 'light'));
  804. // Safe mode
  805. setToMultipleID("safemodeToggle", 'click', function () {
  806. document.getElementById("safemodeToggle1600").classList.toggle('checked');
  807. if (document.getElementById("safemodeToggle1600").classList.contains('checked')) {
  808. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  809. } else {
  810. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square-o" aria-hidden="true"></i>');
  811. }
  812. });
  813. // Editor
  814. setToMultipleID("editorButton", "click", toggleEditor);
  815. // FullScreen
  816. setToMultipleID("fullscreenButton", "click", goFullscreen);
  817. // Editor fullScreen
  818. setToMultipleID("editorFullscreenButton", "click", editorGoFullscreen);
  819. // Format
  820. setToMultipleID("formatButton", "click", formatCode);
  821. // Debug
  822. setToMultipleID("debugButton", "click", toggleDebug);
  823. // Metadata
  824. setToMultipleID("metadataButton", "click", toggleMetadata);
  825. // Restore theme
  826. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  827. toggleTheme(theme);
  828. }
  829. // Monaco
  830. var xhr = new XMLHttpRequest();
  831. xhr.open('GET', "babylon.d.txt", true);
  832. xhr.onreadystatechange = function () {
  833. if (xhr.readyState === 4) {
  834. if (xhr.status === 200) {
  835. require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' } });
  836. require(['vs/editor/editor.main'], function () {
  837. monaco.languages.typescript.javascriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  838. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  839. run();
  840. });
  841. }
  842. }
  843. };
  844. xhr.send(null);
  845. })();