main.js 39 KB

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