main.js 50 KB

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