main.js 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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 baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  771. var snippet = JSON.parse(xmlHttp.responseText);
  772. var newUrl = baseUrl + "#" + snippet.id;
  773. this.currentSnippetToken = snippet.id;
  774. if (snippet.version && snippet.version !== "0") {
  775. newUrl += "#" + snippet.version;
  776. }
  777. location.href = newUrl;
  778. // Hide the complete title & co message
  779. this.hideNoMetadata();
  780. compileAndRun(this.parent, this.fpsLabel);
  781. } else {
  782. this.parent.utils.showError("Unable to save your code. It may be too long.", null);
  783. }
  784. }
  785. }.bind(this);
  786. xmlHttp.open("POST", this.snippetV3Url + (this.currentSnippetToken ? "/" + this.currentSnippetToken : ""), true);
  787. xmlHttp.setRequestHeader("Content-Type", "application/json");
  788. var dataToSend = {
  789. payload: JSON.stringify({
  790. code: this.parent.monacoCreator.JsEditor.getValue()
  791. }),
  792. name: this.currentSnippetTitle,
  793. description: this.currentSnippetDescription,
  794. tags: this.currentSnippetTags
  795. };
  796. xmlHttp.send(JSON.stringify(dataToSend));
  797. };
  798. askForSave() {
  799. if (this.currentSnippetTitle == null ||
  800. this.currentSnippetDescription == null ||
  801. this.currentSnippetTags == null) {
  802. document.getElementById("saveLayer").style.display = "block";
  803. } else {
  804. this.save();
  805. }
  806. };
  807. askForDiff() {
  808. const diffLayer = document.getElementById("diffLayer");
  809. const right = document.getElementById("diffFormCompareTo");
  810. if (this.previousHash && right.value === "") {
  811. // Use the previous snippet hash for right comparison, if present
  812. right.value = this.previousHash;
  813. }
  814. diffLayer.style.display = "block";
  815. }
  816. async loadSnippetCode(snippetid) {
  817. if (!snippetid || snippetid === "")
  818. return "";
  819. let response = await fetch(`${this.snippetV3Url}/${snippetid.replace(/#/g, "/")}`);
  820. if (!response.ok)
  821. throw new Error(`Unable to load snippet ${snippetid}`)
  822. let result = await response.json();
  823. return JSON.parse(result.jsonPayload).code.toString();
  824. }
  825. async getSnippetCode(value) {
  826. if (!value || value === "") {
  827. // use current snippet
  828. return this.parent.monacoCreator.JsEditor.getValue();
  829. } else {
  830. // load script
  831. return await this.loadSnippetCode(value);
  832. }
  833. }
  834. async diff() {
  835. try {
  836. const leftText = await this.getSnippetCode(document.getElementById("diffFormSource").value);
  837. const rightText = await this.getSnippetCode(document.getElementById("diffFormCompareTo").value);
  838. this.toggleDiffEditor(this.parent.monacoCreator, this.parent.menuPG, leftText, rightText);
  839. } catch (e) {
  840. // only pass the message, we don't want to inspect the stacktrace in this case
  841. this.parent.utils.showError(e.message, null);
  842. }
  843. }
  844. toggleDiffEditor(monacoCreator, menuPG, leftText, rightText) {
  845. const diffView = document.getElementById("diffView");
  846. if (leftText && rightText) {
  847. menuPG.resizeForDiff();
  848. diffView.style.display = "block";
  849. monacoCreator.createDiff(leftText, rightText, diffView);
  850. } else {
  851. monacoCreator.disposeDiff();
  852. diffView.style.display = "none";
  853. if (menuPG.isMobileVersion) {
  854. menuPG.resizeBigJsEditor();
  855. } else {
  856. menuPG.resizeSplitted();
  857. }
  858. }
  859. }
  860. navigateToPrevious() {
  861. var dn = this.parent.monacoCreator.diffNavigator;
  862. if (!dn)
  863. return;
  864. if (dn.canNavigate())
  865. dn.previous();
  866. }
  867. navigateToNext() {
  868. var dn = this.parent.monacoCreator.diffNavigator;
  869. if (!dn)
  870. return;
  871. if (dn.canNavigate())
  872. dn.next();
  873. }
  874. /**
  875. * Toggle the code editor
  876. */
  877. toggleEditor() {
  878. var editorButton = document.getElementById("editorButton1280");
  879. var scene = engine.scenes[0];
  880. // If the editor is present
  881. if (editorButton.classList.contains('checked')) {
  882. this.parent.utils.setToMultipleID("editorButton", "removeClass", 'checked');
  883. this.parent.splitInstance.collapse(0);
  884. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square" aria-hidden="true"></i>');
  885. } else {
  886. this.parent.utils.setToMultipleID("editorButton", "addClass", 'checked');
  887. this.parent.splitInstance.setSizes([50, 50]); // Reset
  888. this.parent.utils.setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  889. }
  890. engine.resize();
  891. if (scene.debugLayer.isVisible()) {
  892. scene.debugLayer.show({
  893. embedMode: true
  894. });
  895. }
  896. };
  897. /**
  898. * Toggle the BJS debug layer
  899. */
  900. toggleDebug() {
  901. // Always showing the debug layer, because you can close it by itself
  902. var scene = engine.scenes[0];
  903. if (scene.debugLayer.isVisible()) {
  904. scene.debugLayer.hide();
  905. } else {
  906. scene.debugLayer.show({
  907. embedMode: true
  908. });
  909. }
  910. };
  911. /**
  912. * HASH part
  913. */
  914. cleanHash() {
  915. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  916. if (splits.length > 2) {
  917. splits.splice(2, splits.length - 2);
  918. }
  919. location.hash = splits.join("#");
  920. };
  921. checkHash() {
  922. let pgHash = "";
  923. if (location.search) {
  924. var query = this.parseQuery(location.search);
  925. if (query.pg) {
  926. pgHash = "#" + query.pg + "#" + (query.revision || "0")
  927. }
  928. } else if (location.hash) {
  929. if (this.previousHash !== location.hash) {
  930. pgHash = location.hash;
  931. }
  932. } else if (location.pathname) {
  933. const pgMatch = location.pathname.match(/\/pg\/(.*)/);
  934. const withRevision = location.pathname.match(/\/pg\/(.*)\/revision\/(\d*)/);
  935. if (pgMatch || withRevision) {
  936. if (withRevision) {
  937. pgHash = "#" + withRevision[1] + "#" + withRevision[2];
  938. } else {
  939. pgHash = "#" + pgMatch[1] + "#0";
  940. }
  941. }
  942. }
  943. if (pgHash) {
  944. this.previousHash = pgHash;
  945. this.loadPlayground(pgHash.substr(1))
  946. }
  947. window.addEventListener("hashchange", this.checkHash.bind(this));
  948. };
  949. loadPlayground(id) {
  950. try {
  951. var xmlHttp = new XMLHttpRequest();
  952. xmlHttp.onreadystatechange = function () {
  953. if (xmlHttp.readyState === 4) {
  954. if (xmlHttp.status === 200) {
  955. if (!this.checkTypescriptSupport(xmlHttp)) {
  956. return;
  957. }
  958. var snippet = JSON.parse(xmlHttp.responseText);
  959. this.parent.monacoCreator.BlockEditorChange = true;
  960. this.parent.monacoCreator.JsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  961. // Check if title / descr / tags are already set
  962. if (snippet.name != null && snippet.name != "") {
  963. this.currentSnippetTitle = snippet.name;
  964. } else this.currentSnippetTitle = null;
  965. if (snippet.description != null && snippet.description != "") {
  966. this.currentSnippetDescription = snippet.description;
  967. } else this.currentSnippetDescription = null;
  968. if (snippet.tags != null && snippet.tags != "") {
  969. this.currentSnippetTags = snippet.tags;
  970. } else this.currentSnippetTags = null;
  971. if (this.currentSnippetTitle != null && this.currentSnippetTags != null && this.currentSnippetDescription) {
  972. if (document.getElementById("saveLayer")) {
  973. document.getElementById("saveFormTitle").value = this.currentSnippetTitle;
  974. document.getElementById("saveFormDescription").value = this.currentSnippetDescription;
  975. document.getElementById("saveFormTags").value = this.currentSnippetTags;
  976. this.hideNoMetadata();
  977. }
  978. } else {
  979. this.showNoMetadata();
  980. }
  981. this.updateMetadata();
  982. this.parent.monacoCreator.JsEditor.setPosition({
  983. lineNumber: 0,
  984. column: 0
  985. });
  986. this.parent.monacoCreator.BlockEditorChange = false;
  987. compileAndRun(this.parent, this.fpsLabel);
  988. }
  989. }
  990. }.bind(this);
  991. this.currentSnippetToken = id.split("#")[0];
  992. if (!id.split("#")[1]) id += "#0";
  993. xmlHttp.open("GET", this.snippetV3Url + "/" + id.replace("#", "/"));
  994. xmlHttp.send();
  995. } catch (e) {
  996. }
  997. }
  998. updateMetadata() {
  999. if (this.currentSnippetTitle) {
  1000. document.querySelector('title').innerText = (this.currentSnippetTitle + " | Babylon.js Playground");
  1001. }
  1002. if (this.currentSnippetDescription) {
  1003. document.querySelector('meta[name="description"]').setAttribute("content", this.currentSnippetDescription + " - Babylon.js Playground");
  1004. }
  1005. if (this.currentSnippetTags) {
  1006. document.querySelector('meta[name="keywords"]').setAttribute("content", "babylon.js, game engine, webgl, 3d," + this.currentSnippetTags);
  1007. }
  1008. }
  1009. parseQuery(queryString) {
  1010. var query = {};
  1011. var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
  1012. for (var i = 0; i < pairs.length; i++) {
  1013. var pair = pairs[i].split('=');
  1014. query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
  1015. }
  1016. return query;
  1017. }
  1018. }