index.js 36 KB

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