index.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. examples = new Examples();
  2. utils = new Utils();
  3. monacoCreator = new MonacoCreator();
  4. settingsPG = new SettingsPG(monacoCreator);
  5. menuPG = new MenuPG();
  6. /**
  7. * Apply things to the differents menu sizes
  8. */
  9. var multipleSize = [1280, 1024, 'Mobile'];
  10. var setToMultipleID = function (id, thingToDo, param) {
  11. multipleSize.forEach(function (size) {
  12. if (thingToDo == "innerHTML") {
  13. document.getElementById(id + size).innerHTML = param
  14. }
  15. else if (thingToDo == "click") {
  16. if (param.length > 1) {
  17. for (var i = 0; i < param.length; i++) {
  18. document.getElementById(id + size).addEventListener("click", param[i]);
  19. }
  20. }
  21. else
  22. document.getElementById(id + size).addEventListener("click", param);
  23. }
  24. else if (thingToDo == "addClass") {
  25. document.getElementById(id + size).classList.add(param);
  26. }
  27. else if (thingToDo == "removeClass") {
  28. document.getElementById(id + size).classList.remove(param);
  29. }
  30. else if (thingToDo == "display") {
  31. document.getElementById(id + size).style.display = param;
  32. }
  33. });
  34. };
  35. /**
  36. * View split
  37. */
  38. var splitInstance = Split(['#jsEditor', '#canvasZone']);
  39. /**
  40. * Language of the script
  41. */
  42. if (settingsPG.scriptLanguage == "TS") {
  43. var compilerTriggerTimeoutID;
  44. function triggerCompile(d, func) {
  45. if (compilerTriggerTimeoutID !== null) {
  46. window.clearTimeout(compilerTriggerTimeoutID);
  47. }
  48. compilerTriggerTimeoutID = window.setTimeout(function () {
  49. try {
  50. var output = transpileModule(d, {
  51. module: ts.ModuleKind.AMD,
  52. target: ts.ScriptTarget.ES5,
  53. noLib: true,
  54. noResolve: true,
  55. suppressOutputPathCheck: true
  56. });
  57. if (typeof output === "string") {
  58. func(output);
  59. }
  60. }
  61. catch (e) {
  62. utils.showError(e.message, e);
  63. }
  64. }, 100);
  65. }
  66. function transpileModule(input, options) {
  67. var inputFileName = options.jsx ? "module.tsx" : "module.ts";
  68. var sourceFile = ts.createSourceFile(inputFileName, input, options.target || ts.ScriptTarget.ES5);
  69. // Output
  70. var outputText;
  71. var program = ts.createProgram([inputFileName], options, {
  72. getSourceFile: function (fileName) { return fileName.indexOf("module") === 0 ? sourceFile : undefined; },
  73. writeFile: function (_name, text) { outputText = text; },
  74. getDefaultLibFileName: function () { return "lib.d.ts"; },
  75. useCaseSensitiveFileNames: function () { return false; },
  76. getCanonicalFileName: function (fileName) { return fileName; },
  77. getCurrentDirectory: function () { return ""; },
  78. getNewLine: function () { return "\r\n"; },
  79. fileExists: function (fileName) { return fileName === inputFileName; },
  80. readFile: function () { return ""; },
  81. directoryExists: function () { return true; },
  82. getDirectories: function () { return []; }
  83. });
  84. // Emit
  85. program.emit();
  86. if (outputText === undefined) {
  87. throw new Error("Output generation failed");
  88. }
  89. return outputText;
  90. }
  91. function getRunCode(callBack) {
  92. triggerCompile(monacoCreator.JsEditor.getValue(), function (result) {
  93. callBack(result + "var createScene = function() { return Playground.CreateScene(engine, engine.getRenderingCanvas()); }")
  94. });
  95. }
  96. }
  97. function getRunCode(callBack) {
  98. var code = monacoCreator.JsEditor.getValue();
  99. callBack(code);
  100. }
  101. var run = function () {
  102. var snippetV3Url = "https://snippet.babylonjs.com"
  103. var currentSnippetToken;
  104. var currentSnippetTitle = null;
  105. var currentSnippetDescription = null;
  106. var currentSnippetTags = null;
  107. var engine;
  108. var fpsLabel = document.getElementById("fpsLabel");
  109. var scripts;
  110. var zipCode;
  111. BABYLON.Engine.ShadersRepository = "/src/Shaders/";
  112. // TO DO : Rewrite this with unpkg.com
  113. if (location.href.indexOf("indexStable") !== -1) {
  114. setToMultipleID("currentVersion", "innerHTML", "v.3.0");
  115. } else {
  116. setToMultipleID("currentVersion", "innerHTML", "v.4.0");
  117. }
  118. var checkTypescriptSupport = function (xhr) {
  119. // If we're loading TS content and it's JS page
  120. if (xhr.responseText.indexOf("class Playground") !== -1) {
  121. if (settingsPG.ScriptLanguage == "JS") {
  122. settingsPG.ScriptLanguage = "TS";
  123. location.reload();
  124. return false;
  125. }
  126. } else { // If we're loading JS content and it's TS page
  127. if (settingsPG.ScriptLanguage == "TS") {
  128. settingsPG.ScriptLanguage = "JS";
  129. location.reload();
  130. return false;
  131. }
  132. }
  133. return true;
  134. }
  135. var loadScript = function (scriptURL, title) {
  136. var xhr = new XMLHttpRequest();
  137. xhr.open('GET', scriptURL, true);
  138. xhr.onreadystatechange = function () {
  139. if (xhr.readyState === 4) {
  140. if (xhr.status === 200) {
  141. if (!checkTypescriptSupport(xhr)) return;
  142. xhr.onreadystatechange = null;
  143. monacoCreator.BlockEditorChange = true;
  144. monacoCreator.JsEditor.setValue(xhr.responseText);
  145. monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  146. monacoCreator.BlockEditorChange = false;
  147. compileAndRun();
  148. currentSnippetToken = null;
  149. }
  150. }
  151. };
  152. xhr.send(null);
  153. };
  154. var loadScriptsList = function () {
  155. var exampleList = document.getElementById("exampleList");
  156. var xhr = new XMLHttpRequest();
  157. //Open Typescript or Javascript examples
  158. // TO DO - Check why it's always javascript ? Is it hard coded in html page ?
  159. // Should we merge both lists ?
  160. if (exampleList.className != 'typescript') {
  161. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list.json', true);
  162. }
  163. else {
  164. xhr.open('GET', 'https://raw.githubusercontent.com/BabylonJS/Documentation/master/examples/list_ts.json', true);
  165. }
  166. xhr.onreadystatechange = function () {
  167. if (xhr.readyState === 4) {
  168. if (xhr.status === 200) {
  169. scripts = JSON.parse(xhr.response)["examples"];
  170. function sortScriptsList(a, b) {
  171. if (a.title < b.title) return -1;
  172. else return 1;
  173. }
  174. scripts.sort(sortScriptsList);
  175. if (exampleList) {
  176. for (var i = 0; i < scripts.length; i++) {
  177. scripts[i].samples.sort(sortScriptsList);
  178. var exampleCategory = document.createElement("div");
  179. exampleCategory.classList.add("categoryContainer");
  180. var exampleCategoryTitle = document.createElement("p");
  181. exampleCategoryTitle.innerText = scripts[i].title;
  182. exampleCategory.appendChild(exampleCategoryTitle);
  183. for (var ii = 0; ii < scripts[i].samples.length; ii++) {
  184. var example = document.createElement("div");
  185. example.classList.add("itemLine");
  186. example.id = ii;
  187. var exampleImg = document.createElement("img");
  188. exampleImg.src = scripts[i].samples[ii].icon.replace("icons", "https://doc.babylonjs.com/examples/icons");
  189. exampleImg.setAttribute("onClick", "document.getElementById('PGLink_" + scripts[i].samples[ii].PGID + "').click();");
  190. var exampleContent = document.createElement("div");
  191. exampleContent.classList.add("itemContent");
  192. exampleContent.setAttribute("onClick", "document.getElementById('PGLink_" + scripts[i].samples[ii].PGID + "').click();");
  193. var exampleContentLink = document.createElement("div");
  194. exampleContentLink.classList.add("itemContentLink");
  195. var exampleTitle = document.createElement("h3");
  196. exampleTitle.classList.add("exampleCategoryTitle");
  197. exampleTitle.innerText = scripts[i].samples[ii].title;
  198. var exampleDescr = document.createElement("div");
  199. exampleDescr.classList.add("itemLineChild");
  200. exampleDescr.innerText = scripts[i].samples[ii].description;
  201. var exampleDocLink = document.createElement("a");
  202. exampleDocLink.classList.add("itemLineDocLink");
  203. exampleDocLink.innerText = "Documentation";
  204. exampleDocLink.href = scripts[i].samples[ii].doc;
  205. exampleDocLink.target = "_blank";
  206. var examplePGLink = document.createElement("a");
  207. examplePGLink.id = "PGLink_" + scripts[i].samples[ii].PGID;
  208. examplePGLink.classList.add("itemLinePGLink");
  209. examplePGLink.innerText = "Display";
  210. examplePGLink.href = scripts[i].samples[ii].PGID;
  211. exampleContentLink.appendChild(exampleTitle);
  212. exampleContentLink.appendChild(exampleDescr);
  213. exampleContent.appendChild(exampleContentLink);
  214. exampleContent.appendChild(exampleDocLink);
  215. exampleContent.appendChild(examplePGLink);
  216. example.appendChild(exampleImg);
  217. example.appendChild(exampleContent);
  218. exampleCategory.appendChild(example);
  219. }
  220. exampleList.appendChild(exampleCategory);
  221. }
  222. var noResultContainer = document.createElement("div");
  223. noResultContainer.id = "noResultsContainer";
  224. noResultContainer.classList.add("categoryContainer");
  225. noResultContainer.style.display = "none";
  226. noResultContainer.innerHTML = "<p id='noResults'>No results found.</p>";
  227. exampleList.appendChild(noResultContainer);
  228. }
  229. if (!location.hash) {
  230. // Query string
  231. var queryString = window.location.search;
  232. if (queryString) {
  233. var query = queryString.replace("?", "");
  234. index = parseInt(query);
  235. if (!isNaN(index)) {
  236. // TO DO - Should we remove this deprecated code ?
  237. var newPG = "";
  238. switch (index) {
  239. case 1: newPG = "#TAZ2CB#0"; break; // Basic scene
  240. case 2: newPG = "#A1210C#0"; break; // Basic elements
  241. case 3: newPG = "#CURCZC#0"; break; // Rotation and scaling
  242. case 4: newPG = "#DXARSP#0"; break; // Materials
  243. case 5: newPG = "#1A3M5C#0"; break; // Cameras
  244. case 6: newPG = "#AQRDKW#0"; break; // Lights
  245. case 7: newPG = "#QYFDDP#1"; break; // Animations
  246. case 8: newPG = "#9RI8CG#0"; break; // Sprites
  247. case 9: newPG = "#U8MEB0#0"; break; // Collisions
  248. case 10: newPG = "#KQV9SA#0"; break; // Intersections
  249. case 11: newPG = "#NU4F6Y#0"; break; // Picking
  250. case 12: newPG = "#EF9X5R#0"; break; // Particles
  251. case 13: newPG = "#7G0IQW#0"; break; // Environment
  252. case 14: newPG = "#95PXRY#0"; break; // Height map
  253. case 15: newPG = "#IFYDRS#0"; break; // Shadows
  254. case 16: newPG = "#AQZJ4C#0"; break; // Import meshes
  255. case 17: newPG = "#J19GYK#0"; break; // Actions
  256. case 18: newPG = "#UZ23UH#0"; break; // Drag and drop
  257. case 19: newPG = "#AQZJ4C#0"; break; // Fresnel
  258. case 20: newPG = "#8ZNVGR#0"; break; // Easing functions
  259. case 21: newPG = "#B2ZXG6#0"; break; // Procedural texture
  260. case 22: newPG = "#DXAEUY#0"; break; // Basic sounds
  261. case 23: newPG = "#EDVU95#0"; break; // Sound on mesh
  262. case 24: newPG = "#N96NXC#0"; break; // SSAO rendering pipeline
  263. case 25: newPG = "#7D2QDD#0"; break; // SSAO 2
  264. case 26: newPG = "#V2DAKC#0"; break; // Volumetric light scattering
  265. case 27: newPG = "#XH85A9#0"; break; // Refraction and reflection
  266. case 28: newPG = "#8MGKWK#0"; break; // PBR
  267. case 29: newPG = "#0K8EYN#0"; break; // Instanced bones
  268. case 30: newPG = "#C245A1#0"; break; // Pointer events handling
  269. case 31: newPG = "#TAFSN0#2"; break; // WebVR
  270. case 32: newPG = "#3VMTI9#0"; break; // GUI
  271. case 33: newPG = "#7149G4#0"; break; // Physics
  272. default: newPG = ""; break;
  273. }
  274. window.location.href = location.protocol + "//" + location.host + location.pathname + "#" + newPG;
  275. } else if (query.indexOf("=") === -1) {
  276. loadScript("scripts/" + query + ".js", query);
  277. } else {
  278. loadScript(settingsPG.DefaultScene, "Basic scene");
  279. }
  280. } else {
  281. loadScript(settingsPG.DefaultScene, "Basic scene");
  282. }
  283. }
  284. // Restore theme
  285. settingsPG.restoreTheme(monacoCreator);
  286. // Restore language
  287. settingsPG.setScriptLanguage();
  288. // TO DO - Check why this doesn't work.
  289. // // Remove editor if window size is less than 850px
  290. // var removeEditorForSmallScreen = function () {
  291. // if (mq.matches) {
  292. // splitInstance.collapse(0);
  293. // } else {
  294. // splitInstance.setSizes([50, 50]);
  295. // }
  296. // }
  297. // var mq = window.matchMedia("(max-width: 850px)");
  298. // mq.addListener(removeEditorForSmallScreen);
  299. }
  300. }
  301. };
  302. xhr.send(null);
  303. }
  304. var createNewScript = function () {
  305. // check if checked is on
  306. let iCanClear = checkSafeMode("Are you sure you want to create a new playground?");
  307. if (!iCanClear) return;
  308. location.hash = "";
  309. currentSnippetToken = null;
  310. currentSnippetTitle = null;
  311. currentSnippetDescription = null;
  312. currentSnippetTags = null;
  313. showNoMetadata();
  314. if (monacoCreator.monacoMode === "javascript") {
  315. 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};');
  316. } else {
  317. 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}');
  318. }
  319. monacoCreator.JsEditor.setPosition({ lineNumber: 11, column: 0 });
  320. monacoCreator.JsEditor.focus();
  321. compileAndRun();
  322. }
  323. var clear = function () {
  324. // check if checked is on
  325. let iCanClear = checkSafeMode("Are you sure you want to clear the playground?");
  326. if (!iCanClear) return;
  327. location.hash = "";
  328. currentSnippetToken = null;
  329. monacoCreator.JsEditor.setValue('');
  330. monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  331. monacoCreator.JsEditor.focus();
  332. }
  333. // TO DO - Is this really usefull ? Safe mode only available in full HD screen, not for small screen ? Why ?!
  334. var checkSafeMode = function (message) {
  335. var safeToggle = document.getElementById("safemodeToggle1280");
  336. if (safeToggle.classList.contains('checked')) {
  337. let confirm = window.confirm(message);
  338. if (!confirm) {
  339. return false;
  340. } else {
  341. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  342. return true;
  343. }
  344. } else {
  345. return true;
  346. }
  347. }
  348. var showNoMetadata = function () {
  349. if (currentSnippetTitle) {
  350. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  351. document.getElementById("saveFormTitle").readOnly = true;
  352. }
  353. else {
  354. document.getElementById("saveFormTitle").value = '';
  355. document.getElementById("saveFormTitle").readOnly = false;
  356. }
  357. if (currentSnippetDescription) {
  358. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  359. document.getElementById("saveFormDescription").readOnly = true;
  360. }
  361. else {
  362. document.getElementById("saveFormDescription").value = '';
  363. document.getElementById("saveFormDescription").readOnly = false;
  364. }
  365. if (currentSnippetTags) {
  366. document.getElementById("saveFormTags").value = currentSnippetTags;
  367. document.getElementById("saveFormTags").readOnly = true;
  368. }
  369. else {
  370. document.getElementById("saveFormTags").value = '';
  371. document.getElementById("saveFormTags").readOnly = false;
  372. }
  373. document.getElementById("saveFormButtons").style.display = "block";
  374. document.getElementById("saveFormButtonOk").style.display = "inline-block";
  375. };
  376. showNoMetadata();
  377. var hideNoMetadata = function () {
  378. document.getElementById("saveFormTitle").readOnly = true;
  379. document.getElementById("saveFormDescription").readOnly = true;
  380. document.getElementById("saveFormTags").readOnly = true;
  381. document.getElementById("saveFormButtonOk").style.display = "none";
  382. setToMultipleID("metadataButton", "display", "inline-block");
  383. };
  384. compileAndRun = function () {
  385. try {
  386. var waitRing = document.getElementById("waitDiv");
  387. if (waitRing) {
  388. waitRing.style.display = "none";
  389. }
  390. if (!BABYLON.Engine.isSupported()) {
  391. utils.showError("Your browser does not support WebGL. Please, try to update it, or install a compatible one.", null);
  392. return;
  393. }
  394. var showInspector = false;
  395. showBJSPGMenu();
  396. monacoCreator.JsEditor.updateOptions({ readOnly: false });
  397. if (BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.debugLayer.isVisible()) {
  398. showInspector = true;
  399. }
  400. if (engine) {
  401. engine.dispose();
  402. engine = null;
  403. }
  404. var canvas = document.getElementById("renderCanvas");
  405. document.getElementById("errorZone").style.display = 'none';
  406. document.getElementById("errorZone").innerHTML = "";
  407. document.getElementById("statusBar").innerHTML = "Loading assets... Please wait.";
  408. var checkCamera = true;
  409. var checkSceneCount = true;
  410. var createEngineFunction = "createDefaultEngine";
  411. var createSceneFunction;
  412. getRunCode(function (code) {
  413. var createDefaultEngine = function () {
  414. return new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
  415. }
  416. var scene;
  417. var defaultEngineZip = "new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true })";
  418. if (code.indexOf("createEngine") !== -1) {
  419. createEngineFunction = "createEngine";
  420. }
  421. // Check for different typos
  422. if (code.indexOf("delayCreateScene") !== -1) { // createScene
  423. createSceneFunction = "delayCreateScene";
  424. checkCamera = false;
  425. } else if (code.indexOf("createScene") !== -1) { // createScene
  426. createSceneFunction = "createScene";
  427. } else if (code.indexOf("CreateScene") !== -1) { // CreateScene
  428. createSceneFunction = "CreateScene";
  429. } else if (code.indexOf("createscene") !== -1) { // createscene
  430. createSceneFunction = "createscene";
  431. }
  432. if (!createSceneFunction) {
  433. // just pasted code.
  434. engine = createDefaultEngine();
  435. scene = new BABYLON.Scene(engine);
  436. eval("runScript = function(scene, canvas) {" + code + "}");
  437. runScript(scene, canvas);
  438. zipCode = "var engine = " + defaultEngineZip + ";\r\nvar scene = new BABYLON.Scene(engine);\r\n\r\n" + code;
  439. } else {
  440. //execute the code
  441. eval(code);
  442. //create engine
  443. eval("engine = " + createEngineFunction + "()");
  444. if (!engine) {
  445. utils.showError("createEngine function must return an engine.", null);
  446. return;
  447. }
  448. //create scene
  449. eval("scene = " + createSceneFunction + "()");
  450. if (!scene) {
  451. utils.showError(createSceneFunction + " function must return a scene.", null);
  452. return;
  453. }
  454. // if scene returns a promise avoid checks
  455. if (scene.then) {
  456. checkCamera = false;
  457. checkSceneCount = false;
  458. }
  459. var createEngineZip = (createEngineFunction === "createEngine")
  460. ? "createEngine()"
  461. : defaultEngineZip;
  462. zipCode =
  463. code + "\r\n\r\n" +
  464. "var engine = " + createEngineZip + ";\r\n" +
  465. "var scene = " + createSceneFunction + "();";
  466. }
  467. engine.runRenderLoop(function () {
  468. if (engine.scenes.length === 0) {
  469. return;
  470. }
  471. if (canvas.width !== canvas.clientWidth) {
  472. engine.resize();
  473. }
  474. var scene = engine.scenes[0];
  475. if (scene.activeCamera || scene.activeCameras.length > 0) {
  476. scene.render();
  477. }
  478. fpsLabel.innerHTML = engine.getFps().toFixed() + " fps";
  479. });
  480. if (checkSceneCount && engine.scenes.length === 0) {
  481. utils.showError("You must at least create a scene.", null);
  482. return;
  483. }
  484. if (checkCamera && engine.scenes[0].activeCamera == null) {
  485. utils.showError("You must at least create a camera.", null);
  486. return;
  487. } else if (scene.then) {
  488. scene.then(function () {
  489. document.getElementById("statusBar").innerHTML = "";
  490. });
  491. } else {
  492. engine.scenes[0].executeWhenReady(function () {
  493. document.getElementById("statusBar").innerHTML = "";
  494. });
  495. }
  496. if (scene) {
  497. if (showInspector) {
  498. if (scene.then) {
  499. // Handle if scene is a promise
  500. scene.then(function (s) {
  501. if (!s.debugLayer.isVisible()) {
  502. s.debugLayer.show({ embedMode: true });
  503. }
  504. })
  505. } else {
  506. if (!scene.debugLayer.isVisible()) {
  507. scene.debugLayer.show({ embedMode: true });
  508. }
  509. }
  510. }
  511. }
  512. });
  513. } catch (e) {
  514. utils.showError(e.message, e);
  515. // Also log error in console to help debug playgrounds
  516. console.error(e);
  517. }
  518. };
  519. window.addEventListener("resize",
  520. function () {
  521. if (engine) {
  522. engine.resize();
  523. }
  524. });
  525. // Load scripts list
  526. loadScriptsList();
  527. // Zip
  528. var addContentToZip = function (zip, name, url, replace, buffer, then) {
  529. if (url.substring(0, 5) == "data:" || url.substring(0, 5) == "http:" || url.substring(0, 5) == "blob:" || url.substring(0, 6) == "https:") {
  530. then();
  531. return;
  532. }
  533. var xhr = new XMLHttpRequest();
  534. xhr.open('GET', url, true);
  535. if (buffer) {
  536. xhr.responseType = "arraybuffer";
  537. }
  538. xhr.onreadystatechange = function () {
  539. if (xhr.readyState === 4) {
  540. if (xhr.status === 200) {
  541. var text;
  542. if (!buffer) {
  543. if (replace) {
  544. var splits = replace.split("\r\n");
  545. for (var index = 0; index < splits.length; index++) {
  546. splits[index] = " " + splits[index];
  547. }
  548. replace = splits.join("\r\n");
  549. text = xhr.responseText.replace("####INJECT####", replace);
  550. } else {
  551. text = xhr.responseText;
  552. }
  553. }
  554. zip.file(name, buffer ? xhr.response : text);
  555. then();
  556. }
  557. }
  558. };
  559. xhr.send(null);
  560. }
  561. var addTexturesToZip = function (zip, index, textures, folder, then) {
  562. if (index === textures.length || !textures[index].name) {
  563. then();
  564. return;
  565. }
  566. if (textures[index].isRenderTarget || textures[index] instanceof BABYLON.DynamicTexture || textures[index].name.indexOf("data:") !== -1) {
  567. addTexturesToZip(zip, index + 1, textures, folder, then);
  568. return;
  569. }
  570. if (textures[index].isCube) {
  571. if (textures[index].name.indexOf("dds") === -1) {
  572. if (textures[index]._extensions) {
  573. for (var i = 0; i < 6; i++) {
  574. textures.push({ name: textures[index].name + textures[index]._extensions[i] });
  575. }
  576. } else if (textures[index]._files) {
  577. for (var i = 0; i < 6; i++) {
  578. textures.push({ name: textures[index]._files[i] });
  579. }
  580. }
  581. }
  582. else {
  583. textures.push({ name: textures[index].name });
  584. }
  585. addTexturesToZip(zip, index + 1, textures, folder, then);
  586. return;
  587. }
  588. if (folder == null) {
  589. folder = zip.folder("textures");
  590. }
  591. var url;
  592. if (textures[index].video) {
  593. url = textures[index].video.currentSrc;
  594. } else {
  595. // url = textures[index].name;
  596. url = textures[index].url ? textures[index].url : textures[index].name;
  597. }
  598. var name = textures[index].name.replace("textures/", "");
  599. // var name = url.substr(url.lastIndexOf("/") + 1);
  600. if (url != null) {
  601. addContentToZip(folder,
  602. name,
  603. url,
  604. null,
  605. true,
  606. function () {
  607. addTexturesToZip(zip, index + 1, textures, folder, then);
  608. });
  609. }
  610. else {
  611. addTexturesToZip(zip, index + 1, textures, folder, then);
  612. }
  613. }
  614. var addImportedFilesToZip = function (zip, index, importedFiles, folder, then) {
  615. if (index === importedFiles.length) {
  616. then();
  617. return;
  618. }
  619. if (!folder) {
  620. folder = zip.folder("scenes");
  621. }
  622. var url = importedFiles[index];
  623. var name = url.substr(url.lastIndexOf("/") + 1);
  624. addContentToZip(folder,
  625. name,
  626. url,
  627. null,
  628. true,
  629. function () {
  630. addImportedFilesToZip(zip, index + 1, importedFiles, folder, then);
  631. });
  632. }
  633. var getZip = function () {
  634. if (engine.scenes.length === 0) {
  635. return;
  636. }
  637. var zip = new JSZip();
  638. var scene = engine.scenes[0];
  639. var textures = scene.textures;
  640. var importedFiles = scene.importedMeshesFiles;
  641. document.getElementById("statusBar").innerHTML = "Creating archive... Please wait.";
  642. if (zipCode.indexOf("textures/worldHeightMap.jpg") !== -1) {
  643. textures.push({ name: "textures/worldHeightMap.jpg" });
  644. }
  645. addContentToZip(zip,
  646. "index.html",
  647. "zipContent/index.html",
  648. zipCode,
  649. false,
  650. function () {
  651. addTexturesToZip(zip,
  652. 0,
  653. textures,
  654. null,
  655. function () {
  656. addImportedFilesToZip(zip,
  657. 0,
  658. importedFiles,
  659. null,
  660. function () {
  661. var blob = zip.generate({ type: "blob" });
  662. saveAs(blob, "sample.zip");
  663. document.getElementById("statusBar").innerHTML = "";
  664. });
  665. });
  666. });
  667. }
  668. // Versions
  669. // TO DO - Rewrite that
  670. setVersion = function (version) {
  671. // switch (version) {
  672. // case "stable":
  673. // location.href = "indexStable.html" + location.hash;
  674. // break;
  675. // default:
  676. // location.href = "index.html" + location.hash;
  677. // break;
  678. // }
  679. }
  680. // TO DO - Make it work on small screens and mobile
  681. showQRCode = function () {
  682. $("#qrCodeImage").empty();
  683. var playgroundCode = window.location.href.split("#");
  684. playgroundCode.shift();
  685. $("#qrCodeImage").qrcode({ text: "https://playground.babylonjs.com/frame.html#" + (playgroundCode.join("#")) });
  686. };
  687. // Fullscreen
  688. document.getElementById("renderCanvas").addEventListener("webkitfullscreenchange", function () {
  689. if (document.webkitIsFullScreen) goFullPage();
  690. else exitFullPage();
  691. }, false);
  692. var goFullPage = function () {
  693. var canvasElement = document.getElementById("renderCanvas");
  694. canvasElement.style.position = "absolute";
  695. canvasElement.style.top = 0;
  696. canvasElement.style.left = 0;
  697. canvasElement.style.zIndex = 100;
  698. }
  699. var exitFullPage = function () {
  700. document.getElementById("renderCanvas").style.position = "relative";
  701. document.getElementById("renderCanvas").style.zIndex = 0;
  702. }
  703. var goFullscreen = function () {
  704. if (engine) {
  705. engine.switchFullscreen(true);
  706. }
  707. }
  708. var editorGoFullscreen = function () {
  709. var editorDiv = document.getElementById("jsEditor");
  710. if (editorDiv.requestFullscreen) {
  711. editorDiv.requestFullscreen();
  712. } else if (editorDiv.mozRequestFullScreen) {
  713. editorDiv.mozRequestFullScreen();
  714. } else if (editorDiv.webkitRequestFullscreen) {
  715. editorDiv.webkitRequestFullscreen();
  716. }
  717. }
  718. var toggleEditor = function () {
  719. var editorButton = document.getElementById("editorButton1280");
  720. var scene = engine.scenes[0];
  721. // If the editor is present
  722. if (editorButton.classList.contains('checked')) {
  723. setToMultipleID("editorButton", "removeClass", 'checked');
  724. splitInstance.collapse(0);
  725. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-square" aria-hidden="true"></i>');
  726. } else {
  727. setToMultipleID("editorButton", "addClass", 'checked');
  728. splitInstance.setSizes([50, 50]); // Reset
  729. setToMultipleID("editorButton", "innerHTML", 'Editor <i class="fa fa-check-square" aria-hidden="true"></i>');
  730. }
  731. engine.resize();
  732. if (scene.debugLayer.isVisible()) {
  733. scene.debugLayer.show({ embedMode: true });
  734. }
  735. }
  736. var toggleDebug = function () {
  737. // Always showing the debug layer, because you can close it by itself
  738. var scene = engine.scenes[0];
  739. if (scene.debugLayer.isVisible()) {
  740. scene.debugLayer.hide();
  741. }
  742. else {
  743. scene.debugLayer.show({ embedMode: true });
  744. }
  745. }
  746. var toggleMetadata = function () {
  747. document.getElementById("saveLayer").style.display = "block";
  748. }
  749. var formatCode = function () {
  750. monacoCreator.JsEditor.getAction('editor.action.formatDocument').run();
  751. }
  752. var toggleMinimap = function () {
  753. var minimapToggle = document.getElementById("minimapToggle1280");
  754. if (minimapToggle.classList.contains('checked')) {
  755. monacoCreator.JsEditor.updateOptions({ minimap: { enabled: false } });
  756. setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-square" aria-hidden="true"></i>');
  757. } else {
  758. monacoCreator.JsEditor.updateOptions({ minimap: { enabled: true } });
  759. setToMultipleID("minimapToggle", "innerHTML", 'Minimap <i class="fa fa-check-square" aria-hidden="true"></i>');
  760. }
  761. minimapToggle.classList.toggle('checked');
  762. }
  763. //Navigation Overwrites
  764. var exitPrompt = function (e) {
  765. var safeToggle = document.getElementById("safemodeToggle1280");
  766. if (safeToggle.classList.contains('checked')) {
  767. e = e || window.event;
  768. var message =
  769. 'This page is asking you to confirm that you want to leave - data you have entered may not be saved.';
  770. if (e) {
  771. e.returnValue = message;
  772. }
  773. return message;
  774. }
  775. };
  776. window.onbeforeunload = exitPrompt;
  777. // Snippet
  778. var save = function () {
  779. // Retrieve title if necessary
  780. if (document.getElementById("saveLayer")) {
  781. currentSnippetTitle = document.getElementById("saveFormTitle").value;
  782. currentSnippetDescription = document.getElementById("saveFormDescription").value;
  783. currentSnippetTags = document.getElementById("saveFormTags").value;
  784. }
  785. var xmlHttp = new XMLHttpRequest();
  786. xmlHttp.onreadystatechange = function () {
  787. if (xmlHttp.readyState === 4) {
  788. if (xmlHttp.status === 200) {
  789. var baseUrl = location.href.replace(location.hash, "").replace(location.search, "");
  790. var snippet = JSON.parse(xmlHttp.responseText);
  791. var newUrl = baseUrl + "#" + snippet.id;
  792. currentSnippetToken = snippet.id;
  793. if (snippet.version && snippet.version !== "0") {
  794. newUrl += "#" + snippet.version;
  795. }
  796. location.href = newUrl;
  797. // Hide the complete title & co message
  798. hideNoMetadata();
  799. compileAndRun();
  800. } else {
  801. utils.showError("Unable to save your code. It may be too long.", null);
  802. }
  803. }
  804. }
  805. xmlHttp.open("POST", snippetV3Url + (currentSnippetToken ? "/" + currentSnippetToken : ""), true);
  806. xmlHttp.setRequestHeader("Content-Type", "application/json");
  807. var dataToSend = {
  808. payload: JSON.stringify({
  809. code: monacoCreator.JsEditor.getValue()
  810. }),
  811. name: currentSnippetTitle,
  812. description: currentSnippetDescription,
  813. tags: currentSnippetTags
  814. };
  815. xmlHttp.send(JSON.stringify(dataToSend));
  816. }
  817. var askForSave = function () {
  818. if (currentSnippetTitle == null
  819. || currentSnippetDescription == null
  820. || currentSnippetTags == null) {
  821. document.getElementById("saveLayer").style.display = "block";
  822. }
  823. else {
  824. save();
  825. }
  826. };
  827. document.getElementById("saveFormButtonOk").addEventListener("click", function () {
  828. document.getElementById("saveLayer").style.display = "none";
  829. save();
  830. });
  831. document.getElementById("saveFormButtonCancel").addEventListener("click", function () {
  832. document.getElementById("saveLayer").style.display = "none";
  833. });
  834. setToMultipleID("mainTitle", "innerHTML", "v" + BABYLON.Engine.Version);
  835. var previousHash = "";
  836. var cleanHash = function () {
  837. var splits = decodeURIComponent(location.hash.substr(1)).split("#");
  838. if (splits.length > 2) {
  839. splits.splice(2, splits.length - 2);
  840. }
  841. location.hash = splits.join("#");
  842. }
  843. var checkHash = function (firstTime) {
  844. if (location.hash) {
  845. if (previousHash !== location.hash) {
  846. cleanHash();
  847. previousHash = location.hash;
  848. try {
  849. var xmlHttp = new XMLHttpRequest();
  850. xmlHttp.onreadystatechange = function () {
  851. if (xmlHttp.readyState === 4) {
  852. if (xmlHttp.status === 200) {
  853. if (!checkTypescriptSupport(xmlHttp)) {
  854. return;
  855. }
  856. var snippet = JSON.parse(xmlHttp.responseText);
  857. monacoCreator.BlockEditorChange = true;
  858. monacoCreator.JsEditor.setValue(JSON.parse(snippet.jsonPayload).code.toString());
  859. // Check if title / descr / tags are already set
  860. if (snippet.name != null && snippet.name != "") {
  861. currentSnippetTitle = snippet.name;
  862. }
  863. else currentSnippetTitle = null;
  864. if (snippet.description != null && snippet.description != "") {
  865. currentSnippetDescription = snippet.description;
  866. }
  867. else currentSnippetDescription = null;
  868. if (snippet.tags != null && snippet.tags != "") {
  869. currentSnippetTags = snippet.tags;
  870. }
  871. else currentSnippetTags = null;
  872. if (currentSnippetTitle != null && currentSnippetTags != null && currentSnippetDescription) {
  873. if (document.getElementById("saveLayer")) {
  874. document.getElementById("saveFormTitle").value = currentSnippetTitle;
  875. document.getElementById("saveFormDescription").value = currentSnippetDescription;
  876. document.getElementById("saveFormTags").value = currentSnippetTags;
  877. hideNoMetadata();
  878. }
  879. }
  880. else {
  881. showNoMetadata();
  882. }
  883. monacoCreator.JsEditor.setPosition({ lineNumber: 0, column: 0 });
  884. monacoCreator.BlockEditorChange = false;
  885. compileAndRun();
  886. // setToMultipleID("currentScript", "innerHTML", "Custom");
  887. }
  888. }
  889. };
  890. var hash = location.hash.substr(1);
  891. currentSnippetToken = hash.split("#")[0];
  892. if (!hash.split("#")[1]) hash += "#0";
  893. xmlHttp.open("GET", snippetV3Url + "/" + hash.replace("#", "/"));
  894. xmlHttp.send();
  895. } catch (e) {
  896. }
  897. }
  898. }
  899. setTimeout(checkHash, 200);
  900. }
  901. checkHash(true);
  902. // ---------- UI
  903. // Run
  904. setToMultipleID("runButton", "click", compileAndRun);
  905. // New
  906. setToMultipleID("newButton", "click", createNewScript);
  907. // Clear
  908. setToMultipleID("clearButton", "click", clear);
  909. // Save
  910. setToMultipleID("saveButton", "click", askForSave);
  911. // Zip
  912. setToMultipleID("zipButton", "click", getZip);
  913. // // Themes
  914. setToMultipleID("darkTheme", "click", [settingsPG.setTheme.bind(settingsPG, 'dark'), menuPG.clickOptionSub.bind(menuPG)]);
  915. setToMultipleID("lightTheme", "click", [settingsPG.setTheme.bind(settingsPG, 'light'), menuPG.clickOptionSub.bind(menuPG)]);
  916. // Size
  917. var displayFontSize = document.getElementsByClassName('displayFontSize');
  918. for (var i = 0; i < displayFontSize.length; i++) {
  919. var options = displayFontSize[i].querySelectorAll('.option');
  920. for (var j = 0; j < options.length; j++) {
  921. options[j].addEventListener('click', menuPG.clickOptionSub.bind(menuPG));
  922. options[j].addEventListener('click', settingsPG.setFontSize.bind(settingsPG, options[j].innerText));
  923. }
  924. }
  925. // Footer links
  926. var displayFontSize = document.getElementsByClassName('displayFooterLinks');
  927. for (var i = 0; i < displayFontSize.length; i++) {
  928. var options = displayFontSize[i].querySelectorAll('.option');
  929. for (var j = 0; j < options.length; j++) {
  930. options[j].addEventListener('click', menuPG.clickOptionSub.bind(this));
  931. }
  932. }
  933. // Language (JS / TS)
  934. setToMultipleID("toTSbutton", "click", function () {
  935. settingsPG.ScriptLanguage = "TS";
  936. location.reload();
  937. });
  938. setToMultipleID("toJSbutton", "click", function () {
  939. settingsPG.ScriptLanguage = "JS";
  940. location.reload();
  941. });
  942. // Safe mode
  943. setToMultipleID("safemodeToggle", 'click', function () {
  944. document.getElementById("safemodeToggle1280").classList.toggle('checked');
  945. if (document.getElementById("safemodeToggle1280").classList.contains('checked')) {
  946. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-check-square" aria-hidden="true"></i>');
  947. } else {
  948. setToMultipleID("safemodeToggle", "innerHTML", 'Safe mode <i class="fa fa-square" aria-hidden="true"></i>');
  949. }
  950. });
  951. // Editor
  952. setToMultipleID("editorButton", "click", toggleEditor);
  953. // FullScreen
  954. setToMultipleID("fullscreenButton", "click", goFullscreen);
  955. // Editor fullScreen
  956. setToMultipleID("editorFullscreenButton", "click", editorGoFullscreen);
  957. // Format
  958. setToMultipleID("formatButton", "click", formatCode);
  959. // Format
  960. setToMultipleID("minimapToggle", "click", toggleMinimap);
  961. // Debug
  962. setToMultipleID("debugButton", "click", toggleDebug);
  963. // Metadata
  964. setToMultipleID("metadataButton", "click", toggleMetadata);
  965. // Restore theme
  966. settingsPG.restoreTheme(monacoCreator);
  967. // Restore language
  968. settingsPG.setScriptLanguage();
  969. menuPG.resizeBigCanvas();
  970. }