babylon.tools.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. Tools.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 RegisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  255. for (var index = 0; index < events.length; index++) {
  256. var event = events[index];
  257. window.addEventListener(event.name, event.handler, false);
  258. try {
  259. if (window.parent) {
  260. window.parent.addEventListener(event.name, event.handler, false);
  261. }
  262. } catch (e) {
  263. // Silently fails...
  264. }
  265. }
  266. }
  267. public static UnregisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  268. for (var index = 0; index < events.length; index++) {
  269. var event = events[index];
  270. window.removeEventListener(event.name, event.handler);
  271. try {
  272. if (window.parent) {
  273. window.parent.removeEventListener(event.name, event.handler);
  274. }
  275. } catch (e) {
  276. // Silently fails...
  277. }
  278. }
  279. }
  280. public static GetFps(): number {
  281. return fps;
  282. }
  283. public static GetDeltaTime(): number {
  284. return deltaTime;
  285. }
  286. public static _MeasureFps(): void {
  287. previousFramesDuration.push((new Date).getTime());
  288. var length = previousFramesDuration.length;
  289. if (length >= 2) {
  290. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  291. }
  292. if (length >= fpsRange) {
  293. if (length > fpsRange) {
  294. previousFramesDuration.splice(0, 1);
  295. length = previousFramesDuration.length;
  296. }
  297. var sum = 0;
  298. for (var id = 0; id < length - 1; id++) {
  299. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  300. }
  301. fps = 1000.0 / (sum / (length - 1));
  302. }
  303. }
  304. public static CreateScreenshot(engine: Engine, camera: Camera, size: any): void {
  305. var width: number;
  306. var height: number;
  307. var scene = camera.getScene();
  308. var previousCamera: BABYLON.Camera = null;
  309. if (scene.activeCamera !== camera) {
  310. previousCamera = scene.activeCamera;
  311. scene.activeCamera = camera;
  312. }
  313. //If a precision value is specified
  314. if (size.precision) {
  315. width = Math.round(engine.getRenderWidth() * size.precision);
  316. height = Math.round(width / engine.getAspectRatio(camera));
  317. size = { width: width, height: height };
  318. }
  319. else if (size.width && size.height) {
  320. width = size.width;
  321. height = size.height;
  322. }
  323. //If passing only width, computing height to keep display canvas ratio.
  324. else if (size.width && !size.height) {
  325. width = size.width;
  326. height = Math.round(width / engine.getAspectRatio(camera));
  327. size = { width: width, height: height };
  328. }
  329. //If passing only height, computing width to keep display canvas ratio.
  330. else if (size.height && !size.width) {
  331. height = size.height;
  332. width = Math.round(height * engine.getAspectRatio(camera));
  333. size = { width: width, height: height };
  334. }
  335. //Assuming here that "size" parameter is a number
  336. else if (!isNaN(size)) {
  337. height = size;
  338. width = size;
  339. }
  340. else {
  341. Tools.Error("Invalid 'size' parameter !");
  342. return;
  343. }
  344. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  345. var texture = new RenderTargetTexture("screenShot", size, engine.scenes[0]);
  346. texture.renderList = engine.scenes[0].meshes;
  347. texture.onAfterRender = () => {
  348. // Read the contents of the framebuffer
  349. var numberOfChannelsByLine = width * 4;
  350. var halfHeight = height / 2;
  351. //Reading datas from WebGL
  352. var data = engine.readPixels(0, 0, width, height);
  353. //To flip image on Y axis.
  354. for (var i = 0; i < halfHeight; i++) {
  355. for (var j = 0; j < numberOfChannelsByLine; j++) {
  356. var currentCell = j + i * numberOfChannelsByLine;
  357. var targetLine = height - i - 1;
  358. var targetCell = j + targetLine * numberOfChannelsByLine;
  359. var temp = data[currentCell];
  360. data[currentCell] = data[targetCell];
  361. data[targetCell] = temp;
  362. }
  363. }
  364. // Create a 2D canvas to store the result
  365. if (!screenshotCanvas) {
  366. screenshotCanvas = document.createElement('canvas');
  367. }
  368. screenshotCanvas.width = width;
  369. screenshotCanvas.height = height;
  370. var context = screenshotCanvas.getContext('2d');
  371. // Copy the pixels to a 2D canvas
  372. var imageData = context.createImageData(width, height);
  373. imageData.data.set(data);
  374. context.putImageData(imageData, 0, 0);
  375. var base64Image = screenshotCanvas.toDataURL();
  376. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  377. if (("download" in document.createElement("a"))) {
  378. var a = window.document.createElement("a");
  379. a.href = base64Image;
  380. var date = new Date();
  381. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  382. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  383. window.document.body.appendChild(a);
  384. a.addEventListener("click", () => {
  385. a.parentElement.removeChild(a);
  386. });
  387. a.click();
  388. //Or opening a new tab with the image if it is not possible to automatically start download.
  389. } else {
  390. var newWindow = window.open("");
  391. var img = newWindow.document.createElement("img");
  392. img.src = base64Image;
  393. newWindow.document.body.appendChild(img);
  394. }
  395. };
  396. texture.render(true);
  397. texture.dispose();
  398. if (previousCamera) {
  399. scene.activeCamera = previousCamera;
  400. }
  401. }
  402. // Logs
  403. private static _NoneLogLevel = 0;
  404. private static _MessageLogLevel = 1;
  405. private static _WarningLogLevel = 2;
  406. private static _ErrorLogLevel = 4;
  407. static get NoneLogLevel(): number {
  408. return Tools._NoneLogLevel;
  409. }
  410. static get MessageLogLevel(): number {
  411. return Tools._MessageLogLevel;
  412. }
  413. static get WarningLogLevel(): number {
  414. return Tools._WarningLogLevel;
  415. }
  416. static get ErrorLogLevel(): number {
  417. return Tools._ErrorLogLevel;
  418. }
  419. static get AllLogLevel(): number {
  420. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;;
  421. }
  422. private static _FormatMessage(message: string): string {
  423. var padStr = i => (i < 10) ? "0" + i : "" + i;
  424. var date = new Date();
  425. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  426. }
  427. public static Log: (message: string) => void = Tools._LogEnabled;
  428. private static _LogDisabled(message: string): void {
  429. // nothing to do
  430. }
  431. private static _LogEnabled(message: string): void {
  432. console.log(Tools._FormatMessage(message));
  433. }
  434. public static Warn: (message: string) => void = Tools._WarnEnabled;
  435. private static _WarnDisabled(message: string): void {
  436. // nothing to do
  437. }
  438. private static _WarnEnabled(message: string): void {
  439. console.warn(Tools._FormatMessage(message));
  440. }
  441. public static Error: (message: string) => void = Tools._ErrorEnabled;
  442. private static _ErrorDisabled(message: string): void {
  443. // nothing to do
  444. }
  445. private static _ErrorEnabled(message: string): void {
  446. console.error(Tools._FormatMessage(message));
  447. }
  448. public static set LogLevels(level: number) {
  449. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  450. Tools.Log = Tools._LogEnabled;
  451. }
  452. else {
  453. Tools.Log = Tools._LogDisabled;
  454. }
  455. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  456. Tools.Warn = Tools._WarnEnabled;
  457. }
  458. else {
  459. Tools.Warn = Tools._WarnDisabled;
  460. }
  461. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  462. Tools.Error = Tools._ErrorEnabled;
  463. }
  464. else {
  465. Tools.Error = Tools._ErrorDisabled;
  466. }
  467. }
  468. }
  469. }