main.js 40 KB

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