index.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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 = "https://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. engine.runRenderLoop(function () {
  308. if (engine.scenes.length === 0) {
  309. return;
  310. }
  311. if (canvas.width !== canvas.clientWidth) {
  312. engine.resize();
  313. }
  314. var scene = engine.scenes[0];
  315. if (scene.activeCamera || scene.activeCameras.length > 0) {
  316. scene.render();
  317. }
  318. fpsLabel.style.right = document.body.clientWidth - (jsEditor.domElement.clientWidth + canvas.clientWidth) + "px";
  319. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  320. });
  321. var code = jsEditor.getValue();
  322. var scene;
  323. if (code.indexOf("createScene") !== -1) { // createScene
  324. eval(code);
  325. scene = createScene();
  326. if (!scene) {
  327. showError("createScene function must return a scene.", null);
  328. return;
  329. }
  330. zipCode = code + "\r\n\r\nvar scene = createScene();";
  331. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  332. eval(code);
  333. scene = CreateScene();
  334. if (!scene) {
  335. showError("CreateScene function must return a scene.", null);
  336. return;
  337. }
  338. zipCode = code + "\r\n\r\nvar scene = CreateScene();";
  339. } else if (code.indexOf("createscene") !== -1) { // createscene
  340. eval(code);
  341. scene = createscene();
  342. if (!scene) {
  343. showError("createscene function must return a scene.", null);
  344. return;
  345. }
  346. zipCode = code + "\r\n\r\nvar scene = createscene();";
  347. } else { // Direct code
  348. scene = new BABYLON.Scene(engine);
  349. eval("runScript = function(scene, canvas) {" + code + "}");
  350. runScript(scene, canvas);
  351. zipCode = "var scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  352. }
  353. if (engine.scenes.length === 0) {
  354. showError("You must at least create a scene.", null);
  355. return;
  356. }
  357. if (engine.scenes[0].activeCamera == null) {
  358. showError("You must at least create a camera.", null);
  359. return;
  360. }
  361. engine.scenes[0].executeWhenReady(function () {
  362. document.getElementById("statusBar").innerHTML = "";
  363. });
  364. if (scene) {
  365. if (showInspector) {
  366. scene.debugLayer.show({ initialTab: initialTabIndex });
  367. scene.executeWhenReady(function () {
  368. scene.debugLayer._inspector.refresh();
  369. })
  370. } else if (showDebugLayer) {
  371. scene.debugLayer.show();
  372. }
  373. }
  374. } catch (e) {
  375. showError(e.message, e);
  376. }
  377. };
  378. window.addEventListener("resize",
  379. function () {
  380. if (engine) {
  381. engine.resize();
  382. }
  383. });
  384. // Load scripts list
  385. loadScriptsList();
  386. // Zip
  387. var addContentToZip = function (zip, name, url, replace, buffer, then) {
  388. var xhr = new XMLHttpRequest();
  389. xhr.open('GET', url, true);
  390. if (buffer) {
  391. xhr.responseType = "arraybuffer";
  392. }
  393. xhr.onreadystatechange = function () {
  394. if (xhr.readyState === 4) {
  395. if (xhr.status === 200) {
  396. var text;
  397. if (!buffer) {
  398. if (replace) {
  399. var splits = replace.split("\r\n");
  400. for (var index = 0; index < splits.length; index++) {
  401. splits[index] = " " + splits[index];
  402. }
  403. replace = splits.join("\r\n");
  404. text = xhr.responseText.replace("####INJECT####", replace);
  405. } else {
  406. text = xhr.responseText;
  407. }
  408. }
  409. zip.file(name, buffer ? xhr.response : text);
  410. then();
  411. }
  412. }
  413. };
  414. xhr.send(null);
  415. }
  416. var addTexturesToZip = function (zip, index, textures, folder, then) {
  417. if (index === textures.length) {
  418. then();
  419. return;
  420. }
  421. if (textures[index].isRenderTarget || textures[index] instanceof BABYLON.DynamicTexture || textures[index].name.indexOf("data:") !== -1) {
  422. addTexturesToZip(zip, index + 1, textures, folder, then);
  423. return;
  424. }
  425. if (textures[index].isCube) {
  426. if (textures[index]._extensions && textures[index].name.indexOf("dds") === -1) {
  427. for (var i = 0; i < 6; i++) {
  428. textures.push({ name: textures[index].name + textures[index]._extensions[i] });
  429. }
  430. }
  431. else {
  432. textures.push({ name: textures[index].name });
  433. }
  434. addTexturesToZip(zip, index + 1, textures, folder, then);
  435. return;
  436. }
  437. if (folder == null) {
  438. folder = zip.folder("textures");
  439. }
  440. var url;
  441. if (textures[index].video) {
  442. url = textures[index].video.currentSrc;
  443. } else {
  444. // url = textures[index].name;
  445. url = textures[index].url ? textures[index].url : textures[index].name;
  446. }
  447. var name = textures[index].name.replace("textures/", "");
  448. // var name = url.substr(url.lastIndexOf("/") + 1);
  449. if (url != null) {
  450. addContentToZip(folder,
  451. name,
  452. url,
  453. null,
  454. true,
  455. function () {
  456. addTexturesToZip(zip, index + 1, textures, folder, then);
  457. });
  458. }
  459. else {
  460. addTexturesToZip(zip, index + 1, textures, folder, then);
  461. }
  462. }
  463. var addImportedFilesToZip = function (zip, index, importedFiles, folder, then) {
  464. if (index === importedFiles.length) {
  465. then();
  466. return;
  467. }
  468. if (!folder) {
  469. folder = zip.folder("scenes");
  470. }
  471. var url = importedFiles[index];
  472. var name = url.substr(url.lastIndexOf("/") + 1);
  473. addContentToZip(folder,
  474. name,
  475. url,
  476. null,
  477. true,
  478. function () {
  479. addImportedFilesToZip(zip, index + 1, importedFiles, folder, then);
  480. });
  481. }
  482. var getZip = function () {
  483. if (engine.scenes.length === 0) {
  484. return;
  485. }
  486. var zip = new JSZip();
  487. var scene = engine.scenes[0];
  488. var textures = scene.textures;
  489. var importedFiles = scene.importedMeshesFiles;
  490. document.getElementById("statusBar").innerHTML = "Creating archive...Please wait";
  491. if (zipCode.indexOf("textures/worldHeightMap.jpg") !== -1) {
  492. textures.push({ name: "textures/worldHeightMap.jpg" });
  493. }
  494. addContentToZip(zip,
  495. "index.html",
  496. "zipContent/index.html",
  497. zipCode,
  498. false,
  499. function () {
  500. addTexturesToZip(zip,
  501. 0,
  502. textures,
  503. null,
  504. function () {
  505. addImportedFilesToZip(zip,
  506. 0,
  507. importedFiles,
  508. null,
  509. function () {
  510. var blob = zip.generate({ type: "blob" });
  511. saveAs(blob, "sample.zip");
  512. document.getElementById("statusBar").innerHTML = "";
  513. });
  514. });
  515. });
  516. }
  517. // Versions
  518. setVersion = function (version) {
  519. switch (version) {
  520. case "stable":
  521. location.href = "indexStable.html" + location.hash;
  522. break;
  523. default:
  524. location.href = "index.html" + location.hash;
  525. break;
  526. }
  527. }
  528. // Fonts
  529. setFontSize = function (size) {
  530. fontSize = size;
  531. document.querySelector(".view-lines").style.fontSize = size + "px";
  532. setToMultipleID("currentFontSize", "innerHTML", "Font: " + size);
  533. };
  534. // Fullscreen
  535. document.getElementById("renderCanvas").addEventListener("webkitfullscreenchange", function () {
  536. if (document.webkitIsFullScreen) goFullPage();
  537. else exitFullPage();
  538. }, false);
  539. var goFullPage = function () {
  540. var canvasElement = document.getElementById("renderCanvas");
  541. canvasElement.style.position = "absolute";
  542. canvasElement.style.top = 0;
  543. canvasElement.style.left = 0;
  544. canvasElement.style.zIndex = 100;
  545. }
  546. var exitFullPage = function () {
  547. document.getElementById("renderCanvas").style.position = "relative";
  548. document.getElementById("renderCanvas").style.zIndex = 0;
  549. }
  550. var goFullscreen = function () {
  551. if (engine) {
  552. engine.switchFullscreen(true);
  553. }
  554. }
  555. var editorGoFullscreen = function () {
  556. var editorDiv = document.getElementById("jsEditor");
  557. if (editorDiv.requestFullscreen) {
  558. editorDiv.requestFullscreen();
  559. } else if (editorDiv.mozRequestFullScreen) {
  560. editorDiv.mozRequestFullScreen();
  561. } else if (editorDiv.webkitRequestFullscreen) {
  562. editorDiv.webkitRequestFullscreen();
  563. }
  564. }
  565. var toggleEditor = function () {
  566. var editorButton = document.getElementById("editorButton1600");
  567. var scene = engine.scenes[0];
  568. // If the editor is present
  569. if (editorButton.classList.contains('checked')) {
  570. setToMultipleID("editorButton", "removeClass", 'checked');
  571. splitInstance.collapse(0);
  572. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square-o" aria-hidden="true"></i>');
  573. } else {
  574. setToMultipleID("editorButton", "addClass", 'checked');
  575. splitInstance.setSizes([50, 50]); // Reset
  576. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  577. }
  578. engine.resize();
  579. if (scene.debugLayer.isVisible()) {
  580. scene.debugLayer.hide();
  581. scene.debugLayer.show();
  582. }
  583. }
  584. /**
  585. * Toggle the dark theme
  586. */
  587. var toggleTheme = function (theme) {
  588. // Monaco
  589. var vsTheme;
  590. if (theme == 'dark') {
  591. vsTheme = 'vs-dark'
  592. } else {
  593. vsTheme = 'vs'
  594. }
  595. var oldCode = jsEditor.getValue();
  596. jsEditor.dispose();
  597. editorOptions.theme = vsTheme;
  598. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  599. jsEditor.setValue(oldCode);
  600. setFontSize(fontSize);
  601. jsEditor.onKeyUp(function (evt) {
  602. markDirty();
  603. });
  604. for (var index = 0; index < elementToTheme.length; index++) {
  605. var obj = elementToTheme[index];
  606. var domObjArr = document.querySelectorAll(obj);
  607. for (var domObjIndex = 0; domObjIndex < domObjArr.length; domObjIndex++) {
  608. var domObj = domObjArr[domObjIndex];
  609. domObj.classList.remove('light');
  610. domObj.classList.remove('dark');
  611. domObj.classList.add(theme);
  612. }
  613. }
  614. localStorage.setItem("bjs-playground-theme", theme);
  615. }
  616. var toggleDebug = function () {
  617. var debugButton = document.getElementById("debugButton1600");
  618. var scene = engine.scenes[0];
  619. if (debugButton.classList.contains('uncheck')) {
  620. setToMultipleID("debugButton", "removeClass", 'uncheck');
  621. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-check-square" aria-hidden="true"></i>');
  622. scene.debugLayer.show();
  623. } else {
  624. setToMultipleID("debugButton", "addClass", 'uncheck');
  625. setToMultipleID("debugButton", "innerHTML", 'Debug layer<i class="fa fa-square-o" aria-hidden="true"></i>');
  626. scene.debugLayer.hide();
  627. }
  628. }
  629. var toggleMetadata = function () {
  630. var scene = engine.scenes[0];
  631. document.getElementById("saveLayer").style.display = "block";
  632. }
  633. var formatCode = function () {
  634. jsEditor.getAction('editor.action.format').run();
  635. }
  636. //Navigation Overwrites
  637. var exitPrompt = function (e) {
  638. var safeToggle = document.getElementById("safemodeToggle1600");
  639. if (safeToggle.classList.contains('checked')) {
  640. e = e || window.event;
  641. var message =
  642. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  643. if (e) {
  644. e.returnValue = message;
  645. }
  646. return message;
  647. }
  648. };
  649. window.onbeforeunload = exitPrompt;
  650. // Snippet
  651. var save = function () {
  652. // Retrieve title if necessary
  653. if (document.getElementById("saveLayer")) {
  654. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  655. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  656. currentSnippetTags = document.getElementById("saveFormTags").value;
  657. }
  658. var xmlHttp = new XMLHttpRequest();
  659. xmlHttp.onreadystatechange = function () {
  660. if (xmlHttp.readyState === 4) {
  661. if (xmlHttp.status === 201) {
  662. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  663. var snippet = JSON.parse(xmlHttp.responseText);
  664. var newUrl = baseUrl + "#" + snippet.id;
  665. currentSnippetToken = snippet.id;
  666. if (snippet.version && snippet.version !== "0") {
  667. newUrl += "#" + snippet.version;
  668. }
  669. location.href = newUrl;
  670. // Hide the complete title & co message
  671. hideNoMetadata();
  672. compileAndRun();
  673. } else {
  674. showError("Unable to save your code. It may be too long.", null);
  675. }
  676. }
  677. }
  678. xmlHttp.open("POST", snippetUrl + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  679. xmlHttp.setRequestHeader("Content-Type", "application/json");
  680. var dataToSend = {
  681. payload: {
  682. code: jsEditor.getValue()
  683. },
  684. name: currentSnippetTitle,
  685. description: currentSnippetDescription,
  686. tags: currentSnippetTags
  687. };
  688. xmlHttp.send(JSON.stringify(dataToSend));
  689. }
  690. var askForSave = function () {
  691. if (currentSnippetTitle == null
  692. || currentSnippetDescription == null
  693. || currentSnippetTags == null) {
  694. document.getElementById("saveLayer").style.display = "block";
  695. }
  696. else {
  697. save();
  698. }
  699. };
  700. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  701. document.getElementById("saveLayer").style.display = "none";
  702. save();
  703. });
  704. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  705. document.getElementById("saveLayer").style.display = "none";
  706. });
  707. document.getElementById("saveMessage").addEventListener("click", function () {
  708. document.getElementById("saveMessage").style.display = "none";
  709. });
  710. document.getElementById("mainTitle").innerHTML = "v" + BABYLON.Engine.Version;
  711. var previousHash = "";
  712. var cleanHash = function () {
  713. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  714. if (splits.length > 2) {
  715. splits.splice(2, splits.length - 2);
  716. }
  717. location.hash = splits.join("#");
  718. }
  719. var checkHash = function (firstTime) {
  720. if (location.hash) {
  721. if (previousHash !== location.hash) {
  722. cleanHash();
  723. previousHash = location.hash;
  724. try {
  725. var xmlHttp = new XMLHttpRequest();
  726. xmlHttp.onreadystatechange = function () {
  727. if (xmlHttp.readyState === 4) {
  728. if (xmlHttp.status === 200) {
  729. var snippet = JSON.parse(xmlHttp.responseText)[0];
  730. blockEditorChange = true;
  731. jsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  732. // Check if title / descr / tags are already set
  733. if (snippet.name != null && snippet.name != "") {
  734. currentSnippetTitle = snippet.name;
  735. }
  736. else currentSnippetTitle = null;
  737. if (snippet.description != null && snippet.description != "") {
  738. currentSnippetDescription = snippet.description;
  739. }
  740. else currentSnippetDescription = null;
  741. if (snippet.tags != null && snippet.tags != "") {
  742. currentSnippetTags = snippet.tags;
  743. }
  744. else currentSnippetTags = null;
  745. if (currentSnippetTitle != null && currentSnippetTags != null && currentSnippetDescription) {
  746. if (document.getElementById("saveLayer")) {
  747. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  748. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  749. document.getElementById("saveFormTags").value = currentSnippetTags;
  750. hideNoMetadata();
  751. }
  752. }
  753. else {
  754. showNoMetadata();
  755. }
  756. jsEditor.setPosition({ lineNumber: 0, column: 0 });
  757. blockEditorChange = false;
  758. compileAndRun();
  759. setToMultipleID("currentScript", "innerHTML", "Custom");
  760. } else if (firstTime) {
  761. location.href = location.href.replace(location.hash, "");
  762. if (scripts) {
  763. loadScriptFromIndex(0);
  764. }
  765. }
  766. }
  767. };
  768. var hash = location.hash.substr(1);
  769. currentSnippetToken = hash.split("#")[0];
  770. if (!hash.split("#")[1]) hash += "#0";
  771. xmlHttp.open("GET", snippetUrl + "/" + hash.replace("#", "/"));
  772. xmlHttp.send();
  773. } catch (e) {
  774. }
  775. }
  776. }
  777. setTimeout(checkHash, 200);
  778. }
  779. checkHash(true);
  780. // ---------- UI
  781. // Run
  782. setToMultipleID("runButton", "click", compileAndRun);
  783. // New
  784. setToMultipleID("newButton", "click", createNewScript);
  785. // Clear
  786. setToMultipleID("clearButton", "click", clear);
  787. // Save
  788. setToMultipleID("saveButton", "click", askForSave);
  789. // Zip
  790. setToMultipleID("zipButton", "click", getZip);
  791. // Themes
  792. setToMultipleID("darkTheme", "click", toggleTheme.bind(this, 'dark'));
  793. setToMultipleID("lightTheme", "click", toggleTheme.bind(this, 'light'));
  794. // Safe mode
  795. setToMultipleID("safemodeToggle", 'click', function () {
  796. document.getElementById("safemodeToggle1600").classList.toggle('checked');
  797. if (document.getElementById("safemodeToggle1600").classList.contains('checked')) {
  798. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  799. } else {
  800. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square-o" aria-hidden="true"></i>');
  801. }
  802. });
  803. // Editor
  804. setToMultipleID("editorButton", "click", toggleEditor);
  805. // FullScreen
  806. setToMultipleID("fullscreenButton", "click", goFullscreen);
  807. // Editor fullScreen
  808. setToMultipleID("editorFullscreenButton", "click", editorGoFullscreen);
  809. // Format
  810. setToMultipleID("formatButton", "click", formatCode);
  811. // Debug
  812. setToMultipleID("debugButton", "click", toggleDebug);
  813. // Metadata
  814. setToMultipleID("metadataButton", "click", toggleMetadata);
  815. // Restore theme
  816. var theme = localStorage.getItem("bjs-playground-theme") || 'light';
  817. toggleTheme(theme);
  818. }
  819. // Monaco
  820. var xhr = new XMLHttpRequest();
  821. xhr.open('GET', "babylon.d.txt", true);
  822. xhr.onreadystatechange = function () {
  823. if (xhr.readyState === 4) {
  824. if (xhr.status === 200) {
  825. require.config({ paths: { 'vs': 'node_modules/monaco-editor/min/vs' } });
  826. require(['vs/editor/editor.main'], function () {
  827. monaco.languages.typescript.javascriptDefaults.addExtraLib(xhr.responseText, 'babylon.d.ts');
  828. jsEditor = monaco.editor.create(document.getElementById('jsEditor'), editorOptions);
  829. run();
  830. });
  831. }
  832. }
  833. };
  834. xhr.send(null);
  835. })();