babylon.tools.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. var BABYLON;
  2. (function (BABYLON) {
  3. // Screenshots
  4. var screenshotCanvas;
  5. // FPS
  6. var fpsRange = 60;
  7. var previousFramesDuration = [];
  8. var fps = 60;
  9. var deltaTime = 0;
  10. var cloneValue = function (source, destinationObject) {
  11. if (!source)
  12. return null;
  13. if (source instanceof BABYLON.Mesh) {
  14. return null;
  15. }
  16. if (source instanceof BABYLON.SubMesh) {
  17. return source.clone(destinationObject);
  18. } else if (source.clone) {
  19. return source.clone();
  20. }
  21. return null;
  22. };
  23. var Tools = (function () {
  24. function Tools() {
  25. }
  26. Tools.GetFilename = function (path) {
  27. var index = path.lastIndexOf("/");
  28. if (index < 0)
  29. return path;
  30. return path.substring(index + 1);
  31. };
  32. Tools.GetDOMTextContent = function (element) {
  33. var result = "";
  34. var child = element.firstChild;
  35. while (child) {
  36. if (child.nodeType == 3) {
  37. result += child.textContent;
  38. }
  39. child = child.nextSibling;
  40. }
  41. return result;
  42. };
  43. Tools.ToDegrees = function (angle) {
  44. return angle * 180 / Math.PI;
  45. };
  46. Tools.ToRadians = function (angle) {
  47. return angle * Math.PI / 180;
  48. };
  49. Tools.ExtractMinAndMax = function (positions, start, count) {
  50. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  51. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  52. for (var index = start; index < start + count; index++) {
  53. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  54. minimum = BABYLON.Vector3.Minimize(current, minimum);
  55. maximum = BABYLON.Vector3.Maximize(current, maximum);
  56. }
  57. return {
  58. minimum: minimum,
  59. maximum: maximum
  60. };
  61. };
  62. Tools.MakeArray = function (obj, allowsNullUndefined) {
  63. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  64. return undefined;
  65. return Array.isArray(obj) ? obj : [obj];
  66. };
  67. // Misc.
  68. Tools.GetPointerPrefix = function () {
  69. var eventPrefix = "pointer";
  70. // Check if hand.js is referenced or if the browser natively supports pointer events
  71. if (!navigator.pointerEnabled) {
  72. eventPrefix = "mouse";
  73. }
  74. return eventPrefix;
  75. };
  76. Tools.QueueNewFrame = function (func) {
  77. if (window.requestAnimationFrame)
  78. window.requestAnimationFrame(func);
  79. else if (window.msRequestAnimationFrame)
  80. window.msRequestAnimationFrame(func);
  81. else if (window.webkitRequestAnimationFrame)
  82. window.webkitRequestAnimationFrame(func);
  83. else if (window.mozRequestAnimationFrame)
  84. window.mozRequestAnimationFrame(func);
  85. else if (window.oRequestAnimationFrame)
  86. window.oRequestAnimationFrame(func);
  87. else {
  88. window.setTimeout(func, 16);
  89. }
  90. };
  91. Tools.RequestFullscreen = function (element) {
  92. if (element.requestFullscreen)
  93. element.requestFullscreen();
  94. else if (element.msRequestFullscreen)
  95. element.msRequestFullscreen();
  96. else if (element.webkitRequestFullscreen)
  97. element.webkitRequestFullscreen();
  98. else if (element.mozRequestFullScreen)
  99. element.mozRequestFullScreen();
  100. };
  101. Tools.ExitFullscreen = function () {
  102. if (document.exitFullscreen) {
  103. document.exitFullscreen();
  104. } else if (document.mozCancelFullScreen) {
  105. document.mozCancelFullScreen();
  106. } else if (document.webkitCancelFullScreen) {
  107. document.webkitCancelFullScreen();
  108. } else if (document.msCancelFullScreen) {
  109. document.msCancelFullScreen();
  110. }
  111. };
  112. // External files
  113. Tools.LoadImage = function (url, onload, onerror, database) {
  114. var img = new Image();
  115. img.crossOrigin = 'anonymous';
  116. img.onload = function () {
  117. onload(img);
  118. };
  119. img.onerror = function (err) {
  120. onerror(img, err);
  121. };
  122. var noIndexedDB = function () {
  123. img.src = url;
  124. };
  125. var loadFromIndexedDB = function () {
  126. database.loadImageFromDB(url, img);
  127. };
  128. //ANY database to do!
  129. if (database && database.enableTexturesOffline) {
  130. database.openAsync(loadFromIndexedDB, noIndexedDB);
  131. } else {
  132. if (url.indexOf("file:") === -1) {
  133. noIndexedDB();
  134. } else {
  135. try {
  136. var textureName = url.substring(5);
  137. var blobURL;
  138. try {
  139. blobURL = URL.createObjectURL(FilesTextures[textureName], { oneTimeOnly: true });
  140. } catch (ex) {
  141. // Chrome doesn't support oneTimeOnly parameter
  142. blobURL = URL.createObjectURL(FilesTextures[textureName]);
  143. }
  144. img.src = blobURL;
  145. } catch (e) {
  146. console.log("Error while trying to load texture: " + textureName);
  147. img.src = null;
  148. }
  149. }
  150. }
  151. return img;
  152. };
  153. //ANY
  154. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer) {
  155. var noIndexedDB = function () {
  156. var request = new XMLHttpRequest();
  157. var loadUrl = Tools.BaseUrl + url;
  158. request.open('GET', loadUrl, true);
  159. if (useArrayBuffer) {
  160. request.responseType = "arraybuffer";
  161. }
  162. request.onprogress = progressCallBack;
  163. request.onreadystatechange = function () {
  164. if (request.readyState == 4) {
  165. if (request.status == 200) {
  166. callback(!useArrayBuffer ? request.responseText : request.response);
  167. } else {
  168. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  169. }
  170. }
  171. };
  172. request.send(null);
  173. };
  174. var loadFromIndexedDB = function () {
  175. database.loadSceneFromDB(url, callback, progressCallBack, noIndexedDB);
  176. };
  177. // Caching only scenes files
  178. if (database && url.indexOf(".babylon") !== -1 && (database.enableSceneOffline)) {
  179. database.openAsync(loadFromIndexedDB, noIndexedDB);
  180. } else {
  181. noIndexedDB();
  182. }
  183. };
  184. Tools.ReadFile = function (fileToLoad, callback, progressCallBack) {
  185. var reader = new FileReader();
  186. reader.onload = function (e) {
  187. callback(e.target.result);
  188. };
  189. reader.onprogress = progressCallBack;
  190. // Asynchronous read
  191. reader.readAsText(fileToLoad);
  192. };
  193. // Misc.
  194. Tools.WithinEpsilon = function (a, b) {
  195. var num = a - b;
  196. return -1.401298E-45 <= num && num <= 1.401298E-45;
  197. };
  198. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  199. for (var prop in source) {
  200. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  201. continue;
  202. }
  203. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  204. continue;
  205. }
  206. var sourceValue = source[prop];
  207. var typeOfSourceValue = typeof sourceValue;
  208. if (typeOfSourceValue == "function") {
  209. continue;
  210. }
  211. if (typeOfSourceValue == "object") {
  212. if (sourceValue instanceof Array) {
  213. destination[prop] = [];
  214. if (sourceValue.length > 0) {
  215. if (typeof sourceValue[0] == "object") {
  216. for (var index = 0; index < sourceValue.length; index++) {
  217. var clonedValue = cloneValue(sourceValue[index], destination);
  218. if (destination[prop].indexOf(clonedValue) === -1) {
  219. destination[prop].push(clonedValue);
  220. }
  221. }
  222. } else {
  223. destination[prop] = sourceValue.slice(0);
  224. }
  225. }
  226. } else {
  227. destination[prop] = cloneValue(sourceValue, destination);
  228. }
  229. } else {
  230. destination[prop] = sourceValue;
  231. }
  232. }
  233. };
  234. Tools.IsEmpty = function (obj) {
  235. for (var i in obj) {
  236. return false;
  237. }
  238. return true;
  239. };
  240. Tools.RegisterTopRootEvents = function (events) {
  241. for (var index = 0; index < events.length; index++) {
  242. var event = events[index];
  243. window.addEventListener(event.name, event.handler, false);
  244. try {
  245. if (window.parent) {
  246. window.parent.addEventListener(event.name, event.handler, false);
  247. }
  248. } catch (e) {
  249. // Silently fails...
  250. }
  251. }
  252. };
  253. Tools.UnregisterTopRootEvents = function (events) {
  254. for (var index = 0; index < events.length; index++) {
  255. var event = events[index];
  256. window.removeEventListener(event.name, event.handler);
  257. try {
  258. if (window.parent) {
  259. window.parent.removeEventListener(event.name, event.handler);
  260. }
  261. } catch (e) {
  262. // Silently fails...
  263. }
  264. }
  265. };
  266. Tools.GetFps = function () {
  267. return fps;
  268. };
  269. Tools.GetDeltaTime = function () {
  270. return deltaTime;
  271. };
  272. Tools._MeasureFps = function () {
  273. previousFramesDuration.push((new Date).getTime());
  274. var length = previousFramesDuration.length;
  275. if (length >= 2) {
  276. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  277. }
  278. if (length >= fpsRange) {
  279. if (length > fpsRange) {
  280. previousFramesDuration.splice(0, 1);
  281. length = previousFramesDuration.length;
  282. }
  283. var sum = 0;
  284. for (var id = 0; id < length - 1; id++) {
  285. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  286. }
  287. fps = 1000.0 / (sum / (length - 1));
  288. }
  289. };
  290. Tools.CreateScreenshot = function (engine, camera, size) {
  291. var width;
  292. var height;
  293. //If a precision value is specified
  294. if (size.precision) {
  295. width = Math.round(engine.getRenderWidth() * size.precision);
  296. height = Math.round(width / engine.getAspectRatio(camera));
  297. size = { width: width, height: height };
  298. } else if (size.width && size.height) {
  299. width = size.width;
  300. height = size.height;
  301. } else if (size.width && !size.height) {
  302. width = size.width;
  303. height = Math.round(width / engine.getAspectRatio(camera));
  304. size = { width: width, height: height };
  305. } else if (size.height && !size.width) {
  306. height = size.height;
  307. width = Math.round(height * engine.getAspectRatio(camera));
  308. size = { width: width, height: height };
  309. } else if (!isNaN(size)) {
  310. height = size;
  311. width = size;
  312. } else {
  313. console.error("Invalid 'size' parameter !");
  314. return;
  315. }
  316. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  317. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0]);
  318. texture.renderList = engine.scenes[0].meshes;
  319. texture.onAfterRender = function () {
  320. // Read the contents of the framebuffer
  321. var numberOfChannelsByLine = width * 4;
  322. var halfHeight = height / 2;
  323. //Reading datas from WebGL
  324. var data = engine.readPixels(0, 0, width, height);
  325. for (var i = 0; i < halfHeight; i++) {
  326. for (var j = 0; j < numberOfChannelsByLine; j++) {
  327. var currentCell = j + i * numberOfChannelsByLine;
  328. var targetLine = height - i - 1;
  329. var targetCell = j + targetLine * numberOfChannelsByLine;
  330. var temp = data[currentCell];
  331. data[currentCell] = data[targetCell];
  332. data[targetCell] = temp;
  333. }
  334. }
  335. // Create a 2D canvas to store the result
  336. if (!screenshotCanvas) {
  337. screenshotCanvas = document.createElement('canvas');
  338. }
  339. screenshotCanvas.width = width;
  340. screenshotCanvas.height = height;
  341. var context = screenshotCanvas.getContext('2d');
  342. // Copy the pixels to a 2D canvas
  343. var imageData = context.createImageData(width, height);
  344. imageData.data.set(data);
  345. context.putImageData(imageData, 0, 0);
  346. var base64Image = screenshotCanvas.toDataURL();
  347. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  348. if (("download" in document.createElement("a"))) {
  349. var a = window.document.createElement("a");
  350. a.href = base64Image;
  351. var date = new Date();
  352. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  353. a.setAttribute("download", "screenshot-" + stringDate);
  354. window.document.body.appendChild(a);
  355. a.addEventListener("click", function () {
  356. a.parentElement.removeChild(a);
  357. });
  358. a.click();
  359. //Or opening a new tab with the image if it is not possible to automatically start download.
  360. } else {
  361. var newWindow = window.open("");
  362. var img = newWindow.document.createElement("img");
  363. img.src = base64Image;
  364. newWindow.document.body.appendChild(img);
  365. }
  366. };
  367. texture.render();
  368. texture.dispose();
  369. };
  370. Tools.BaseUrl = "";
  371. return Tools;
  372. })();
  373. BABYLON.Tools = Tools;
  374. })(BABYLON || (BABYLON = {}));
  375. //# sourceMappingURL=babylon.tools.js.map