mainWebGPU.js 43 KB

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