index.js 40 KB

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