main.js 44 KB

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