babylon.tools.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. img.crossOrigin = 'anonymous';
  142. img.onload = () => {
  143. onload(img);
  144. };
  145. img.onerror = err => {
  146. onerror(img, err);
  147. };
  148. var noIndexedDB = () => {
  149. img.src = url;
  150. };
  151. var loadFromIndexedDB = () => {
  152. database.loadImageFromDB(url, img);
  153. };
  154. //ANY database to do!
  155. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  156. database.openAsync(loadFromIndexedDB, noIndexedDB);
  157. }
  158. else {
  159. if (url.indexOf("file:") === -1) {
  160. noIndexedDB();
  161. }
  162. else {
  163. try {
  164. var textureName = url.substring(5);
  165. var blobURL;
  166. try {
  167. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  168. }
  169. catch (ex) {
  170. // Chrome doesn't support oneTimeOnly parameter
  171. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  172. }
  173. img.src = blobURL;
  174. }
  175. catch (e) {
  176. Tools.Log("Error while trying to load texture: " + textureName);
  177. img.src = null;
  178. }
  179. }
  180. }
  181. return img;
  182. }
  183. //ANY
  184. public static LoadFile(url: string, callback: (data: any) => void, progressCallBack?: () => void, database?, useArrayBuffer?: boolean, onError?: () => void): void {
  185. url = Tools.CleanUrl(url);
  186. var noIndexedDB = () => {
  187. var request = new XMLHttpRequest();
  188. var loadUrl = Tools.BaseUrl + url;
  189. request.open('GET', loadUrl, true);
  190. if (useArrayBuffer) {
  191. request.responseType = "arraybuffer";
  192. }
  193. request.onprogress = progressCallBack;
  194. request.onreadystatechange = () => {
  195. if (request.readyState == 4) {
  196. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  197. callback(!useArrayBuffer ? request.responseText : request.response);
  198. } else { // Failed
  199. if (onError) {
  200. onError();
  201. } else {
  202. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  203. }
  204. }
  205. }
  206. };
  207. request.send(null);
  208. };
  209. var loadFromIndexedDB = () => {
  210. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  211. };
  212. if (url.indexOf("file:") !== -1) {
  213. var fileName = url.substring(5);
  214. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  215. }
  216. else {
  217. // Caching all files
  218. if (database && database.enableSceneOffline) {
  219. database.openAsync(loadFromIndexedDB, noIndexedDB);
  220. }
  221. else {
  222. noIndexedDB();
  223. }
  224. }
  225. }
  226. public static ReadFile(fileToLoad, callback, progressCallBack, useArrayBuffer?: boolean): void {
  227. var reader = new FileReader();
  228. reader.onload = e => {
  229. callback(e.target.result);
  230. };
  231. reader.onprogress = progressCallBack;
  232. if (!useArrayBuffer) {
  233. // Asynchronous read
  234. reader.readAsText(fileToLoad);
  235. }
  236. else {
  237. reader.readAsArrayBuffer(fileToLoad);
  238. }
  239. }
  240. // Misc.
  241. public static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void {
  242. if (v.x < min.x)
  243. min.x = v.x;
  244. if (v.y < min.y)
  245. min.y = v.y;
  246. if (v.z < min.z)
  247. min.z = v.z;
  248. if (v.x > max.x)
  249. max.x = v.x;
  250. if (v.y > max.y)
  251. max.y = v.y;
  252. if (v.z > max.z)
  253. max.z = v.z;
  254. }
  255. public static WithinEpsilon(a: number, b: number): boolean {
  256. var num = a - b;
  257. return -1.401298E-45 <= num && num <= 1.401298E-45;
  258. }
  259. public static DeepCopy(source, destination, doNotCopyList?: string[], mustCopyList?: string[]): void {
  260. for (var prop in source) {
  261. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  262. continue;
  263. }
  264. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  265. continue;
  266. }
  267. var sourceValue = source[prop];
  268. var typeOfSourceValue = typeof sourceValue;
  269. if (typeOfSourceValue == "function") {
  270. continue;
  271. }
  272. if (typeOfSourceValue == "object") {
  273. if (sourceValue instanceof Array) {
  274. destination[prop] = [];
  275. if (sourceValue.length > 0) {
  276. if (typeof sourceValue[0] == "object") {
  277. for (var index = 0; index < sourceValue.length; index++) {
  278. var clonedValue = cloneValue(sourceValue[index], destination);
  279. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  280. destination[prop].push(clonedValue);
  281. }
  282. }
  283. } else {
  284. destination[prop] = sourceValue.slice(0);
  285. }
  286. }
  287. } else {
  288. destination[prop] = cloneValue(sourceValue, destination);
  289. }
  290. } else {
  291. destination[prop] = sourceValue;
  292. }
  293. }
  294. }
  295. public static IsEmpty(obj): boolean {
  296. for (var i in obj) {
  297. return false;
  298. }
  299. return true;
  300. }
  301. public static RegisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  302. for (var index = 0; index < events.length; index++) {
  303. var event = events[index];
  304. window.addEventListener(event.name, event.handler, false);
  305. try {
  306. if (window.parent) {
  307. window.parent.addEventListener(event.name, event.handler, false);
  308. }
  309. } catch (e) {
  310. // Silently fails...
  311. }
  312. }
  313. }
  314. public static UnregisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  315. for (var index = 0; index < events.length; index++) {
  316. var event = events[index];
  317. window.removeEventListener(event.name, event.handler);
  318. try {
  319. if (window.parent) {
  320. window.parent.removeEventListener(event.name, event.handler);
  321. }
  322. } catch (e) {
  323. // Silently fails...
  324. }
  325. }
  326. }
  327. public static GetFps(): number {
  328. return fps;
  329. }
  330. public static GetDeltaTime(): number {
  331. return deltaTime;
  332. }
  333. public static _MeasureFps(): void {
  334. previousFramesDuration.push((new Date).getTime());
  335. var length = previousFramesDuration.length;
  336. if (length >= 2) {
  337. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  338. }
  339. if (length >= fpsRange) {
  340. if (length > fpsRange) {
  341. previousFramesDuration.splice(0, 1);
  342. length = previousFramesDuration.length;
  343. }
  344. var sum = 0;
  345. for (var id = 0; id < length - 1; id++) {
  346. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  347. }
  348. fps = 1000.0 / (sum / (length - 1));
  349. }
  350. }
  351. public static CreateScreenshot(engine: Engine, camera: Camera, size: any): void {
  352. var width: number;
  353. var height: number;
  354. var scene = camera.getScene();
  355. var previousCamera: BABYLON.Camera = null;
  356. if (scene.activeCamera !== camera) {
  357. previousCamera = scene.activeCamera;
  358. scene.activeCamera = camera;
  359. }
  360. //If a precision value is specified
  361. if (size.precision) {
  362. width = Math.round(engine.getRenderWidth() * size.precision);
  363. height = Math.round(width / engine.getAspectRatio(camera));
  364. size = { width: width, height: height };
  365. }
  366. else if (size.width && size.height) {
  367. width = size.width;
  368. height = size.height;
  369. }
  370. //If passing only width, computing height to keep display canvas ratio.
  371. else if (size.width && !size.height) {
  372. width = size.width;
  373. height = Math.round(width / engine.getAspectRatio(camera));
  374. size = { width: width, height: height };
  375. }
  376. //If passing only height, computing width to keep display canvas ratio.
  377. else if (size.height && !size.width) {
  378. height = size.height;
  379. width = Math.round(height * engine.getAspectRatio(camera));
  380. size = { width: width, height: height };
  381. }
  382. //Assuming here that "size" parameter is a number
  383. else if (!isNaN(size)) {
  384. height = size;
  385. width = size;
  386. }
  387. else {
  388. Tools.Error("Invalid 'size' parameter !");
  389. return;
  390. }
  391. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  392. var texture = new RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  393. texture.renderList = engine.scenes[0].meshes;
  394. texture.onAfterRender = () => {
  395. // Read the contents of the framebuffer
  396. var numberOfChannelsByLine = width * 4;
  397. var halfHeight = height / 2;
  398. //Reading datas from WebGL
  399. var data = engine.readPixels(0, 0, width, height);
  400. //To flip image on Y axis.
  401. for (var i = 0; i < halfHeight; i++) {
  402. for (var j = 0; j < numberOfChannelsByLine; j++) {
  403. var currentCell = j + i * numberOfChannelsByLine;
  404. var targetLine = height - i - 1;
  405. var targetCell = j + targetLine * numberOfChannelsByLine;
  406. var temp = data[currentCell];
  407. data[currentCell] = data[targetCell];
  408. data[targetCell] = temp;
  409. }
  410. }
  411. // Create a 2D canvas to store the result
  412. if (!screenshotCanvas) {
  413. screenshotCanvas = document.createElement('canvas');
  414. }
  415. screenshotCanvas.width = width;
  416. screenshotCanvas.height = height;
  417. var context = screenshotCanvas.getContext('2d');
  418. // Copy the pixels to a 2D canvas
  419. var imageData = context.createImageData(width, height);
  420. imageData.data.set(data);
  421. context.putImageData(imageData, 0, 0);
  422. var base64Image = screenshotCanvas.toDataURL();
  423. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  424. if (("download" in document.createElement("a"))) {
  425. var a = window.document.createElement("a");
  426. a.href = base64Image;
  427. var date = new Date();
  428. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  429. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  430. window.document.body.appendChild(a);
  431. a.addEventListener("click", () => {
  432. a.parentElement.removeChild(a);
  433. });
  434. a.click();
  435. //Or opening a new tab with the image if it is not possible to automatically start download.
  436. } else {
  437. var newWindow = window.open("");
  438. var img = newWindow.document.createElement("img");
  439. img.src = base64Image;
  440. newWindow.document.body.appendChild(img);
  441. }
  442. };
  443. texture.render(true);
  444. texture.dispose();
  445. if (previousCamera) {
  446. scene.activeCamera = previousCamera;
  447. }
  448. }
  449. // XHR response validator for local file scenario
  450. public static ValidateXHRData(xhr: XMLHttpRequest, dataType = 7): boolean {
  451. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  452. try {
  453. if (dataType & 1) {
  454. if (xhr.responseText && xhr.responseText.length > 0) {
  455. return true;
  456. } else if (dataType === 1) {
  457. return false;
  458. }
  459. }
  460. if (dataType & 2) {
  461. // Check header width and height since there is no "TGA" magic number
  462. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  463. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  464. return true;
  465. } else if (dataType === 2) {
  466. return false;
  467. }
  468. }
  469. if (dataType & 4) {
  470. // Check for the "DDS" magic number
  471. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  472. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  473. return true;
  474. } else {
  475. return false;
  476. }
  477. }
  478. } catch (e) {
  479. // Global protection
  480. }
  481. return false;
  482. }
  483. // Logs
  484. private static _NoneLogLevel = 0;
  485. private static _MessageLogLevel = 1;
  486. private static _WarningLogLevel = 2;
  487. private static _ErrorLogLevel = 4;
  488. static get NoneLogLevel(): number {
  489. return Tools._NoneLogLevel;
  490. }
  491. static get MessageLogLevel(): number {
  492. return Tools._MessageLogLevel;
  493. }
  494. static get WarningLogLevel(): number {
  495. return Tools._WarningLogLevel;
  496. }
  497. static get ErrorLogLevel(): number {
  498. return Tools._ErrorLogLevel;
  499. }
  500. static get AllLogLevel(): number {
  501. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  502. }
  503. private static _FormatMessage(message: string): string {
  504. var padStr = i => (i < 10) ? "0" + i : "" + i;
  505. var date = new Date();
  506. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  507. }
  508. public static Log: (message: string) => void = Tools._LogEnabled;
  509. private static _LogDisabled(message: string): void {
  510. // nothing to do
  511. }
  512. private static _LogEnabled(message: string): void {
  513. console.log(Tools._FormatMessage(message));
  514. }
  515. public static Warn: (message: string) => void = Tools._WarnEnabled;
  516. private static _WarnDisabled(message: string): void {
  517. // nothing to do
  518. }
  519. private static _WarnEnabled(message: string): void {
  520. console.warn(Tools._FormatMessage(message));
  521. }
  522. public static Error: (message: string) => void = Tools._ErrorEnabled;
  523. private static _ErrorDisabled(message: string): void {
  524. // nothing to do
  525. }
  526. private static _ErrorEnabled(message: string): void {
  527. console.error(Tools._FormatMessage(message));
  528. }
  529. public static set LogLevels(level: number) {
  530. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  531. Tools.Log = Tools._LogEnabled;
  532. }
  533. else {
  534. Tools.Log = Tools._LogDisabled;
  535. }
  536. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  537. Tools.Warn = Tools._WarnEnabled;
  538. }
  539. else {
  540. Tools.Warn = Tools._WarnDisabled;
  541. }
  542. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  543. Tools.Error = Tools._ErrorEnabled;
  544. }
  545. else {
  546. Tools.Error = Tools._ErrorDisabled;
  547. }
  548. }
  549. }
  550. }