main.js 40 KB

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