main.js 45 KB

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