main.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. var engine = null;
  2. var canvas = 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({
  36. readOnly: false
  37. });
  38. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.debugLayer && BABYLON.Engine.LastCreatedScene.debugLayer.isVisible()) {
  39. showInspector = true;
  40. }
  41. if (engine) {
  42. try {
  43. engine.dispose();
  44. } catch (ex) {}
  45. engine = null;
  46. }
  47. canvas = document.getElementById("renderCanvas");
  48. document.getElementById("errorZone").style.display = 'none';
  49. document.getElementById("errorZone").innerHTML = "";
  50. document.getElementById("statusBar").innerHTML = "Loading assets... Please wait.";
  51. var checkCamera = true;
  52. var checkSceneCount = true;
  53. var createEngineFunction = "createDefaultEngine";
  54. var createSceneFunction;
  55. parent.monacoCreator.getRunCode().then(code => {
  56. createDefaultEngine = function () {
  57. return new BABYLON.Engine(canvas, true, {
  58. preserveDrawingBuffer: true,
  59. stencil: true
  60. });
  61. }
  62. var zipVariables = "var engine = null;\r\nvar scene = null;\r\n";
  63. var defaultEngineZip = "var createDefaultEngine = function() { return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true }); }";
  64. if (code.indexOf("createEngine") !== -1) {
  65. createEngineFunction = "createEngine";
  66. }
  67. // Check for different typos
  68. if (code.indexOf("delayCreateScene") !== -1) { // delayCreateScene
  69. createSceneFunction = "delayCreateScene";
  70. checkCamera = false;
  71. } else if (code.indexOf("createScene") !== -1) { // createScene
  72. createSceneFunction = "createScene";
  73. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  74. createSceneFunction = "CreateScene";
  75. } else if (code.indexOf("createscene") !== -1) { // createscene
  76. createSceneFunction = "createscene";
  77. }
  78. if (!createSceneFunction) {
  79. // Just pasted code.
  80. engine = createDefaultEngine();
  81. scene = new BABYLON.Scene(engine);
  82. var runScript = null;
  83. fastEval("runScript = function(scene, canvas) {" + code + "}");
  84. runScript(scene, canvas);
  85. parent.zipTool.ZipCode = zipVariables + defaultEngineZip + "var engine = createDefaultEngine();" + ";\r\nvar scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  86. } else {
  87. code += "\r\n\r\nengine = " + createEngineFunction + "();";
  88. code += "\r\nif (!engine) throw 'engine should not be null.';";
  89. if (parent.settingsPG.ScriptLanguage == "JS") {
  90. code += "\r\n" + "scene = " + createSceneFunction + "();";
  91. } else {
  92. var startCar = code.search('var ' + createSceneFunction);
  93. code = code.substr(0, startCar) + code.substr(startCar + 4);
  94. code += "\n" + "scene = " + createSceneFunction + "();";
  95. }
  96. // Execute the code
  97. fastEval(code);
  98. if (!engine) {
  99. parent.utils.showError("createEngine function must return an engine.", null);
  100. return;
  101. }
  102. if (!scene) {
  103. parent.utils.showError(createSceneFunction + " function must return a scene.", null);
  104. return;
  105. }
  106. // if scene returns a promise avoid checks
  107. if (scene.then) {
  108. checkCamera = false;
  109. checkSceneCount = false;
  110. }
  111. var createEngineZip = (createEngineFunction === "createEngine") ?
  112. zipVariables :
  113. zipVariables + defaultEngineZip;
  114. parent.zipTool.zipCode =
  115. createEngineZip + ";\r\n" +
  116. code;
  117. }
  118. engine = engine;
  119. var sceneToRender;
  120. if (scene.then) {
  121. scene.then(s => {
  122. sceneToRender = s;
  123. });
  124. } else {
  125. sceneToRender = scene;
  126. }
  127. engine.runRenderLoop(function () {
  128. if (!sceneToRender) {
  129. return;
  130. }
  131. if (canvas.width !== canvas.clientWidth) {
  132. engine.resize();
  133. }
  134. if (sceneToRender.activeCamera || sceneToRender.activeCameras.length > 0) {
  135. sceneToRender.render();
  136. }
  137. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  138. }.bind(this));
  139. if (checkSceneCount && engine.scenes.length === 0) {
  140. parent.utils.showError("You must at least create a scene.", null);
  141. return;
  142. }
  143. if (checkCamera && engine.scenes[0].activeCamera == null) {
  144. parent.utils.showError("You must at least create a camera.", null);
  145. return;
  146. } else if (scene.then) {
  147. scene.then(function () {
  148. document.getElementById("statusBar").innerHTML = "";
  149. });
  150. } else {
  151. engine.scenes[0].executeWhenReady(function () {
  152. document.getElementById("statusBar").innerHTML = "";
  153. });
  154. }
  155. if (scene) {
  156. if (showInspector) {
  157. if (scene.then) {
  158. // Handle if scene is a promise
  159. scene.then(function (s) {
  160. if (!s.debugLayer.isVisible()) {
  161. s.debugLayer.show({
  162. embedMode: true
  163. });
  164. }
  165. })
  166. } else {
  167. if (!scene.debugLayer.isVisible()) {
  168. scene.debugLayer.show({
  169. embedMode: true
  170. });
  171. }
  172. }
  173. }
  174. }
  175. }).catch(e => {
  176. handleException(parent, e);
  177. });
  178. } catch (e) {
  179. handleException(parent, e);
  180. }
  181. };
  182. /**
  183. * This JS file contains the main function
  184. */
  185. class Main {
  186. constructor(parent) {
  187. this.parent = parent;
  188. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  189. this.snippetV3Url = "https://snippet.babylonjs.com"
  190. this.currentSnippetToken;
  191. this.currentSnippetTitle = null;
  192. this.currentSnippetDescription = null;
  193. this.currentSnippetTags = null;
  194. this.fpsLabel = document.getElementById("fpsLabel");
  195. this.scripts;
  196. this.previousHash = "";
  197. }
  198. /**
  199. * First function to initialize the script
  200. */
  201. initialize() {
  202. this.parent.monacoCreator.loadMonaco();
  203. };
  204. /**
  205. * Main function of the app
  206. */
  207. run() {
  208. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  209. document.getElementById("saveLayer").style.display = "none";
  210. this.save();
  211. }.bind(this));
  212. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  213. document.getElementById("saveLayer").style.display = "none";
  214. });
  215. document.getElementById("diffFormButtonOk").addEventListener("click", function () {
  216. document.getElementById("diffLayer").style.display = "none";
  217. this.diff();
  218. }.bind(this));
  219. document.getElementById("diffFormButtonCancel").addEventListener("click", function () {
  220. document.getElementById("diffLayer").style.display = "none";
  221. });
  222. // Resize the render view when resizing the window
  223. window.addEventListener("resize",
  224. function () {
  225. if (engine) {
  226. engine.resize();
  227. }
  228. }.bind(this)
  229. );
  230. // Restore BJS version if needed
  231. var restoreVersionResult = true;
  232. if (this.parent.settingsPG.restoreVersion() == false) {
  233. // Check if there a hash in the URL
  234. this.checkHash();
  235. restoreVersionResult = false;
  236. }
  237. // Load scripts list
  238. this.loadScriptsList(restoreVersionResult);
  239. // -------------------- UI --------------------
  240. var handleRun = () => compileAndRun(this.parent, this.fpsLabel);
  241. var handleSave = () => this.askForSave();
  242. var handleGetZip = () => this.parent.zipTool.getZip(engine);
  243. // Display BJS version
  244. if (BABYLON) this.parent.utils.setToMultipleID("mainTitle", "innerHTML", "v" + BABYLON.Engine.Version);
  245. // Run
  246. this.parent.utils.setToMultipleID("runButton", "click", handleRun);
  247. // New
  248. this.parent.utils.setToMultipleID("newButton", "click", function () {
  249. this.parent.menuPG.removeAllOptions();
  250. this.createNewScript.call(this);
  251. }.bind(this));
  252. // Clear
  253. this.parent.utils.setToMultipleID("clearButton", "click", function () {
  254. this.parent.menuPG.removeAllOptions();
  255. this.clear.call(this);
  256. }.bind(this));
  257. // Save
  258. this.parent.utils.setToMultipleID("saveButton", "click", handleSave);
  259. // Diff
  260. this.parent.utils.setToMultipleID("diffButton", "click", this.askForDiff.bind(this));
  261. this.parent.utils.setToMultipleID("previousButton", "click", this.navigateToPrevious.bind(this));
  262. this.parent.utils.setToMultipleID("nextButton", "click", this.navigateToNext.bind(this));
  263. this.parent.utils.setToMultipleID("exitButton", "click", function () {
  264. this.toggleDiffEditor(this.parent.monacoCreator, this.parent.menuPG)
  265. }.bind(this));
  266. // Zip
  267. this.parent.utils.setToMultipleID("zipButton", "click", handleGetZip);
  268. // Themes
  269. this.parent.utils.setToMultipleID("darkTheme", "click", function () {
  270. this.parent.menuPG.removeAllOptions();
  271. this.parent.settingsPG.setTheme.call(this.parent.settingsPG, 'dark');
  272. }.bind(this));
  273. this.parent.utils.setToMultipleID("lightTheme", "click", function () {
  274. this.parent.menuPG.removeAllOptions();
  275. this.parent.settingsPG.setTheme.call(this.parent.settingsPG, 'light');
  276. }.bind(this));
  277. // Size
  278. var displayFontSize = document.getElementsByClassName('displayFontSize');
  279. for (var i = 0; i < displayFontSize.length; i++) {
  280. var options = displayFontSize[i].querySelectorAll('.option');
  281. for (var j = 0; j < options.length; j++) {
  282. options[j].addEventListener('click', function (evt) {
  283. this.parent.menuPG.removeAllOptions();
  284. this.parent.settingsPG.setFontSize.call(this.parent.settingsPG, evt.target.innerText)
  285. }.bind(this));
  286. }
  287. }
  288. // Footer links
  289. var displayFontSize = document.getElementsByClassName('displayFooterLinks');
  290. for (var i = 0; i < displayFontSize.length; i++) {
  291. var options = displayFontSize[i].querySelectorAll('.option');
  292. for (var j = 0; j < options.length; j++) {
  293. options[j].addEventListener('click', this.parent.menuPG.clickOptionSub.bind(this));
  294. }
  295. }
  296. // Language (JS / TS)
  297. this.parent.utils.setToMultipleID("toTSbutton", "click", function () {
  298. if (location.hash != null && location.hash != "") {
  299. this.parent.settingsPG.ScriptLanguage = "TS";
  300. window.location = "./";
  301. } else {
  302. if (this.parent.settingsPG.ScriptLanguage == "JS") {
  303. //revert in case the reload is cancel due to safe mode
  304. if (document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()).classList.contains('checked')) {
  305. // Message before unload
  306. var languageTSswapper = function () {
  307. this.parent.settingsPG.ScriptLanguage = "TS";
  308. window.removeEventListener('unload', languageTSswapper.bind(this));
  309. };
  310. window.addEventListener('unload', languageTSswapper.bind(this));
  311. location.reload();
  312. } else {
  313. this.parent.settingsPG.ScriptLanguage = "TS";
  314. location.reload();
  315. }
  316. }
  317. }
  318. }.bind(this));
  319. this.parent.utils.setToMultipleID("toJSbutton", "click", function () {
  320. if (location.hash != null && location.hash != "") {
  321. this.parent.settingsPG.ScriptLanguage = "JS";
  322. window.location = "./";
  323. } else {
  324. if (this.parent.settingsPG.ScriptLanguage == "TS") {
  325. //revert in case the reload is cancel due to safe mode
  326. if (document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()).classList.contains('checked')) {
  327. // Message before unload
  328. var LanguageJSswapper = function () {
  329. this.parent.settingsPG.ScriptLanguage = "JS";
  330. window.removeEventListener('unload', LanguageJSswapper.bind(this));
  331. };
  332. window.addEventListener('unload', LanguageJSswapper.bind(this));
  333. location.reload();
  334. } else {
  335. this.parent.settingsPG.ScriptLanguage = "JS";
  336. location.reload();
  337. }
  338. }
  339. }
  340. }.bind(this));
  341. // Safe mode
  342. this.parent.utils.setToMultipleID("safemodeToggle", 'click', function () {
  343. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  344. if (document.getElementById("safemodeToggle1280").classList.contains('checked')) {
  345. this.parent.utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  346. } else {
  347. this.parent.utils.setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square" aria-hidden="true"></i>');
  348. }
  349. }.bind(this));
  350. // Editor
  351. this.parent.utils.setToMultipleID("editorButton", "click", this.toggleEditor.bind(this));
  352. // FullScreen
  353. this.parent.utils.setToMultipleID("fullscreenButton", "click", function () {
  354. this.parent.menuPG.removeAllOptions();
  355. this.parent.menuPG.goFullscreen(engine);
  356. }.bind(this));
  357. // Editor fullScreen
  358. this.parent.utils.setToMultipleID("editorFullscreenButton", "click", function () {
  359. this.parent.menuPG.removeAllOptions();
  360. this.parent.menuPG.editorGoFullscreen.call(this.parent.menuPG)
  361. }.bind(this));
  362. // Format
  363. this.parent.utils.setToMultipleID("formatButton", "click", function () {
  364. this.parent.menuPG.removeAllOptions();
  365. this.parent.monacoCreator.formatCode.call(this.parent.monacoCreator)
  366. }.bind(this));
  367. // Minimap
  368. this.parent.utils.setToMultipleID("minimapToggle", "click", this.parent.monacoCreator.toggleMinimap.bind(this.parent.monacoCreator));
  369. // Inspector
  370. this.parent.utils.setToMultipleID("debugButton", "click", function () {
  371. this.parent.menuPG.removeAllOptions();
  372. this.toggleDebug.call(this);
  373. }.bind(this));
  374. // Metadata
  375. this.parent.utils.setToMultipleID("metadataButton", "click", function () {
  376. this.parent.menuPG.removeAllOptions();
  377. this.parent.menuPG.displayMetadata.call(this.parent.menuPG)
  378. }.bind(this));
  379. // Initialize the metadata form
  380. this.showNoMetadata();
  381. // Restore theme
  382. this.parent.settingsPG.restoreTheme();
  383. // Restore font size
  384. this.parent.settingsPG.restoreFont();
  385. // Restore language
  386. this.parent.settingsPG.setScriptLanguage();
  387. // Check if it's mobile mode. If true, switch to full canvas by default
  388. this.parent.menuPG.resizeBigCanvas();
  389. // HotKeys
  390. document.onkeydown = function (e) {
  391. // Alt+Enter to Run
  392. if (e.altKey && (e.key === 'Enter' || event.which === 13)) {
  393. handleRun();
  394. }
  395. // Ctrl+Shift+S to Download Zip
  396. else if (
  397. (window.navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey) &&
  398. e.shiftKey &&
  399. (e.key === 'S' || event.which === 83)
  400. ) {
  401. handleGetZip();
  402. }
  403. // Ctrl+S to Save
  404. else if (
  405. (window.navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey) &&
  406. (e.key === 'S' || event.which === 83)
  407. ) {
  408. e.preventDefault();
  409. handleSave();
  410. }
  411. };
  412. };
  413. /**
  414. * Check if we're in the correct language for the selected script
  415. * @param {*} xhr
  416. */
  417. checkTypescriptSupport(xhr) {
  418. // If we're loading TS content and it's JS page
  419. if (xhr.responseText.indexOf("class Playground") !== -1) {
  420. if (this.parent.settingsPG.ScriptLanguage == "JS") {
  421. this.parent.settingsPG.ScriptLanguage = "TS";
  422. location.reload();
  423. return false;
  424. }
  425. } else { // If we're loading JS content and it's TS page
  426. if (this.parent.settingsPG.ScriptLanguage == "TS") {
  427. this.parent.settingsPG.ScriptLanguage = "JS";
  428. location.reload();
  429. return false;
  430. }
  431. }
  432. return true;
  433. };
  434. /**
  435. * Load a script in the database
  436. * @param {*} scriptURL
  437. * @param {*} title
  438. */
  439. loadScript(scriptURL, title) {
  440. var xhr = new XMLHttpRequest();
  441. xhr.open('GET', scriptURL, true);
  442. xhr.onreadystatechange = function () {
  443. if (xhr.readyState === 4) {
  444. if (xhr.status === 200) {
  445. if (!this.checkTypescriptSupport(xhr)) return;
  446. xhr.onreadystatechange = null;
  447. this.parent.monacoCreator.BlockEditorChange = true;
  448. this.parent.monacoCreator.JsEditor.setValue(xhr.responseText);
  449. this.parent.monacoCreator.JsEditor.setPosition({
  450. lineNumber: 0,
  451. column: 0
  452. });
  453. this.parent.monacoCreator.BlockEditorChange = false;
  454. compileAndRun(this.parent, this.fpsLabel);
  455. this.currentSnippetToken = null;
  456. }
  457. }
  458. }.bind(this);
  459. xhr.send(null);
  460. };
  461. /**
  462. * Load the examples scripts list in the database
  463. */
  464. loadScriptsList(restoreVersionResult) {
  465. var exampleList = document.getElementById("exampleList");
  466. var xhr = new XMLHttpRequest();
  467. // Open Typescript or Javascript examples
  468. if (exampleList.className != 'typescript') {
  469. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list.json', true);
  470. } else {
  471. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list_ts.json', true);
  472. }
  473. xhr.onreadystatechange = function () {
  474. if (xhr.readyState === 4) {
  475. if (xhr.status === 200) {
  476. this.scripts = JSON.parse(xhr.response)["examples"];
  477. function sortScriptsList(a, b) {
  478. if (a.title < b.title) return -1;
  479. else return 1;
  480. }
  481. this.scripts.sort(sortScriptsList);
  482. if (exampleList) {
  483. for (var i = 0; i < this.scripts.length; i++) {
  484. this.scripts[i].samples.sort(sortScriptsList);
  485. var exampleCategory = document.createElement("div");
  486. exampleCategory.classList.add("categoryContainer");
  487. var exampleCategoryTitle = document.createElement("p");
  488. exampleCategoryTitle.innerText = this.scripts[i].title;
  489. exampleCategory.appendChild(exampleCategoryTitle);
  490. for (var ii = 0; ii < this.scripts[i].samples.length; ii++) {
  491. var example = document.createElement("div");
  492. example.classList.add("itemLine");
  493. example.id = ii;
  494. var exampleImg = document.createElement("img");
  495. exampleImg.setAttribute("data-src", this.scripts[i].samples[ii].icon.replace("icons", "https://doc.babylonjs.com/examples/icons"));
  496. exampleImg.setAttribute("onClick", "document.getElementById('PGLink_" + this.scripts[i].samples[ii].PGID + "').click();");
  497. var exampleContent = document.createElement("div");
  498. exampleContent.classList.add("itemContent");
  499. exampleContent.setAttribute("onClick", "document.getElementById('PGLink_" + this.scripts[i].samples[ii].PGID + "').click();");
  500. var exampleContentLink = document.createElement("div");
  501. exampleContentLink.classList.add("itemContentLink");
  502. var exampleTitle = document.createElement("h3");
  503. exampleTitle.classList.add("exampleCategoryTitle");
  504. exampleTitle.innerText = this.scripts[i].samples[ii].title;
  505. var exampleDescr = document.createElement("div");
  506. exampleDescr.classList.add("itemLineChild");
  507. exampleDescr.innerText = this.scripts[i].samples[ii].description;
  508. var exampleDocLink = document.createElement("a");
  509. exampleDocLink.classList.add("itemLineDocLink");
  510. exampleDocLink.innerText = "Documentation";
  511. exampleDocLink.href = this.scripts[i].samples[ii].doc;
  512. exampleDocLink.target = "_blank";
  513. var examplePGLink = document.createElement("a");
  514. examplePGLink.id = "PGLink_" + this.scripts[i].samples[ii].PGID;
  515. examplePGLink.classList.add("itemLinePGLink");
  516. examplePGLink.innerText = "Display";
  517. examplePGLink.href = this.scripts[i].samples[ii].PGID;
  518. examplePGLink.addEventListener("click", function () {
  519. location.href = this.href;
  520. location.reload();
  521. });
  522. exampleContentLink.appendChild(exampleTitle);
  523. exampleContentLink.appendChild(exampleDescr);
  524. exampleContent.appendChild(exampleContentLink);
  525. exampleContent.appendChild(exampleDocLink);
  526. exampleContent.appendChild(examplePGLink);
  527. example.appendChild(exampleImg);
  528. example.appendChild(exampleContent);
  529. exampleCategory.appendChild(example);
  530. }
  531. exampleList.appendChild(exampleCategory);
  532. }
  533. var noResultContainer = document.createElement("div");
  534. noResultContainer.id = "noResultsContainer";
  535. noResultContainer.classList.add("categoryContainer");
  536. noResultContainer.style.display = "none";
  537. noResultContainer.innerHTML = "<p id='noResults'>No results found.</p>";
  538. exampleList.appendChild(noResultContainer);
  539. }
  540. if (!location.hash && restoreVersionResult == false) {
  541. // Query string
  542. var queryString = window.location.search;
  543. if (queryString) {
  544. var query = queryString.replace("?", "");
  545. index = parseInt(query);
  546. if (!isNaN(index)) {
  547. var newPG = "";
  548. switch (index) {
  549. case 1:
  550. newPG = "#TAZ2CB#0";
  551. break; // Basic scene
  552. case 2:
  553. newPG = "#A1210C#0";
  554. break; // Basic elements
  555. case 3:
  556. newPG = "#CURCZC#0";
  557. break; // Rotation and scaling
  558. case 4:
  559. newPG = "#DXARSP#0";
  560. break; // Materials
  561. case 5:
  562. newPG = "#1A3M5C#0";
  563. break; // Cameras
  564. case 6:
  565. newPG = "#AQRDKW#0";
  566. break; // Lights
  567. case 7:
  568. newPG = "#QYFDDP#1";
  569. break; // Animations
  570. case 8:
  571. newPG = "#9RI8CG#0";
  572. break; // Sprites
  573. case 9:
  574. newPG = "#U8MEB0#0";
  575. break; // Collisions
  576. case 10:
  577. newPG = "#KQV9SA#0";
  578. break; // Intersections
  579. case 11:
  580. newPG = "#NU4F6Y#0";
  581. break; // Picking
  582. case 12:
  583. newPG = "#EF9X5R#0";
  584. break; // Particles
  585. case 13:
  586. newPG = "#7G0IQW#0";
  587. break; // Environment
  588. case 14:
  589. newPG = "#95PXRY#0";
  590. break; // Height map
  591. case 15:
  592. newPG = "#IFYDRS#0";
  593. break; // Shadows
  594. case 16:
  595. newPG = "#AQZJ4C#0";
  596. break; // Import meshes
  597. case 17:
  598. newPG = "#J19GYK#0";
  599. break; // Actions
  600. case 18:
  601. newPG = "#UZ23UH#0";
  602. break; // Drag and drop
  603. case 19:
  604. newPG = "#AQZJ4C#0";
  605. break; // Fresnel
  606. case 20:
  607. newPG = "#8ZNVGR#0";
  608. break; // Easing functions
  609. case 21:
  610. newPG = "#B2ZXG6#0";
  611. break; // Procedural texture
  612. case 22:
  613. newPG = "#DXAEUY#0";
  614. break; // Basic sounds
  615. case 23:
  616. newPG = "#EDVU95#0";
  617. break; // Sound on mesh
  618. case 24:
  619. newPG = "#N96NXC#0";
  620. break; // SSAO rendering pipeline
  621. case 25:
  622. newPG = "#7D2QDD#0";
  623. break; // SSAO 2
  624. case 26:
  625. newPG = "#V2DAKC#0";
  626. break; // Volumetric light scattering
  627. case 27:
  628. newPG = "#XH85A9#0";
  629. break; // Refraction and reflection
  630. case 28:
  631. newPG = "#8MGKWK#0";
  632. break; // PBR
  633. case 29:
  634. newPG = "#0K8EYN#0";
  635. break; // Instanced bones
  636. case 30:
  637. newPG = "#C245A1#0";
  638. break; // Pointer events handling
  639. case 31:
  640. newPG = "#TAFSN0#2";
  641. break; // WebVR
  642. case 32:
  643. newPG = "#3VMTI9#0";
  644. break; // GUI
  645. case 33:
  646. newPG = "#7149G4#0";
  647. break; // Physics
  648. default:
  649. newPG = "";
  650. break;
  651. }
  652. window.location.href = location.protocol + "//" + location.host + location.pathname + "#" + newPG;
  653. } else if (query.indexOf("=") === -1) {
  654. this.loadScript("scripts/" + query + ".js", query);
  655. } else if (query.indexOf('pg=') === -1 && !location.pathname.match(/\/pg\//)) {
  656. this.loadScript(this.parent.settingsPG.DefaultScene, "Basic scene");
  657. }
  658. } else if (!location.pathname.match(/\/pg\//)) {
  659. this.loadScript(this.parent.settingsPG.DefaultScene, "Basic scene");
  660. }
  661. }
  662. // Restore language
  663. this.parent.settingsPG.setScriptLanguage();
  664. }
  665. }
  666. }.bind(this);
  667. xhr.send(null);
  668. };
  669. createNewScript() {
  670. // Check if safe mode is on, and ask if it is
  671. if (!this.checkSafeMode("Are you sure you want to create a new playground?")) return;
  672. location.hash = "";
  673. this.currentSnippetToken = null;
  674. this.currentSnippetTitle = null;
  675. this.currentSnippetDescription = null;
  676. this.currentSnippetTags = null;
  677. this.showNoMetadata();
  678. if (this.parent.monacoCreator.monacoMode === "javascript") {
  679. 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};');
  680. } else {
  681. 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}');
  682. }
  683. this.parent.monacoCreator.JsEditor.setPosition({
  684. lineNumber: 11,
  685. column: 0
  686. });
  687. this.parent.monacoCreator.JsEditor.focus();
  688. compileAndRun(this.parent, this.fpsLabel);
  689. };
  690. clear() {
  691. // Check if safe mode is on, and ask if it is
  692. if (!this.checkSafeMode("Are you sure you want to clear the playground?")) return;
  693. location.hash = "";
  694. this.currentSnippetToken = null;
  695. this.parent.monacoCreator.JsEditor.setValue('');
  696. this.parent.monacoCreator.JsEditor.setPosition({
  697. lineNumber: 0,
  698. column: 0
  699. });
  700. this.parent.monacoCreator.JsEditor.focus();
  701. };
  702. compileAndRunFromOutside() {
  703. compileAndRun(this.parent, this.fpsLabel);
  704. };
  705. checkSafeMode(message) {
  706. if (document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()) &&
  707. document.getElementById("safemodeToggle" + this.parent.utils.getCurrentSize()).classList.contains('checked')) {
  708. let confirm = window.confirm(message);
  709. if (!confirm) {
  710. return false;
  711. } else {
  712. for (var i = 0; i < this.parent.utils.multipleSize.length; i++) {
  713. document.getElementById("safemodeToggle" + this.parent.utils.multipleSize[i]).classList.toggle('checked');
  714. }
  715. return true;
  716. }
  717. } else {
  718. return true;
  719. }
  720. };
  721. /**
  722. * Metadatas form
  723. */
  724. showNoMetadata() {
  725. if (this.currentSnippetTitle) {
  726. document.getElementById("saveFormTitle").value = this.currentSnippetTitle;
  727. document.getElementById("saveFormTitle").readOnly = true;
  728. } else {
  729. document.getElementById("saveFormTitle").value = '';
  730. document.getElementById("saveFormTitle").readOnly = false;
  731. }
  732. if (this.currentSnippetDescription) {
  733. document.getElementById("saveFormDescription").value = this.currentSnippetDescription;
  734. document.getElementById("saveFormDescription").readOnly = true;
  735. } else {
  736. document.getElementById("saveFormDescription").value = '';
  737. document.getElementById("saveFormDescription").readOnly = false;
  738. }
  739. if (this.currentSnippetTags) {
  740. document.getElementById("saveFormTags").value = this.currentSnippetTags;
  741. document.getElementById("saveFormTags").readOnly = true;
  742. } else {
  743. document.getElementById("saveFormTags").value = '';
  744. document.getElementById("saveFormTags").readOnly = false;
  745. }
  746. document.getElementById("saveFormButtons").style.display = "block";
  747. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  748. };
  749. hideNoMetadata() {
  750. document.getElementById("saveFormTitle").readOnly = true;
  751. document.getElementById("saveFormDescription").readOnly = true;
  752. document.getElementById("saveFormTags").readOnly = true;
  753. document.getElementById("saveFormButtonOk").style.display = "none";
  754. };
  755. /*
  756. * Metadatas save
  757. */
  758. save() {
  759. // Retrieve title if necessary
  760. if (document.getElementById("saveLayer")) {
  761. this.currentSnippetTitle = document.getElementById("saveFormTitle").value;
  762. this.currentSnippetDescription = document.getElementById("saveFormDescription").value;
  763. this.currentSnippetTags = document.getElementById("saveFormTags").value;
  764. }
  765. this.updateMetadata();
  766. var xmlHttp = new XMLHttpRequest();
  767. xmlHttp.onreadystatechange = function () {
  768. if (xmlHttp.readyState === 4) {
  769. if (xmlHttp.status === 200) {
  770. var snippet = JSON.parse(xmlHttp.responseText);
  771. if (location.pathname && location.pathname.indexOf('pg/') !== -1) {
  772. // full path with /pg/??????
  773. if (location.pathname.indexOf('revision') !== -1) {
  774. location.href = location.href.replace(/revision\/(\d+)/, "revision/" + snippet.version);
  775. } else {
  776. location.href = location.href + '/revision/' + snippet.version;
  777. }
  778. } else if (location.search && location.search.indexOf('pg=') !== -1) {
  779. // query string with ?pg=??????
  780. const currentQuery = this.parseQuery(location.search);
  781. if (currentQuery.revision) {
  782. location.href = location.href.replace(/revision=(\d+)/, "revision=" + snippet.version);
  783. } else {
  784. location.href = location.href + '&revision=' + snippet.version;
  785. }
  786. } else {
  787. // default behavior!
  788. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  789. var newUrl = baseUrl + "#" + snippet.id;
  790. this.currentSnippetToken = snippet.id;
  791. if (snippet.version && snippet.version !== "0") {
  792. newUrl += "#" + snippet.version;
  793. }
  794. location.href = newUrl;
  795. // Hide the complete title & co message
  796. this.hideNoMetadata();
  797. compileAndRun(this.parent, this.fpsLabel);
  798. }
  799. } else {
  800. this.parent.utils.showError("Unable to save your code. It may be too long.", null);
  801. }
  802. }
  803. }.bind(this);
  804. xmlHttp.open("POST", this.snippetV3Url + (this.currentSnippetToken ? "/" + this.currentSnippetToken : ""), true);
  805. xmlHttp.setRequestHeader("Content-Type", "application/json");
  806. var dataToSend = {
  807. payload: JSON.stringify({
  808. code: this.parent.monacoCreator.JsEditor.getValue()
  809. }),
  810. name: this.currentSnippetTitle,
  811. description: this.currentSnippetDescription,
  812. tags: this.currentSnippetTags
  813. };
  814. xmlHttp.send(JSON.stringify(dataToSend));
  815. };
  816. askForSave() {
  817. if (this.currentSnippetTitle == null ||
  818. this.currentSnippetDescription == null ||
  819. this.currentSnippetTags == null) {
  820. document.getElementById("saveLayer").style.display = "block";
  821. } else {
  822. this.save();
  823. }
  824. };
  825. askForDiff() {
  826. const diffLayer = document.getElementById("diffLayer");
  827. const right = document.getElementById("diffFormCompareTo");
  828. if (this.previousHash && right.value === "") {
  829. // Use the previous snippet hash for right comparison, if present
  830. right.value = this.previousHash;
  831. }
  832. diffLayer.style.display = "block";
  833. }
  834. async loadSnippetCode(snippetid) {
  835. if (!snippetid || snippetid === "")
  836. return "";
  837. let response = await fetch(`${this.snippetV3Url}/${snippetid.replace(/#/g, "/")}`);
  838. if (!response.ok)
  839. throw new Error(`Unable to load snippet ${snippetid}`)
  840. let result = await response.json();
  841. return JSON.parse(result.jsonPayload).code.toString();
  842. }
  843. async getSnippetCode(value) {
  844. if (!value || value === "") {
  845. // use current snippet
  846. return this.parent.monacoCreator.JsEditor.getValue();
  847. } else {
  848. // load script
  849. return await this.loadSnippetCode(value);
  850. }
  851. }
  852. async diff() {
  853. try {
  854. const leftText = await this.getSnippetCode(document.getElementById("diffFormSource").value);
  855. const rightText = await this.getSnippetCode(document.getElementById("diffFormCompareTo").value);
  856. this.toggleDiffEditor(this.parent.monacoCreator, this.parent.menuPG, leftText, rightText);
  857. } catch (e) {
  858. // only pass the message, we don't want to inspect the stacktrace in this case
  859. this.parent.utils.showError(e.message, null);
  860. }
  861. }
  862. toggleDiffEditor(monacoCreator, menuPG, leftText, rightText) {
  863. const diffView = document.getElementById("diffView");
  864. if (leftText && rightText) {
  865. menuPG.resizeForDiff();
  866. diffView.style.display = "block";
  867. monacoCreator.createDiff(leftText, rightText, diffView);
  868. } else {
  869. monacoCreator.disposeDiff();
  870. diffView.style.display = "none";
  871. if (menuPG.isMobileVersion) {
  872. menuPG.resizeBigJsEditor();
  873. } else {
  874. menuPG.resizeSplitted();
  875. }
  876. }
  877. }
  878. navigateToPrevious() {
  879. var dn = this.parent.monacoCreator.diffNavigator;
  880. if (!dn)
  881. return;
  882. if (dn.canNavigate())
  883. dn.previous();
  884. }
  885. navigateToNext() {
  886. var dn = this.parent.monacoCreator.diffNavigator;
  887. if (!dn)
  888. return;
  889. if (dn.canNavigate())
  890. dn.next();
  891. }
  892. /**
  893. * Toggle the code editor
  894. */
  895. toggleEditor() {
  896. var editorButton = document.getElementById("editorButton1280");
  897. var scene = engine.scenes[0];
  898. // If the editor is present
  899. if (editorButton.classList.contains('checked')) {
  900. this.parent.utils.setToMultipleID("editorButton", "removeClass", 'checked');
  901. this.parent.splitInstance.collapse(0);
  902. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square" aria-hidden="true"></i>');
  903. } else {
  904. this.parent.utils.setToMultipleID("editorButton", "addClass", 'checked');
  905. this.parent.splitInstance.setSizes([50, 50]); // Reset
  906. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  907. }
  908. engine.resize();
  909. if (scene.debugLayer.isVisible()) {
  910. scene.debugLayer.show({
  911. embedMode: true
  912. });
  913. }
  914. };
  915. /**
  916. * Toggle the BJS debug layer
  917. */
  918. toggleDebug() {
  919. // Always showing the debug layer, because you can close it by itself
  920. var scene = engine.scenes[0];
  921. if (scene.debugLayer.isVisible()) {
  922. scene.debugLayer.hide();
  923. } else {
  924. scene.debugLayer.show({
  925. embedMode: true
  926. });
  927. }
  928. };
  929. /**
  930. * HASH part
  931. */
  932. cleanHash() {
  933. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  934. if (splits.length > 2) {
  935. splits.splice(2, splits.length - 2);
  936. }
  937. location.hash = splits.join("#");
  938. };
  939. checkHash() {
  940. let pgHash = "";
  941. if (location.search) {
  942. var query = this.parseQuery(location.search);
  943. if (query.pg) {
  944. pgHash = "#" + query.pg + "#" + (query.revision || "0")
  945. }
  946. } else if (location.hash) {
  947. if (this.previousHash !== location.hash) {
  948. pgHash = location.hash;
  949. }
  950. } else if (location.pathname) {
  951. const pgMatch = location.pathname.match(/\/pg\/(.*)/);
  952. const withRevision = location.pathname.match(/\/pg\/(.*)\/revision\/(\d*)/);
  953. if (pgMatch || withRevision) {
  954. if (withRevision) {
  955. pgHash = "#" + withRevision[1] + "#" + withRevision[2];
  956. } else {
  957. pgHash = "#" + pgMatch[1] + "#0";
  958. }
  959. }
  960. }
  961. if (pgHash) {
  962. var match = pgHash.match(/^(#[A-Z\d]*)(%23)([\d]+)$/);
  963. if (match){
  964. pgHash = match[1]+'#'+match[3];
  965. parent.location.hash = pgHash;
  966. }
  967. this.previousHash = pgHash;
  968. this.loadPlayground(pgHash.substr(1))
  969. }
  970. window.addEventListener("hashchange", this.checkHash.bind(this));
  971. };
  972. loadPlayground(id) {
  973. try {
  974. var xmlHttp = new XMLHttpRequest();
  975. xmlHttp.onreadystatechange = function () {
  976. if (xmlHttp.readyState === 4) {
  977. if (xmlHttp.status === 200) {
  978. if (!this.checkTypescriptSupport(xmlHttp)) {
  979. return;
  980. }
  981. var snippet = JSON.parse(xmlHttp.responseText);
  982. this.parent.monacoCreator.BlockEditorChange = true;
  983. this.parent.monacoCreator.JsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  984. // Check if title / descr / tags are already set
  985. if (snippet.name != null && snippet.name != "") {
  986. this.currentSnippetTitle = snippet.name;
  987. } else this.currentSnippetTitle = null;
  988. if (snippet.description != null && snippet.description != "") {
  989. this.currentSnippetDescription = snippet.description;
  990. } else this.currentSnippetDescription = null;
  991. if (snippet.tags != null && snippet.tags != "") {
  992. this.currentSnippetTags = snippet.tags;
  993. } else this.currentSnippetTags = null;
  994. if (this.currentSnippetTitle != null && this.currentSnippetTags != null && this.currentSnippetDescription) {
  995. if (document.getElementById("saveLayer")) {
  996. document.getElementById("saveFormTitle").value = this.currentSnippetTitle;
  997. document.getElementById("saveFormDescription").value = this.currentSnippetDescription;
  998. document.getElementById("saveFormTags").value = this.currentSnippetTags;
  999. this.hideNoMetadata();
  1000. }
  1001. } else {
  1002. this.showNoMetadata();
  1003. }
  1004. this.updateMetadata();
  1005. this.parent.monacoCreator.JsEditor.setPosition({
  1006. lineNumber: 0,
  1007. column: 0
  1008. });
  1009. this.parent.monacoCreator.BlockEditorChange = false;
  1010. compileAndRun(this.parent, this.fpsLabel);
  1011. }
  1012. }
  1013. }.bind(this);
  1014. this.currentSnippetToken = id.split("#")[0];
  1015. if (!id.split("#")[1]) id += "#0";
  1016. xmlHttp.open("GET", this.snippetV3Url + "/" + id.replace("#", "/"));
  1017. xmlHttp.send();
  1018. } catch (e) {
  1019. }
  1020. }
  1021. updateMetadata() {
  1022. var selection;
  1023. if (this.currentSnippetTitle) {
  1024. selection = document.querySelector('title');
  1025. if(selection){
  1026. selection.innerText = (this.currentSnippetTitle + " | Babylon.js Playground");
  1027. }
  1028. }
  1029. if (this.currentSnippetDescription) {
  1030. selection = document.querySelector('meta[name="description"]');
  1031. if(selection){
  1032. selection.setAttribute("content", this.currentSnippetDescription + " - Babylon.js Playground");
  1033. }
  1034. }
  1035. if (this.currentSnippetTags) {
  1036. selection = document.querySelector('meta[name="keywords"]');
  1037. if(selection){
  1038. selection.setAttribute("content", "babylon.js, game engine, webgl, 3d," + this.currentSnippetTags);
  1039. }
  1040. }
  1041. }
  1042. parseQuery(queryString) {
  1043. var query = {};
  1044. var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
  1045. for (var i = 0; i < pairs.length; i++) {
  1046. var pair = pairs[i].split('=');
  1047. query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
  1048. }
  1049. return query;
  1050. }
  1051. }