main.js 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  1. var engine = null;
  2. var canvas = null;
  3. var scene = null;
  4. var globalParent = null;
  5. handleException = function(parent, e) {
  6. parent.utils.showError(e.message, e);
  7. // Also log error in console to help debug playgrounds
  8. console.error(e);
  9. }
  10. fastEval = function(code) {
  11. var head = document.getElementsByTagName('head')[0];
  12. var script = document.createElement('script');
  13. script.setAttribute('type', 'text/javascript');
  14. script.innerHTML = `try {${code};}
  15. catch(e) {
  16. handleException(globalParent, e);
  17. }`;
  18. head.appendChild(script);
  19. }
  20. /**
  21. * Compile the script in the editor, and run the preview in the canvas
  22. */
  23. compileAndRun = function(parent, fpsLabel) {
  24. // If we need to change the version, don't do this
  25. if (parent.settingsPG.mustModifyBJSversion()) return;
  26. try {
  27. parent.menuPG.hideWaitDiv();
  28. globalParent = parent;
  29. if (!BABYLON.Engine.isSupported()) {
  30. parent.utils.showError("Your browser does not support WebGL. Please, try to update it, or install a compatible one.", null);
  31. return;
  32. }
  33. var showInspector = false;
  34. parent.menuPG.showBJSPGMenu();
  35. parent.monacoCreator.JsEditor.updateOptions({ readOnly: false });
  36. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.debugLayer && BABYLON.Engine.LastCreatedScene.debugLayer.isVisible()) {
  37. showInspector = true;
  38. }
  39. if (engine) {
  40. try {
  41. engine.dispose();
  42. }
  43. catch (ex) { }
  44. engine = null;
  45. }
  46. canvas = document.getElementById("renderCanvas");
  47. document.getElementById("errorZone").style.display = 'none';
  48. document.getElementById("errorZone").innerHTML = "";
  49. document.getElementById("statusBar").innerHTML = "Loading assets... Please wait.";
  50. var checkCamera = true;
  51. var checkSceneCount = true;
  52. var createEngineFunction = "createDefaultEngine";
  53. var createSceneFunction;
  54. parent.monacoCreator.getRunCode().then(code => {
  55. createDefaultEngine = function () {
  56. return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  57. }
  58. var zipVariables = "var engine = null;\r\nvar scene = null;\r\n";
  59. var defaultEngineZip = "var createDefaultEngine = function() { return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true }); }";
  60. if (code.indexOf("createEngine") !== -1) {
  61. createEngineFunction = "createEngine";
  62. }
  63. // Check for different typos
  64. if (code.indexOf("delayCreateScene") !== -1) { // delayCreateScene
  65. createSceneFunction = "delayCreateScene";
  66. checkCamera = false;
  67. } else if (code.indexOf("createScene") !== -1) { // createScene
  68. createSceneFunction = "createScene";
  69. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  70. createSceneFunction = "CreateScene";
  71. } else if (code.indexOf("createscene") !== -1) { // createscene
  72. createSceneFunction = "createscene";
  73. }
  74. if (!createSceneFunction) {
  75. // Just pasted code.
  76. engine = createDefaultEngine();
  77. scene = new BABYLON.Scene(engine);
  78. var runScript = null;
  79. fastEval("runScript = function(scene, canvas) {" + code + "}");
  80. runScript(scene, canvas);
  81. parent.zipTool.ZipCode = zipVariables + defaultEngineZip + "var engine = createDefaultEngine();" + ";\r\nvar scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  82. } else {
  83. code += "\r\n\r\nengine = " + createEngineFunction + "();";
  84. code += "\r\nif (!engine) throw 'engine should not be null.';";
  85. if (parent.settingsPG.ScriptLanguage == "JS") {
  86. code += "\r\n" + "scene = " + createSceneFunction + "();";
  87. }
  88. else {
  89. var startCar = code.search('var ' + createSceneFunction);
  90. code = code.substr(0, startCar) + code.substr(startCar + 4);
  91. code += "\n" + "scene = " + createSceneFunction + "();";
  92. }
  93. // Execute the code
  94. fastEval(code);
  95. if (!engine) {
  96. parent.utils.showError("createEngine function must return an engine.", null);
  97. return;
  98. }
  99. if (!scene) {
  100. parent.utils.showError(createSceneFunction + " function must return a scene.", null);
  101. return;
  102. }
  103. // if scene returns a promise avoid checks
  104. if (scene.then) {
  105. checkCamera = false;
  106. checkSceneCount = false;
  107. }
  108. var createEngineZip = (createEngineFunction === "createEngine")
  109. ? zipVariables
  110. : zipVariables + defaultEngineZip;
  111. parent.zipTool.zipCode =
  112. createEngineZip + ";\r\n" +
  113. code;
  114. }
  115. engine = engine;
  116. engine.runRenderLoop(function () {
  117. if (engine.scenes.length === 0) {
  118. return;
  119. }
  120. if (canvas.width !== canvas.clientWidth) {
  121. engine.resize();
  122. }
  123. var scene = engine.scenes[0];
  124. if (scene.activeCamera || scene.activeCameras.length > 0) {
  125. scene.render();
  126. }
  127. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  128. }.bind(this));
  129. if (checkSceneCount && engine.scenes.length === 0) {
  130. parent.utils.showError("You must at least create a scene.", null);
  131. return;
  132. }
  133. if (checkCamera && engine.scenes[0].activeCamera == null) {
  134. parent.utils.showError("You must at least create a camera.", null);
  135. return;
  136. } else if (scene.then) {
  137. scene.then(function () {
  138. document.getElementById("statusBar").innerHTML = "";
  139. });
  140. } else {
  141. engine.scenes[0].executeWhenReady(function () {
  142. document.getElementById("statusBar").innerHTML = "";
  143. });
  144. }
  145. if (scene) {
  146. if (showInspector) {
  147. if (scene.then) {
  148. // Handle if scene is a promise
  149. scene.then(function (s) {
  150. if (!s.debugLayer.isVisible()) {
  151. s.debugLayer.show({ embedMode: true });
  152. }
  153. })
  154. } else {
  155. if (!scene.debugLayer.isVisible()) {
  156. scene.debugLayer.show({ embedMode: true });
  157. }
  158. }
  159. }
  160. }
  161. }).catch(e => {
  162. handleException(parent, e);
  163. });
  164. } catch (e) {
  165. handleException(parent, e);
  166. }
  167. };
  168. /**
  169. * This JS file contains the main function
  170. */
  171. class Main {
  172. constructor(parent) {
  173. this.parent = parent;
  174. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  175. this.snippetV3Url = "https://snippet.babylonjs.com"
  176. this.currentSnippetToken;
  177. this.currentSnippetTitle = null;
  178. this.currentSnippetDescription = null;
  179. this.currentSnippetTags = null;
  180. this.fpsLabel = document.getElementById("fpsLabel");
  181. this.scripts;
  182. this.previousHash = "";
  183. }
  184. /**
  185. * First function to initialize the script
  186. */
  187. initialize() {
  188. this.parent.monacoCreator.loadMonaco();
  189. };
  190. /**
  191. * Main function of the app
  192. */
  193. run() {
  194. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  195. document.getElementById("saveLayer").style.display = "none";
  196. this.save();
  197. }.bind(this));
  198. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  199. document.getElementById("saveLayer").style.display = "none";
  200. });
  201. document.getElementById("diffFormButtonOk").addEventListener("click", function () {
  202. document.getElementById("diffLayer").style.display = "none";
  203. this.diff();
  204. }.bind(this));
  205. document.getElementById("diffFormButtonCancel").addEventListener("click", function () {
  206. document.getElementById("diffLayer").style.display = "none";
  207. });
  208. // Resize the render view when resizing the window
  209. window.addEventListener("resize",
  210. function () {
  211. if (engine) {
  212. engine.resize();
  213. }
  214. }.bind(this)
  215. );
  216. // Restore BJS version if needed
  217. var restoreVersionResult = true;
  218. if (this.parent.settingsPG.restoreVersion() == false) {
  219. // Check if there a hash in the URL
  220. this.checkHash();
  221. restoreVersionResult = false;
  222. }
  223. // Load scripts list
  224. this.loadScriptsList(restoreVersionResult);
  225. // -------------------- UI --------------------
  226. // Display BJS version
  227. if (BABYLON) this.parent.utils.setToMultipleID("mainTitle", "innerHTML", "v" + BABYLON.Engine.Version);
  228. // Run
  229. this.parent.utils.setToMultipleID("runButton", "click", () => compileAndRun(this.parent, this.fpsLabel));
  230. // New
  231. this.parent.utils.setToMultipleID("newButton", "click", function () {
  232. this.parent.menuPG.removeAllOptions();
  233. this.createNewScript.call(this);
  234. }.bind(this));
  235. // Clear
  236. this.parent.utils.setToMultipleID("clearButton", "click", function () {
  237. this.parent.menuPG.removeAllOptions();
  238. this.clear.call(this);
  239. }.bind(this));
  240. // Save
  241. this.parent.utils.setToMultipleID("saveButton", "click", this.askForSave.bind(this));
  242. // Diff
  243. this.parent.utils.setToMultipleID("diffButton", "click", this.askForDiff.bind(this));
  244. this.parent.utils.setToMultipleID("previousButton", "click", this.navigateToPrevious.bind(this));
  245. this.parent.utils.setToMultipleID("nextButton", "click", this.navigateToNext.bind(this));
  246. this.parent.utils.setToMultipleID("exitButton", "click", function() {
  247. this.toggleDiffEditor(this.parent.monacoCreator, this.parent.menuPG)
  248. }.bind(this));
  249. // Zip
  250. this.parent.utils.setToMultipleID("zipButton", "click", function () {
  251. this.parent.zipTool.getZip(engine);
  252. }.bind(this));
  253. // Themes
  254. this.parent.utils.setToMultipleID("darkTheme", "click", function () {
  255. this.parent.menuPG.removeAllOptions();
  256. this.parent.settingsPG.setTheme.call(this.parent.settingsPG, 'dark');
  257. }.bind(this));
  258. this.parent.utils.setToMultipleID("lightTheme", "click", function () {
  259. this.parent.menuPG.removeAllOptions();
  260. this.parent.settingsPG.setTheme.call(this.parent.settingsPG, 'light');
  261. }.bind(this));
  262. // Size
  263. var displayFontSize = document.getElementsByClassName('displayFontSize');
  264. for (var i = 0; i < displayFontSize.length; i++) {
  265. var options = displayFontSize[i].querySelectorAll('.option');
  266. for (var j = 0; j < options.length; j++) {
  267. options[j].addEventListener('click', function (evt) {
  268. this.parent.menuPG.removeAllOptions();
  269. this.parent.settingsPG.setFontSize.call(this.parent.settingsPG, evt.target.innerText)
  270. }.bind(this));
  271. }
  272. }
  273. // Footer links
  274. var displayFontSize = document.getElementsByClassName('displayFooterLinks');
  275. for (var i = 0; i < displayFontSize.length; i++) {
  276. var options = displayFontSize[i].querySelectorAll('.option');
  277. for (var j = 0; j < options.length; j++) {
  278. options[j].addEventListener('click', this.parent.menuPG.clickOptionSub.bind(this));
  279. }
  280. }
  281. // Language (JS / TS)
  282. this.parent.utils.setToMultipleID("toTSbutton", "click", function () {
  283. if(location.hash != null && location.hash != ""){
  284. this.parent.settingsPG.ScriptLanguage = "TS";
  285. window.location = "./";
  286. }else{
  287. if (this.parent.settingsPG.ScriptLanguage == "JS") {
  288. //revert in case the reload is cancel due to safe mode
  289. if(document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()).classList.contains('checked')){
  290. // Message before unload
  291. var languageTSswapper = function () {
  292. this.parent.settingsPG.ScriptLanguage = "TS";
  293. window.removeEventListener('unload', languageTSswapper.bind(this));
  294. };
  295. window.addEventListener('unload',languageTSswapper.bind(this));
  296. location.reload();
  297. }
  298. else {
  299. this.parent.settingsPG.ScriptLanguage = "TS";
  300. location.reload();
  301. }
  302. }
  303. }
  304. }.bind(this));
  305. this.parent.utils.setToMultipleID("toJSbutton", "click", function () {
  306. if(location.hash != null && location.hash != ""){
  307. this.parent.settingsPG.ScriptLanguage = "JS";
  308. window.location = "./";
  309. }else{
  310. if (this.parent.settingsPG.ScriptLanguage == "TS") {
  311. //revert in case the reload is cancel due to safe mode
  312. if(document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()).classList.contains('checked')){
  313. // Message before unload
  314. var LanguageJSswapper = function () {
  315. this.parent.settingsPG.ScriptLanguage = "JS";
  316. window.removeEventListener('unload', LanguageJSswapper.bind(this));
  317. };
  318. window.addEventListener('unload',LanguageJSswapper.bind(this));
  319. location.reload();
  320. }
  321. else {
  322. this.parent.settingsPG.ScriptLanguage = "JS";
  323. location.reload();
  324. }
  325. }
  326. }
  327. }.bind(this));
  328. // Safe mode
  329. this.parent.utils.setToMultipleID("safemodeToggle", 'click', function () {
  330. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  331. if (document.getElementById("safemodeToggle1280").classList.contains('checked')) {
  332. this.parent.utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  333. } else {
  334. this.parent.utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square" aria-hidden="true"></i>');
  335. }
  336. }.bind(this));
  337. // Editor
  338. this.parent.utils.setToMultipleID("editorButton", "click", this.toggleEditor.bind(this));
  339. // FullScreen
  340. this.parent.utils.setToMultipleID("fullscreenButton", "click", function () {
  341. this.parent.menuPG.removeAllOptions();
  342. this.parent.menuPG.goFullscreen(engine);
  343. }.bind(this));
  344. // Editor fullScreen
  345. this.parent.utils.setToMultipleID("editorFullscreenButton", "click", function () {
  346. this.parent.menuPG.removeAllOptions();
  347. this.parent.menuPG.editorGoFullscreen.call(this.parent.menuPG)
  348. }.bind(this));
  349. // Format
  350. this.parent.utils.setToMultipleID("formatButton", "click", function () {
  351. this.parent.menuPG.removeAllOptions();
  352. this.parent.monacoCreator.formatCode.call(this.parent.monacoCreator)
  353. }.bind(this));
  354. // Minimap
  355. this.parent.utils.setToMultipleID("minimapToggle", "click", this.parent.monacoCreator.toggleMinimap.bind(this.parent.monacoCreator));
  356. // Inspector
  357. this.parent.utils.setToMultipleID("debugButton", "click", function () {
  358. this.parent.menuPG.removeAllOptions();
  359. this.toggleDebug.call(this);
  360. }.bind(this));
  361. // Metadata
  362. this.parent.utils.setToMultipleID("metadataButton", "click", function () {
  363. this.parent.menuPG.removeAllOptions();
  364. this.parent.menuPG.displayMetadata.call(this.parent.menuPG)
  365. }.bind(this));
  366. // Initialize the metadata form
  367. this.showNoMetadata();
  368. // Restore theme
  369. this.parent.settingsPG.restoreTheme();
  370. // Restore font size
  371. this.parent.settingsPG.restoreFont();
  372. // Restore language
  373. this.parent.settingsPG.setScriptLanguage();
  374. // Check if it's mobile mode. If true, switch to full canvas by default
  375. this.parent.menuPG.resizeBigCanvas();
  376. };
  377. /**
  378. * Check if we're in the correct language for the selected script
  379. * @param {*} xhr
  380. */
  381. checkTypescriptSupport(xhr) {
  382. // If we're loading TS content and it's JS page
  383. if (xhr.responseText.indexOf("class Playground") !== -1) {
  384. if (this.parent.settingsPG.ScriptLanguage == "JS") {
  385. this.parent.settingsPG.ScriptLanguage = "TS";
  386. location.reload();
  387. return false;
  388. }
  389. } else { // If we're loading JS content and it's TS page
  390. if (this.parent.settingsPG.ScriptLanguage == "TS") {
  391. this.parent.settingsPG.ScriptLanguage = "JS";
  392. location.reload();
  393. return false;
  394. }
  395. }
  396. return true;
  397. };
  398. /**
  399. * Load a script in the database
  400. * @param {*} scriptURL
  401. * @param {*} title
  402. */
  403. loadScript(scriptURL, title) {
  404. var xhr = new XMLHttpRequest();
  405. xhr.open('GET', scriptURL, true);
  406. xhr.onreadystatechange = function () {
  407. if (xhr.readyState === 4) {
  408. if (xhr.status === 200) {
  409. if (!this.checkTypescriptSupport(xhr)) return;
  410. xhr.onreadystatechange = null;
  411. this.parent.monacoCreator.BlockEditorChange = true;
  412. this.parent.monacoCreator.JsEditor.setValue(xhr.responseText);
  413. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  414. this.parent.monacoCreator.BlockEditorChange = false;
  415. compileAndRun(this.parent, this.fpsLabel);
  416. this.currentSnippetToken = null;
  417. }
  418. }
  419. }.bind(this);
  420. xhr.send(null);
  421. };
  422. /**
  423. * Load the examples scripts list in the database
  424. */
  425. loadScriptsList(restoreVersionResult) {
  426. var exampleList = document.getElementById("exampleList");
  427. var xhr = new XMLHttpRequest();
  428. // Open Typescript or Javascript examples
  429. if (exampleList.className != 'typescript') {
  430. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list.json', true);
  431. }
  432. else {
  433. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list_ts.json', true);
  434. }
  435. xhr.onreadystatechange = function () {
  436. if (xhr.readyState === 4) {
  437. if (xhr.status === 200) {
  438. this.scripts = JSON.parse(xhr.response)["examples"];
  439. function sortScriptsList(a, b) {
  440. if (a.title < b.title) return -1;
  441. else return 1;
  442. }
  443. this.scripts.sort(sortScriptsList);
  444. if (exampleList) {
  445. for (var i = 0; i < this.scripts.length; i++) {
  446. this.scripts[i].samples.sort(sortScriptsList);
  447. var exampleCategory = document.createElement("div");
  448. exampleCategory.classList.add("categoryContainer");
  449. var exampleCategoryTitle = document.createElement("p");
  450. exampleCategoryTitle.innerText = this.scripts[i].title;
  451. exampleCategory.appendChild(exampleCategoryTitle);
  452. for (var ii = 0; ii < this.scripts[i].samples.length; ii++) {
  453. var example = document.createElement("div");
  454. example.classList.add("itemLine");
  455. example.id = ii;
  456. var exampleImg = document.createElement("img");
  457. exampleImg.src = this.scripts[i].samples[ii].icon.replace("icons", "https://doc.babylonjs.com/examples/icons");
  458. exampleImg.setAttribute("onClick", "document.getElementById('PGLink_" + this.scripts[i].samples[ii].PGID + "').click();");
  459. var exampleContent = document.createElement("div");
  460. exampleContent.classList.add("itemContent");
  461. exampleContent.setAttribute("onClick", "document.getElementById('PGLink_" + this.scripts[i].samples[ii].PGID + "').click();");
  462. var exampleContentLink = document.createElement("div");
  463. exampleContentLink.classList.add("itemContentLink");
  464. var exampleTitle = document.createElement("h3");
  465. exampleTitle.classList.add("exampleCategoryTitle");
  466. exampleTitle.innerText = this.scripts[i].samples[ii].title;
  467. var exampleDescr = document.createElement("div");
  468. exampleDescr.classList.add("itemLineChild");
  469. exampleDescr.innerText = this.scripts[i].samples[ii].description;
  470. var exampleDocLink = document.createElement("a");
  471. exampleDocLink.classList.add("itemLineDocLink");
  472. exampleDocLink.innerText = "Documentation";
  473. exampleDocLink.href = this.scripts[i].samples[ii].doc;
  474. exampleDocLink.target = "_blank";
  475. var examplePGLink = document.createElement("a");
  476. examplePGLink.id = "PGLink_" + this.scripts[i].samples[ii].PGID;
  477. examplePGLink.classList.add("itemLinePGLink");
  478. examplePGLink.innerText = "Display";
  479. examplePGLink.href = this.scripts[i].samples[ii].PGID;
  480. examplePGLink.addEventListener("click", function() {
  481. location.href = this.href;
  482. location.reload();
  483. });
  484. exampleContentLink.appendChild(exampleTitle);
  485. exampleContentLink.appendChild(exampleDescr);
  486. exampleContent.appendChild(exampleContentLink);
  487. exampleContent.appendChild(exampleDocLink);
  488. exampleContent.appendChild(examplePGLink);
  489. example.appendChild(exampleImg);
  490. example.appendChild(exampleContent);
  491. exampleCategory.appendChild(example);
  492. }
  493. exampleList.appendChild(exampleCategory);
  494. }
  495. var noResultContainer = document.createElement("div");
  496. noResultContainer.id = "noResultsContainer";
  497. noResultContainer.classList.add("categoryContainer");
  498. noResultContainer.style.display = "none";
  499. noResultContainer.innerHTML = "<p id='noResults'>No results found.</p>";
  500. exampleList.appendChild(noResultContainer);
  501. }
  502. if (!location.hash && restoreVersionResult == false) {
  503. // Query string
  504. var queryString = window.location.search;
  505. if (queryString) {
  506. var query = queryString.replace("?", "");
  507. index = parseInt(query);
  508. if (!isNaN(index)) {
  509. var newPG = "";
  510. switch (index) {
  511. case 1: newPG = "#TAZ2CB#0"; break; // Basic scene
  512. case 2: newPG = "#A1210C#0"; break; // Basic elements
  513. case 3: newPG = "#CURCZC#0"; break; // Rotation and scaling
  514. case 4: newPG = "#DXARSP#0"; break; // Materials
  515. case 5: newPG = "#1A3M5C#0"; break; // Cameras
  516. case 6: newPG = "#AQRDKW#0"; break; // Lights
  517. case 7: newPG = "#QYFDDP#1"; break; // Animations
  518. case 8: newPG = "#9RI8CG#0"; break; // Sprites
  519. case 9: newPG = "#U8MEB0#0"; break; // Collisions
  520. case 10: newPG = "#KQV9SA#0"; break; // Intersections
  521. case 11: newPG = "#NU4F6Y#0"; break; // Picking
  522. case 12: newPG = "#EF9X5R#0"; break; // Particles
  523. case 13: newPG = "#7G0IQW#0"; break; // Environment
  524. case 14: newPG = "#95PXRY#0"; break; // Height map
  525. case 15: newPG = "#IFYDRS#0"; break; // Shadows
  526. case 16: newPG = "#AQZJ4C#0"; break; // Import meshes
  527. case 17: newPG = "#J19GYK#0"; break; // Actions
  528. case 18: newPG = "#UZ23UH#0"; break; // Drag and drop
  529. case 19: newPG = "#AQZJ4C#0"; break; // Fresnel
  530. case 20: newPG = "#8ZNVGR#0"; break; // Easing functions
  531. case 21: newPG = "#B2ZXG6#0"; break; // Procedural texture
  532. case 22: newPG = "#DXAEUY#0"; break; // Basic sounds
  533. case 23: newPG = "#EDVU95#0"; break; // Sound on mesh
  534. case 24: newPG = "#N96NXC#0"; break; // SSAO rendering pipeline
  535. case 25: newPG = "#7D2QDD#0"; break; // SSAO 2
  536. case 26: newPG = "#V2DAKC#0"; break; // Volumetric light scattering
  537. case 27: newPG = "#XH85A9#0"; break; // Refraction and reflection
  538. case 28: newPG = "#8MGKWK#0"; break; // PBR
  539. case 29: newPG = "#0K8EYN#0"; break; // Instanced bones
  540. case 30: newPG = "#C245A1#0"; break; // Pointer events handling
  541. case 31: newPG = "#TAFSN0#2"; break; // WebVR
  542. case 32: newPG = "#3VMTI9#0"; break; // GUI
  543. case 33: newPG = "#7149G4#0"; break; // Physics
  544. default: newPG = ""; break;
  545. }
  546. window.location.href = location.protocol + "//" + location.host + location.pathname + "#" + newPG;
  547. } else if (query.indexOf("=") === -1) {
  548. this.loadScript("scripts/" + query + ".js", query);
  549. } else {
  550. this.loadScript(this.parent.settingsPG.DefaultScene, "Basic scene");
  551. }
  552. } else {
  553. this.loadScript(this.parent.settingsPG.DefaultScene, "Basic scene");
  554. }
  555. }
  556. // Restore language
  557. this.parent.settingsPG.setScriptLanguage();
  558. }
  559. }
  560. }.bind(this);
  561. xhr.send(null);
  562. };
  563. createNewScript() {
  564. // Check if safe mode is on, and ask if it is
  565. if (!this.checkSafeMode("Are you sure you want to create a new playground?")) return;
  566. location.hash = "";
  567. this.currentSnippetToken = null;
  568. this.currentSnippetTitle = null;
  569. this.currentSnippetDescription = null;
  570. this.currentSnippetTags = null;
  571. this.showNoMetadata();
  572. if (this.parent.monacoCreator.monacoMode === "javascript") {
  573. this.parent.monacoCreator.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\r\nvar createScene = function() {\r\n\tvar scene = new BABYLON.Scene(engine);\r\n\tvar camera = new BABYLON.ArcRotateCamera("Camera", -Math.PI / 2, 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};');
  574. } else {
  575. this.parent.monacoCreator.JsEditor.setValue('// You have to create a class called Playground. This class must provide a static function named CreateScene(engine, canvas) which must return a BABYLON.Scene object\r\n// You must at least define a camera inside the CreateScene function\r\n\r\nclass Playground {\r\n\tpublic static CreateScene(engine: BABYLON.Engine, canvas: HTMLCanvasElement): BABYLON.Scene {\r\n\t\tvar scene = new BABYLON.Scene(engine);\r\n\r\n\t\tvar camera = new BABYLON.FreeCamera("camera1", new BABYLON.Vector3(0, 5, -10), scene);\r\n\t\tcamera.setTarget(BABYLON.Vector3.Zero());\r\n\t\tcamera.attachControl(canvas, true);\r\n\r\n\t\treturn scene;\r\n\t}\r\n}');
  576. }
  577. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 11, column: 0 });
  578. this.parent.monacoCreator.JsEditor.focus();
  579. compileAndRun(this.parent, this.fpsLabel);
  580. };
  581. clear() {
  582. // Check if safe mode is on, and ask if it is
  583. if (!this.checkSafeMode("Are you sure you want to clear the playground?")) return;
  584. location.hash = "";
  585. this.currentSnippetToken = null;
  586. this.parent.monacoCreator.JsEditor.setValue('');
  587. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  588. this.parent.monacoCreator.JsEditor.focus();
  589. };
  590. compileAndRunFromOutside() {
  591. compileAndRun(this.parent, this.fpsLabel);
  592. };
  593. checkSafeMode(message) {
  594. if (document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()) &&
  595. document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()).classList.contains('checked')) {
  596. let confirm = window.confirm(message);
  597. if (!confirm) {
  598. return false;
  599. } else {
  600. for (var i = 0; i < this.parent.utils.multipleSize.length; i++) {
  601. document.getElementById("safemodeToggle" + this.parent.utils.multipleSize[i]).classList.toggle('checked');
  602. }
  603. return true;
  604. }
  605. } else {
  606. return true;
  607. }
  608. };
  609. /**
  610. * Metadatas form
  611. */
  612. showNoMetadata() {
  613. if (this.currentSnippetTitle) {
  614. document.getElementById("saveFormTitle").value = this.currentSnippetTitle;
  615. document.getElementById("saveFormTitle").readOnly = true;
  616. }
  617. else {
  618. document.getElementById("saveFormTitle").value = '';
  619. document.getElementById("saveFormTitle").readOnly = false;
  620. }
  621. if (this.currentSnippetDescription) {
  622. document.getElementById("saveFormDescription").value = this.currentSnippetDescription;
  623. document.getElementById("saveFormDescription").readOnly = true;
  624. }
  625. else {
  626. document.getElementById("saveFormDescription").value = '';
  627. document.getElementById("saveFormDescription").readOnly = false;
  628. }
  629. if (this.currentSnippetTags) {
  630. document.getElementById("saveFormTags").value = this.currentSnippetTags;
  631. document.getElementById("saveFormTags").readOnly = true;
  632. }
  633. else {
  634. document.getElementById("saveFormTags").value = '';
  635. document.getElementById("saveFormTags").readOnly = false;
  636. }
  637. document.getElementById("saveFormButtons").style.display = "block";
  638. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  639. };
  640. hideNoMetadata() {
  641. document.getElementById("saveFormTitle").readOnly = true;
  642. document.getElementById("saveFormDescription").readOnly = true;
  643. document.getElementById("saveFormTags").readOnly = true;
  644. document.getElementById("saveFormButtonOk").style.display = "none";
  645. };
  646. /*
  647. * Metadatas save
  648. */
  649. save() {
  650. // Retrieve title if necessary
  651. if (document.getElementById("saveLayer")) {
  652. this.currentSnippetTitle = document.getElementById("saveFormTitle").value;
  653. this.currentSnippetDescription = document.getElementById("saveFormDescription").value;
  654. this.currentSnippetTags = document.getElementById("saveFormTags").value;
  655. }
  656. var xmlHttp = new XMLHttpRequest();
  657. xmlHttp.onreadystatechange = function () {
  658. if (xmlHttp.readyState === 4) {
  659. if (xmlHttp.status === 200) {
  660. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  661. var snippet = JSON.parse(xmlHttp.responseText);
  662. var newUrl = baseUrl + "#" + snippet.id;
  663. this.currentSnippetToken = snippet.id;
  664. if (snippet.version && snippet.version !== "0") {
  665. newUrl += "#" + snippet.version;
  666. }
  667. location.href = newUrl;
  668. // Hide the complete title & co message
  669. this.hideNoMetadata();
  670. compileAndRun(this.parent, this.fpsLabel);
  671. } else {
  672. this.parent.utils.showError("Unable to save your code. It may be too long.", null);
  673. }
  674. }
  675. }.bind(this);
  676. xmlHttp.open("POST", this.snippetV3Url + (this.currentSnippetToken ? "/" + this.currentSnippetToken : ""), true);
  677. xmlHttp.setRequestHeader("Content-Type", "application/json");
  678. var dataToSend = {
  679. payload: JSON.stringify({
  680. code: this.parent.monacoCreator.JsEditor.getValue()
  681. }),
  682. name: this.currentSnippetTitle,
  683. description: this.currentSnippetDescription,
  684. tags: this.currentSnippetTags
  685. };
  686. xmlHttp.send(JSON.stringify(dataToSend));
  687. };
  688. askForSave() {
  689. if (this.currentSnippetTitle == null
  690. || this.currentSnippetDescription == null
  691. || this.currentSnippetTags == null) {
  692. document.getElementById("saveLayer").style.display = "block";
  693. }
  694. else {
  695. this.save();
  696. }
  697. };
  698. askForDiff() {
  699. const diffLayer = document.getElementById("diffLayer");
  700. const right = document.getElementById("diffFormCompareTo");
  701. if (this.previousHash && right.value === "") {
  702. // Use the previous snippet hash for right comparison, if present
  703. right.value = this.previousHash;
  704. }
  705. diffLayer.style.display = "block";
  706. }
  707. async loadSnippetCode(snippetid) {
  708. if (!snippetid || snippetid === "")
  709. return "";
  710. let response = await fetch(`${this.snippetV3Url}/${snippetid.replace(/#/g, "/")}`);
  711. if (!response.ok)
  712. throw new Error(`Unable to load snippet ${snippetid}`)
  713. let result = await response.json();
  714. return JSON.parse(result.jsonPayload).code.toString();
  715. }
  716. async getSnippetCode(value) {
  717. if (!value || value === "") {
  718. // use current snippet
  719. return this.parent.monacoCreator.JsEditor.getValue();
  720. } else {
  721. // load script
  722. return await this.loadSnippetCode(value);
  723. }
  724. }
  725. async diff() {
  726. try {
  727. const leftText = await this.getSnippetCode(document.getElementById("diffFormSource").value);
  728. const rightText = await this.getSnippetCode(document.getElementById("diffFormCompareTo").value);
  729. this.toggleDiffEditor(this.parent.monacoCreator, this.parent.menuPG, leftText, rightText);
  730. } catch(e) {
  731. // only pass the message, we don't want to inspect the stacktrace in this case
  732. this.parent.utils.showError(e.message, null);
  733. }
  734. }
  735. toggleDiffEditor(monacoCreator, menuPG, leftText, rightText) {
  736. const diffView = document.getElementById("diffView");
  737. if (leftText && rightText) {
  738. menuPG.resizeForDiff();
  739. diffView.style.display = "block";
  740. monacoCreator.createDiff(leftText, rightText, diffView);
  741. } else {
  742. monacoCreator.disposeDiff();
  743. diffView.style.display = "none";
  744. if (menuPG.isMobileVersion) {
  745. menuPG.resizeBigJsEditor();
  746. } else {
  747. menuPG.resizeSplitted();
  748. }
  749. }
  750. }
  751. navigateToPrevious() {
  752. var dn = this.parent.monacoCreator.diffNavigator;
  753. if (!dn)
  754. return;
  755. if (dn.canNavigate())
  756. dn.previous();
  757. }
  758. navigateToNext() {
  759. var dn = this.parent.monacoCreator.diffNavigator;
  760. if (!dn)
  761. return;
  762. if (dn.canNavigate())
  763. dn.next();
  764. }
  765. /**
  766. * Toggle the code editor
  767. */
  768. toggleEditor() {
  769. var editorButton = document.getElementById("editorButton1280");
  770. var scene = engine.scenes[0];
  771. // If the editor is present
  772. if (editorButton.classList.contains('checked')) {
  773. this.parent.utils.setToMultipleID("editorButton", "removeClass", 'checked');
  774. this.parent.splitInstance.collapse(0);
  775. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square" aria-hidden="true"></i>');
  776. } else {
  777. this.parent.utils.setToMultipleID("editorButton", "addClass", 'checked');
  778. this.parent.splitInstance.setSizes([50, 50]); // Reset
  779. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  780. }
  781. engine.resize();
  782. if (scene.debugLayer.isVisible()) {
  783. scene.debugLayer.show({ embedMode: true });
  784. }
  785. };
  786. /**
  787. * Toggle the BJS debug layer
  788. */
  789. toggleDebug() {
  790. // Always showing the debug layer, because you can close it by itself
  791. var scene = engine.scenes[0];
  792. if (scene.debugLayer.isVisible()) {
  793. scene.debugLayer.hide();
  794. }
  795. else {
  796. scene.debugLayer.show({ embedMode: true });
  797. }
  798. };
  799. /**
  800. * HASH part
  801. */
  802. cleanHash() {
  803. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  804. if (splits.length > 2) {
  805. splits.splice(2, splits.length - 2);
  806. }
  807. location.hash = splits.join("#");
  808. };
  809. checkHash() {
  810. if (location.hash) {
  811. if (this.previousHash !== location.hash) {
  812. this.cleanHash();
  813. this.previousHash = location.hash;
  814. try {
  815. var xmlHttp = new XMLHttpRequest();
  816. xmlHttp.onreadystatechange = function () {
  817. if (xmlHttp.readyState === 4) {
  818. if (xmlHttp.status === 200) {
  819. if (!this.checkTypescriptSupport(xmlHttp)) {
  820. return;
  821. }
  822. var snippet = JSON.parse(xmlHttp.responseText);
  823. this.parent.monacoCreator.BlockEditorChange = true;
  824. this.parent.monacoCreator.JsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  825. // Check if title / descr / tags are already set
  826. if (snippet.name != null && snippet.name != "") {
  827. this.currentSnippetTitle = snippet.name;
  828. }
  829. else this.currentSnippetTitle = null;
  830. if (snippet.description != null && snippet.description != "") {
  831. this.currentSnippetDescription = snippet.description;
  832. }
  833. else this.currentSnippetDescription = null;
  834. if (snippet.tags != null && snippet.tags != "") {
  835. this.currentSnippetTags = snippet.tags;
  836. }
  837. else this.currentSnippetTags = null;
  838. if (this.currentSnippetTitle != null && this.currentSnippetTags != null && this.currentSnippetDescription) {
  839. if (document.getElementById("saveLayer")) {
  840. document.getElementById("saveFormTitle").value = this.currentSnippetTitle;
  841. document.getElementById("saveFormDescription").value = this.currentSnippetDescription;
  842. document.getElementById("saveFormTags").value = this.currentSnippetTags;
  843. this.hideNoMetadata();
  844. }
  845. }
  846. else {
  847. this.showNoMetadata();
  848. }
  849. this.parent.monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  850. this.parent.monacoCreator.BlockEditorChange = false;
  851. compileAndRun(this.parent, this.fpsLabel);
  852. }
  853. }
  854. }.bind(this);
  855. var hash = location.hash.substr(1);
  856. this.currentSnippetToken = hash.split("#")[0];
  857. if (!hash.split("#")[1]) hash += "#0";
  858. xmlHttp.open("GET", this.snippetV3Url + "/" + hash.replace("#", "/"));
  859. xmlHttp.send();
  860. } catch (e) {
  861. }
  862. }
  863. }
  864. setTimeout(this.checkHash.bind(this), 200);
  865. };
  866. }