index.js 53 KB

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