main.js 50 KB

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