babylon.tools.ts 24 KB

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