babylon.tools.ts 16 KB

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