babylon.tools.ts 27 KB

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