index.js 36 KB

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