index.js 40 KB

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