main.js 52 KB

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