index.js 39 KB

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