babylon.tools.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. // ANY
  2. declare module BABYLON {
  3. export class Database {
  4. static isUASupportingBlobStorage: boolean;
  5. }
  6. }
  7. module BABYLON {
  8. //class FilesTextures { } //ANY
  9. export interface IAnimatable {
  10. animations: Array<Animation>;
  11. }
  12. export interface ISize {
  13. width: number;
  14. height: number;
  15. }
  16. // Screenshots
  17. var screenshotCanvas: HTMLCanvasElement;
  18. // FPS
  19. var fpsRange = 60;
  20. var previousFramesDuration = [];
  21. var fps = 60;
  22. var deltaTime = 0;
  23. var cloneValue = (source, destinationObject) => {
  24. if (!source)
  25. return null;
  26. if (source instanceof Mesh) {
  27. return null;
  28. }
  29. if (source instanceof SubMesh) {
  30. return source.clone(destinationObject);
  31. } else if (source.clone) {
  32. return source.clone();
  33. }
  34. return null;
  35. };
  36. export class Tools {
  37. public static BaseUrl = "";
  38. public static GetFilename(path: string): string {
  39. var index = path.lastIndexOf("/");
  40. if (index < 0)
  41. return path;
  42. return path.substring(index + 1);
  43. }
  44. public static GetDOMTextContent(element: HTMLElement): string {
  45. var result = "";
  46. var child = element.firstChild;
  47. while (child) {
  48. if (child.nodeType == 3) {
  49. result += child.textContent;
  50. }
  51. child = child.nextSibling;
  52. }
  53. return result;
  54. }
  55. public static ToDegrees(angle: number): number {
  56. return angle * 180 / Math.PI;
  57. }
  58. public static ToRadians(angle: number): number {
  59. return angle * Math.PI / 180;
  60. }
  61. public static ExtractMinAndMaxIndexed(positions: number[], indices: number[], indexStart:number, indexCount: number): { minimum: Vector3; maximum: Vector3 } {
  62. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  63. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  64. for (var index = indexStart; index < indexStart + indexCount; index ++) {
  65. var current = new Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  66. minimum = BABYLON.Vector3.Minimize(current, minimum);
  67. maximum = BABYLON.Vector3.Maximize(current, maximum);
  68. }
  69. return {
  70. minimum: minimum,
  71. maximum: maximum
  72. };
  73. }
  74. public static ExtractMinAndMax(positions: number[], start: number, count: number): { minimum: Vector3; maximum: Vector3 } {
  75. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  76. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  77. for (var index = start; index < start + count; index++) {
  78. var current = new Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  79. minimum = BABYLON.Vector3.Minimize(current, minimum);
  80. maximum = BABYLON.Vector3.Maximize(current, maximum);
  81. }
  82. return {
  83. minimum: minimum,
  84. maximum: maximum
  85. };
  86. }
  87. public static MakeArray(obj, allowsNullUndefined?: boolean): Array<any> {
  88. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  89. return undefined;
  90. return Array.isArray(obj) ? obj : [obj];
  91. }
  92. // Misc.
  93. public static GetPointerPrefix(): string {
  94. var eventPrefix = "pointer";
  95. // Check if hand.js is referenced or if the browser natively supports pointer events
  96. if (!navigator.pointerEnabled) {
  97. eventPrefix = "mouse";
  98. }
  99. return eventPrefix;
  100. }
  101. public static QueueNewFrame(func): void {
  102. if (window.requestAnimationFrame)
  103. window.requestAnimationFrame(func);
  104. else if (window.msRequestAnimationFrame)
  105. window.msRequestAnimationFrame(func);
  106. else if (window.webkitRequestAnimationFrame)
  107. window.webkitRequestAnimationFrame(func);
  108. else if (window.mozRequestAnimationFrame)
  109. window.mozRequestAnimationFrame(func);
  110. else if (window.oRequestAnimationFrame)
  111. window.oRequestAnimationFrame(func);
  112. else {
  113. window.setTimeout(func, 16);
  114. }
  115. }
  116. public static RequestFullscreen(element): void {
  117. if (element.requestFullscreen)
  118. element.requestFullscreen();
  119. else if (element.msRequestFullscreen)
  120. element.msRequestFullscreen();
  121. else if (element.webkitRequestFullscreen)
  122. element.webkitRequestFullscreen();
  123. else if (element.mozRequestFullScreen)
  124. element.mozRequestFullScreen();
  125. }
  126. public static ExitFullscreen(): void {
  127. if (document.exitFullscreen) {
  128. document.exitFullscreen();
  129. }
  130. else if (document.mozCancelFullScreen) {
  131. document.mozCancelFullScreen();
  132. }
  133. else if (document.webkitCancelFullScreen) {
  134. document.webkitCancelFullScreen();
  135. }
  136. else if (document.msCancelFullScreen) {
  137. document.msCancelFullScreen();
  138. }
  139. }
  140. // External files
  141. public static CleanUrl(url: string): string {
  142. url = url.replace(/#/mg, "%23");
  143. return url;
  144. }
  145. public static LoadImage(url: string, onload, onerror, database): HTMLImageElement {
  146. url = Tools.CleanUrl(url);
  147. var img = new Image();
  148. img.crossOrigin = 'anonymous';
  149. img.onload = () => {
  150. onload(img);
  151. };
  152. img.onerror = err => {
  153. onerror(img, err);
  154. };
  155. var noIndexedDB = () => {
  156. img.src = url;
  157. };
  158. var loadFromIndexedDB = () => {
  159. database.loadImageFromDB(url, img);
  160. };
  161. //ANY database to do!
  162. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  163. database.openAsync(loadFromIndexedDB, noIndexedDB);
  164. }
  165. else {
  166. if (url.indexOf("file:") === -1) {
  167. noIndexedDB();
  168. }
  169. else {
  170. try {
  171. var textureName = url.substring(5);
  172. var blobURL;
  173. try {
  174. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  175. }
  176. catch (ex) {
  177. // Chrome doesn't support oneTimeOnly parameter
  178. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  179. }
  180. img.src = blobURL;
  181. }
  182. catch (e) {
  183. Tools.Log("Error while trying to load texture: " + textureName);
  184. img.src = null;
  185. }
  186. }
  187. }
  188. return img;
  189. }
  190. //ANY
  191. public static LoadFile(url: string, callback: (data: any) => void, progressCallBack?: () => void, database?, useArrayBuffer?: boolean): void {
  192. url = Tools.CleanUrl(url);
  193. var noIndexedDB = () => {
  194. var request = new XMLHttpRequest();
  195. var loadUrl = Tools.BaseUrl + url;
  196. request.open('GET', loadUrl, true);
  197. if (useArrayBuffer) {
  198. request.responseType = "arraybuffer";
  199. }
  200. request.onprogress = progressCallBack;
  201. request.onreadystatechange = () => {
  202. if (request.readyState == 4) {
  203. if (request.status == 200) {
  204. callback(!useArrayBuffer ? request.responseText : request.response);
  205. } else { // Failed
  206. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  207. }
  208. }
  209. };
  210. request.send(null);
  211. };
  212. var loadFromIndexedDB = () => {
  213. database.loadSceneFromDB(url, callback, progressCallBack, noIndexedDB);
  214. };
  215. if (url.indexOf("file:") !== -1) {
  216. var fileName = url.substring(5);
  217. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  218. }
  219. else {
  220. // Caching only scenes files
  221. if (database && url.indexOf(".babylon") !== -1 && (database.enableSceneOffline)) {
  222. database.openAsync(loadFromIndexedDB, noIndexedDB);
  223. }
  224. else {
  225. noIndexedDB();
  226. }
  227. }
  228. }
  229. public static ReadFile(fileToLoad, callback, progressCallBack, useArrayBuffer?: boolean): void {
  230. var reader = new FileReader();
  231. reader.onload = e => {
  232. callback(e.target.result);
  233. };
  234. reader.onprogress = progressCallBack;
  235. if (!useArrayBuffer) {
  236. // Asynchronous read
  237. reader.readAsText(fileToLoad);
  238. }
  239. else {
  240. reader.readAsArrayBuffer(fileToLoad);
  241. }
  242. }
  243. // Misc.
  244. public static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void {
  245. if (v.x < min.x)
  246. min.x = v.x;
  247. if (v.y < min.y)
  248. min.y = v.y;
  249. if (v.z < min.z)
  250. min.z = v.z;
  251. if (v.x > max.x)
  252. max.x = v.x;
  253. if (v.y > max.y)
  254. max.y = v.y;
  255. if (v.z > max.z)
  256. max.z = v.z;
  257. }
  258. public static WithinEpsilon(a: number, b: number): boolean {
  259. var num = a - b;
  260. return -1.401298E-45 <= num && num <= 1.401298E-45;
  261. }
  262. public static DeepCopy(source, destination, doNotCopyList?: string[], mustCopyList?: string[]): void {
  263. for (var prop in source) {
  264. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  265. continue;
  266. }
  267. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  268. continue;
  269. }
  270. var sourceValue = source[prop];
  271. var typeOfSourceValue = typeof sourceValue;
  272. if (typeOfSourceValue == "function") {
  273. continue;
  274. }
  275. if (typeOfSourceValue == "object") {
  276. if (sourceValue instanceof Array) {
  277. destination[prop] = [];
  278. if (sourceValue.length > 0) {
  279. if (typeof sourceValue[0] == "object") {
  280. for (var index = 0; index < sourceValue.length; index++) {
  281. var clonedValue = cloneValue(sourceValue[index], destination);
  282. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  283. destination[prop].push(clonedValue);
  284. }
  285. }
  286. } else {
  287. destination[prop] = sourceValue.slice(0);
  288. }
  289. }
  290. } else {
  291. destination[prop] = cloneValue(sourceValue, destination);
  292. }
  293. } else {
  294. destination[prop] = sourceValue;
  295. }
  296. }
  297. }
  298. public static IsEmpty(obj): boolean {
  299. for (var i in obj) {
  300. return false;
  301. }
  302. return true;
  303. }
  304. public static RegisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  305. for (var index = 0; index < events.length; index++) {
  306. var event = events[index];
  307. window.addEventListener(event.name, event.handler, false);
  308. try {
  309. if (window.parent) {
  310. window.parent.addEventListener(event.name, event.handler, false);
  311. }
  312. } catch (e) {
  313. // Silently fails...
  314. }
  315. }
  316. }
  317. public static UnregisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  318. for (var index = 0; index < events.length; index++) {
  319. var event = events[index];
  320. window.removeEventListener(event.name, event.handler);
  321. try {
  322. if (window.parent) {
  323. window.parent.removeEventListener(event.name, event.handler);
  324. }
  325. } catch (e) {
  326. // Silently fails...
  327. }
  328. }
  329. }
  330. public static GetFps(): number {
  331. return fps;
  332. }
  333. public static GetDeltaTime(): number {
  334. return deltaTime;
  335. }
  336. public static _MeasureFps(): void {
  337. previousFramesDuration.push((new Date).getTime());
  338. var length = previousFramesDuration.length;
  339. if (length >= 2) {
  340. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  341. }
  342. if (length >= fpsRange) {
  343. if (length > fpsRange) {
  344. previousFramesDuration.splice(0, 1);
  345. length = previousFramesDuration.length;
  346. }
  347. var sum = 0;
  348. for (var id = 0; id < length - 1; id++) {
  349. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  350. }
  351. fps = 1000.0 / (sum / (length - 1));
  352. }
  353. }
  354. public static CreateScreenshot(engine: Engine, camera: Camera, size: any): void {
  355. var width: number;
  356. var height: number;
  357. var scene = camera.getScene();
  358. var previousCamera: BABYLON.Camera = null;
  359. if (scene.activeCamera !== camera) {
  360. previousCamera = scene.activeCamera;
  361. scene.activeCamera = camera;
  362. }
  363. //If a precision value is specified
  364. if (size.precision) {
  365. width = Math.round(engine.getRenderWidth() * size.precision);
  366. height = Math.round(width / engine.getAspectRatio(camera));
  367. size = { width: width, height: height };
  368. }
  369. else if (size.width && size.height) {
  370. width = size.width;
  371. height = size.height;
  372. }
  373. //If passing only width, computing height to keep display canvas ratio.
  374. else if (size.width && !size.height) {
  375. width = size.width;
  376. height = Math.round(width / engine.getAspectRatio(camera));
  377. size = { width: width, height: height };
  378. }
  379. //If passing only height, computing width to keep display canvas ratio.
  380. else if (size.height && !size.width) {
  381. height = size.height;
  382. width = Math.round(height * engine.getAspectRatio(camera));
  383. size = { width: width, height: height };
  384. }
  385. //Assuming here that "size" parameter is a number
  386. else if (!isNaN(size)) {
  387. height = size;
  388. width = size;
  389. }
  390. else {
  391. Tools.Error("Invalid 'size' parameter !");
  392. return;
  393. }
  394. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  395. var texture = new RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  396. texture.renderList = engine.scenes[0].meshes;
  397. texture.onAfterRender = () => {
  398. // Read the contents of the framebuffer
  399. var numberOfChannelsByLine = width * 4;
  400. var halfHeight = height / 2;
  401. //Reading datas from WebGL
  402. var data = engine.readPixels(0, 0, width, height);
  403. //To flip image on Y axis.
  404. for (var i = 0; i < halfHeight; i++) {
  405. for (var j = 0; j < numberOfChannelsByLine; j++) {
  406. var currentCell = j + i * numberOfChannelsByLine;
  407. var targetLine = height - i - 1;
  408. var targetCell = j + targetLine * numberOfChannelsByLine;
  409. var temp = data[currentCell];
  410. data[currentCell] = data[targetCell];
  411. data[targetCell] = temp;
  412. }
  413. }
  414. // Create a 2D canvas to store the result
  415. if (!screenshotCanvas) {
  416. screenshotCanvas = document.createElement('canvas');
  417. }
  418. screenshotCanvas.width = width;
  419. screenshotCanvas.height = height;
  420. var context = screenshotCanvas.getContext('2d');
  421. // Copy the pixels to a 2D canvas
  422. var imageData = context.createImageData(width, height);
  423. imageData.data.set(data);
  424. context.putImageData(imageData, 0, 0);
  425. var base64Image = screenshotCanvas.toDataURL();
  426. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  427. if (("download" in document.createElement("a"))) {
  428. var a = window.document.createElement("a");
  429. a.href = base64Image;
  430. var date = new Date();
  431. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  432. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  433. window.document.body.appendChild(a);
  434. a.addEventListener("click", () => {
  435. a.parentElement.removeChild(a);
  436. });
  437. a.click();
  438. //Or opening a new tab with the image if it is not possible to automatically start download.
  439. } else {
  440. var newWindow = window.open("");
  441. var img = newWindow.document.createElement("img");
  442. img.src = base64Image;
  443. newWindow.document.body.appendChild(img);
  444. }
  445. };
  446. texture.render(true);
  447. texture.dispose();
  448. if (previousCamera) {
  449. scene.activeCamera = previousCamera;
  450. }
  451. }
  452. // Logs
  453. private static _NoneLogLevel = 0;
  454. private static _MessageLogLevel = 1;
  455. private static _WarningLogLevel = 2;
  456. private static _ErrorLogLevel = 4;
  457. static get NoneLogLevel(): number {
  458. return Tools._NoneLogLevel;
  459. }
  460. static get MessageLogLevel(): number {
  461. return Tools._MessageLogLevel;
  462. }
  463. static get WarningLogLevel(): number {
  464. return Tools._WarningLogLevel;
  465. }
  466. static get ErrorLogLevel(): number {
  467. return Tools._ErrorLogLevel;
  468. }
  469. static get AllLogLevel(): number {
  470. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;;
  471. }
  472. private static _FormatMessage(message: string): string {
  473. var padStr = i => (i < 10) ? "0" + i : "" + i;
  474. var date = new Date();
  475. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  476. }
  477. public static Log: (message: string) => void = Tools._LogEnabled;
  478. private static _LogDisabled(message: string): void {
  479. // nothing to do
  480. }
  481. private static _LogEnabled(message: string): void {
  482. console.log(Tools._FormatMessage(message));
  483. }
  484. public static Warn: (message: string) => void = Tools._WarnEnabled;
  485. private static _WarnDisabled(message: string): void {
  486. // nothing to do
  487. }
  488. private static _WarnEnabled(message: string): void {
  489. console.warn(Tools._FormatMessage(message));
  490. }
  491. public static Error: (message: string) => void = Tools._ErrorEnabled;
  492. private static _ErrorDisabled(message: string): void {
  493. // nothing to do
  494. }
  495. private static _ErrorEnabled(message: string): void {
  496. console.error(Tools._FormatMessage(message));
  497. }
  498. public static set LogLevels(level: number) {
  499. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  500. Tools.Log = Tools._LogEnabled;
  501. }
  502. else {
  503. Tools.Log = Tools._LogDisabled;
  504. }
  505. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  506. Tools.Warn = Tools._WarnEnabled;
  507. }
  508. else {
  509. Tools.Warn = Tools._WarnDisabled;
  510. }
  511. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  512. Tools.Error = Tools._ErrorEnabled;
  513. }
  514. else {
  515. Tools.Error = Tools._ErrorDisabled;
  516. }
  517. }
  518. }
  519. }