main.js 49 KB

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