main.js 43 KB

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