main.js 40 KB

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