main.js 40 KB

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