mainWebGPU.js 39 KB

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