index.js 38 KB

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