tools.ts 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. import { Nullable, float } from "../types";
  2. import { Observable } from "./observable";
  3. import { DomManagement } from "./domManagement";
  4. import { Logger } from "./logger";
  5. import { _TypeStore } from "./typeStore";
  6. import { DeepCopier } from "./deepCopier";
  7. import { PrecisionDate } from './precisionDate';
  8. import { _DevTools } from './devTools';
  9. import { WebRequest } from './webRequest';
  10. import { IFileRequest } from './fileRequest';
  11. import { EngineStore } from '../Engines/engineStore';
  12. import { FileTools } from './fileTools';
  13. import { IOfflineProvider } from '../Offline/IOfflineProvider';
  14. import { PromisePolyfill } from './promise';
  15. import { TimingTools } from './timingTools';
  16. import { InstantiationTools } from './instantiationTools';
  17. import { GUID } from './guid';
  18. import { IScreenshotSize } from './interfaces/screenshotSize';
  19. declare type Camera = import("../Cameras/camera").Camera;
  20. declare type Engine = import("../Engines/engine").Engine;
  21. interface IColor4Like {
  22. r: float;
  23. g: float;
  24. b: float;
  25. a: float;
  26. }
  27. /**
  28. * Class containing a set of static utilities functions
  29. */
  30. export class Tools {
  31. /**
  32. * Gets or sets the base URL to use to load assets
  33. */
  34. public static get BaseUrl() {
  35. return FileTools.BaseUrl;
  36. }
  37. public static set BaseUrl(value: string) {
  38. FileTools.BaseUrl = value;
  39. }
  40. /**
  41. * Enable/Disable Custom HTTP Request Headers globally.
  42. * default = false
  43. * @see CustomRequestHeaders
  44. */
  45. public static UseCustomRequestHeaders: boolean = false;
  46. /**
  47. * Custom HTTP Request Headers to be sent with XMLHttpRequests
  48. * i.e. when loading files, where the server/service expects an Authorization header
  49. */
  50. public static CustomRequestHeaders = WebRequest.CustomRequestHeaders;
  51. /**
  52. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  53. */
  54. public static get DefaultRetryStrategy() {
  55. return FileTools.DefaultRetryStrategy;
  56. }
  57. public static set DefaultRetryStrategy(strategy: (url: string, request: WebRequest, retryIndex: number) => number) {
  58. FileTools.DefaultRetryStrategy = strategy;
  59. }
  60. /**
  61. * Default behaviour for cors in the application.
  62. * It can be a string if the expected behavior is identical in the entire app.
  63. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  64. */
  65. public static CorsBehavior: string | ((url: string | string[]) => string) = "anonymous";
  66. /**
  67. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  68. * @ignorenaming
  69. */
  70. public static get UseFallbackTexture() {
  71. return EngineStore.UseFallbackTexture;
  72. }
  73. public static set UseFallbackTexture(value: boolean) {
  74. EngineStore.UseFallbackTexture = value;
  75. }
  76. /**
  77. * Use this object to register external classes like custom textures or material
  78. * to allow the laoders to instantiate them
  79. */
  80. public static get RegisteredExternalClasses() {
  81. return InstantiationTools.RegisteredExternalClasses;
  82. }
  83. public static set RegisteredExternalClasses(classes: { [key: string]: Object }) {
  84. InstantiationTools.RegisteredExternalClasses = classes;
  85. }
  86. /**
  87. * Texture content used if a texture cannot loaded
  88. * @ignorenaming
  89. */
  90. public static get fallbackTexture() {
  91. return EngineStore.FallbackTexture;
  92. }
  93. public static set fallbackTexture(value: string) {
  94. EngineStore.FallbackTexture = value;
  95. }
  96. /**
  97. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  98. * @param u defines the coordinate on X axis
  99. * @param v defines the coordinate on Y axis
  100. * @param width defines the width of the source data
  101. * @param height defines the height of the source data
  102. * @param pixels defines the source byte array
  103. * @param color defines the output color
  104. */
  105. public static FetchToRef(u: number, v: number, width: number, height: number, pixels: Uint8Array, color: IColor4Like): void {
  106. let wrappedU = ((Math.abs(u) * width) % width) | 0;
  107. let wrappedV = ((Math.abs(v) * height) % height) | 0;
  108. let position = (wrappedU + wrappedV * width) * 4;
  109. color.r = pixels[position] / 255;
  110. color.g = pixels[position + 1] / 255;
  111. color.b = pixels[position + 2] / 255;
  112. color.a = pixels[position + 3] / 255;
  113. }
  114. /**
  115. * Interpolates between a and b via alpha
  116. * @param a The lower value (returned when alpha = 0)
  117. * @param b The upper value (returned when alpha = 1)
  118. * @param alpha The interpolation-factor
  119. * @return The mixed value
  120. */
  121. public static Mix(a: number, b: number, alpha: number): number {
  122. return a * (1 - alpha) + b * alpha;
  123. }
  124. /**
  125. * Tries to instantiate a new object from a given class name
  126. * @param className defines the class name to instantiate
  127. * @returns the new object or null if the system was not able to do the instantiation
  128. */
  129. public static Instantiate(className: string): any {
  130. return InstantiationTools.Instantiate(className);
  131. }
  132. /**
  133. * Provides a slice function that will work even on IE
  134. * @param data defines the array to slice
  135. * @param start defines the start of the data (optional)
  136. * @param end defines the end of the data (optional)
  137. * @returns the new sliced array
  138. */
  139. public static Slice<T>(data: T, start?: number, end?: number): T {
  140. if ((data as any).slice) {
  141. return (data as any).slice(start, end);
  142. }
  143. return Array.prototype.slice.call(data, start, end);
  144. }
  145. /**
  146. * Polyfill for setImmediate
  147. * @param action defines the action to execute after the current execution block
  148. */
  149. public static SetImmediate(action: () => void) {
  150. TimingTools.SetImmediate(action);
  151. }
  152. /**
  153. * Function indicating if a number is an exponent of 2
  154. * @param value defines the value to test
  155. * @returns true if the value is an exponent of 2
  156. */
  157. public static IsExponentOfTwo(value: number): boolean {
  158. var count = 1;
  159. do {
  160. count *= 2;
  161. } while (count < value);
  162. return count === value;
  163. }
  164. private static _tmpFloatArray = new Float32Array(1);
  165. /**
  166. * Returns the nearest 32-bit single precision float representation of a Number
  167. * @param value A Number. If the parameter is of a different type, it will get converted
  168. * to a number or to NaN if it cannot be converted
  169. * @returns number
  170. */
  171. public static FloatRound(value: number): number {
  172. if (Math.fround) {
  173. return Math.fround(value);
  174. }
  175. return (Tools._tmpFloatArray[0] = value);
  176. }
  177. /**
  178. * Extracts the filename from a path
  179. * @param path defines the path to use
  180. * @returns the filename
  181. */
  182. public static GetFilename(path: string): string {
  183. var index = path.lastIndexOf("/");
  184. if (index < 0) {
  185. return path;
  186. }
  187. return path.substring(index + 1);
  188. }
  189. /**
  190. * Extracts the "folder" part of a path (everything before the filename).
  191. * @param uri The URI to extract the info from
  192. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  193. * @returns The "folder" part of the path
  194. */
  195. public static GetFolderPath(uri: string, returnUnchangedIfNoSlash = false): string {
  196. var index = uri.lastIndexOf("/");
  197. if (index < 0) {
  198. if (returnUnchangedIfNoSlash) {
  199. return uri;
  200. }
  201. return "";
  202. }
  203. return uri.substring(0, index + 1);
  204. }
  205. /**
  206. * Extracts text content from a DOM element hierarchy
  207. * Back Compat only, please use DomManagement.GetDOMTextContent instead.
  208. */
  209. public static GetDOMTextContent = DomManagement.GetDOMTextContent;
  210. /**
  211. * Convert an angle in radians to degrees
  212. * @param angle defines the angle to convert
  213. * @returns the angle in degrees
  214. */
  215. public static ToDegrees(angle: number): number {
  216. return angle * 180 / Math.PI;
  217. }
  218. /**
  219. * Convert an angle in degrees to radians
  220. * @param angle defines the angle to convert
  221. * @returns the angle in radians
  222. */
  223. public static ToRadians(angle: number): number {
  224. return angle * Math.PI / 180;
  225. }
  226. /**
  227. * Encode a buffer to a base64 string
  228. * @param buffer defines the buffer to encode
  229. * @returns the encoded string
  230. */
  231. public static EncodeArrayBufferTobase64(buffer: ArrayBuffer): string {
  232. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  233. var output = "";
  234. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  235. var i = 0;
  236. var bytes = new Uint8Array(buffer);
  237. while (i < bytes.length) {
  238. chr1 = bytes[i++];
  239. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  240. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  241. enc1 = chr1 >> 2;
  242. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  243. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  244. enc4 = chr3 & 63;
  245. if (isNaN(chr2)) {
  246. enc3 = enc4 = 64;
  247. } else if (isNaN(chr3)) {
  248. enc4 = 64;
  249. }
  250. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  251. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  252. }
  253. return "data:image/png;base64," + output;
  254. }
  255. /**
  256. * Returns an array if obj is not an array
  257. * @param obj defines the object to evaluate as an array
  258. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  259. * @returns either obj directly if obj is an array or a new array containing obj
  260. */
  261. public static MakeArray(obj: any, allowsNullUndefined?: boolean): Nullable<Array<any>> {
  262. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  263. return null;
  264. }
  265. return Array.isArray(obj) ? obj : [obj];
  266. }
  267. /**
  268. * Gets the pointer prefix to use
  269. * @returns "pointer" if touch is enabled. Else returns "mouse"
  270. */
  271. public static GetPointerPrefix(): string {
  272. var eventPrefix = "pointer";
  273. // Check if pointer events are supported
  274. if (DomManagement.IsWindowObjectExist() && !window.PointerEvent && DomManagement.IsNavigatorAvailable() && !navigator.pointerEnabled) {
  275. eventPrefix = "mouse";
  276. }
  277. return eventPrefix;
  278. }
  279. /**
  280. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  281. * @param url define the url we are trying
  282. * @param element define the dom element where to configure the cors policy
  283. */
  284. public static SetCorsBehavior(url: string | string[], element: { crossOrigin: string | null }): void {
  285. FileTools.SetCorsBehavior(url, element);
  286. }
  287. // External files
  288. /**
  289. * Removes unwanted characters from an url
  290. * @param url defines the url to clean
  291. * @returns the cleaned url
  292. */
  293. public static CleanUrl(url: string): string {
  294. url = url.replace(/#/mg, "%23");
  295. return url;
  296. }
  297. /**
  298. * Gets or sets a function used to pre-process url before using them to load assets
  299. */
  300. public static get PreprocessUrl() {
  301. return FileTools.PreprocessUrl;
  302. }
  303. public static set PreprocessUrl(processor: (url: string) => string) {
  304. FileTools.PreprocessUrl = processor;
  305. }
  306. /**
  307. * Loads an image as an HTMLImageElement.
  308. * @param input url string, ArrayBuffer, or Blob to load
  309. * @param onLoad callback called when the image successfully loads
  310. * @param onError callback called when the image fails to load
  311. * @param offlineProvider offline provider for caching
  312. * @param mimeType optional mime type
  313. * @returns the HTMLImageElement of the loaded image
  314. */
  315. public static LoadImage(input: string | ArrayBuffer | Blob, onLoad: (img: HTMLImageElement | ImageBitmap) => void, onError: (message?: string, exception?: any) => void, offlineProvider: Nullable<IOfflineProvider>, mimeType?: string): Nullable<HTMLImageElement> {
  316. return FileTools.LoadImage(input, onLoad, onError, offlineProvider, mimeType);
  317. }
  318. /**
  319. * Loads a file
  320. * @param url url string, ArrayBuffer, or Blob to load
  321. * @param onSuccess callback called when the file successfully loads
  322. * @param onProgress callback called while file is loading (if the server supports this mode)
  323. * @param offlineProvider defines the offline provider for caching
  324. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  325. * @param onError callback called when the file fails to load
  326. * @returns a file request object
  327. */
  328. public static LoadFile(url: string, onSuccess: (data: string | ArrayBuffer, responseURL?: string) => void, onProgress?: (data: any) => void, offlineProvider?: IOfflineProvider, useArrayBuffer?: boolean, onError?: (request?: WebRequest, exception?: any) => void): IFileRequest {
  329. return FileTools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  330. }
  331. /**
  332. * Loads a file from a url
  333. * @param url the file url to load
  334. * @returns a promise containing an ArrayBuffer corrisponding to the loaded file
  335. */
  336. public static LoadFileAsync(url: string): Promise<ArrayBuffer> {
  337. return new Promise((resolve, reject) => {
  338. FileTools.LoadFile(url, (data) => {
  339. resolve(data as ArrayBuffer);
  340. }, undefined, undefined, true, (request, exception) => {
  341. reject(exception);
  342. });
  343. });
  344. }
  345. /**
  346. * Load a script (identified by an url). When the url returns, the
  347. * content of this file is added into a new script element, attached to the DOM (body element)
  348. * @param scriptUrl defines the url of the script to laod
  349. * @param onSuccess defines the callback called when the script is loaded
  350. * @param onError defines the callback to call if an error occurs
  351. * @param scriptId defines the id of the script element
  352. */
  353. public static LoadScript(scriptUrl: string, onSuccess: () => void, onError?: (message?: string, exception?: any) => void, scriptId?: string) {
  354. if (!DomManagement.IsWindowObjectExist()) {
  355. return;
  356. }
  357. var head = document.getElementsByTagName('head')[0];
  358. var script = document.createElement('script');
  359. script.setAttribute('type', 'text/javascript');
  360. script.setAttribute('src', scriptUrl);
  361. if (scriptId) {
  362. script.id = scriptId;
  363. }
  364. script.onload = () => {
  365. if (onSuccess) {
  366. onSuccess();
  367. }
  368. };
  369. script.onerror = (e) => {
  370. if (onError) {
  371. onError(`Unable to load script '${scriptUrl}'`, e);
  372. }
  373. };
  374. head.appendChild(script);
  375. }
  376. /**
  377. * Load an asynchronous script (identified by an url). When the url returns, the
  378. * content of this file is added into a new script element, attached to the DOM (body element)
  379. * @param scriptUrl defines the url of the script to laod
  380. * @param scriptId defines the id of the script element
  381. * @returns a promise request object
  382. */
  383. public static LoadScriptAsync(scriptUrl: string, scriptId?: string): Promise<boolean> {
  384. return new Promise<boolean>((resolve, reject) => {
  385. if (!DomManagement.IsWindowObjectExist()) {
  386. resolve(false);
  387. return;
  388. }
  389. var head = document.getElementsByTagName('head')[0];
  390. var script = document.createElement('script');
  391. script.setAttribute('type', 'text/javascript');
  392. script.setAttribute('src', scriptUrl);
  393. if (scriptId) {
  394. script.id = scriptId;
  395. }
  396. script.onload = () => {
  397. resolve(true);
  398. };
  399. script.onerror = (e) => {
  400. resolve(false);
  401. };
  402. head.appendChild(script);
  403. });
  404. }
  405. /**
  406. * Loads a file from a blob
  407. * @param fileToLoad defines the blob to use
  408. * @param callback defines the callback to call when data is loaded
  409. * @param progressCallback defines the callback to call during loading process
  410. * @returns a file request object
  411. */
  412. public static ReadFileAsDataURL(fileToLoad: Blob, callback: (data: any) => void, progressCallback: (ev: ProgressEvent) => any): IFileRequest {
  413. let reader = new FileReader();
  414. let request: IFileRequest = {
  415. onCompleteObservable: new Observable<IFileRequest>(),
  416. abort: () => reader.abort(),
  417. };
  418. reader.onloadend = (e) => {
  419. request.onCompleteObservable.notifyObservers(request);
  420. };
  421. reader.onload = (e) => {
  422. //target doesn't have result from ts 1.3
  423. callback((<any>e.target)['result']);
  424. };
  425. reader.onprogress = progressCallback;
  426. reader.readAsDataURL(fileToLoad);
  427. return request;
  428. }
  429. /**
  430. * Loads a file
  431. * @param fileToLoad defines the file to load
  432. * @param callback defines the callback to call when data is loaded
  433. * @param progressCallBack defines the callback to call during loading process
  434. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  435. * @returns a file request object
  436. */
  437. public static ReadFile(fileToLoad: File, callback: (data: any) => void, progressCallBack?: (ev: ProgressEvent) => any, useArrayBuffer?: boolean): IFileRequest {
  438. return FileTools.ReadFile(fileToLoad, callback, progressCallBack, useArrayBuffer);
  439. }
  440. /**
  441. * Creates a data url from a given string content
  442. * @param content defines the content to convert
  443. * @returns the new data url link
  444. */
  445. public static FileAsURL(content: string): string {
  446. var fileBlob = new Blob([content]);
  447. var url = window.URL || window.webkitURL;
  448. var link: string = url.createObjectURL(fileBlob);
  449. return link;
  450. }
  451. /**
  452. * Format the given number to a specific decimal format
  453. * @param value defines the number to format
  454. * @param decimals defines the number of decimals to use
  455. * @returns the formatted string
  456. */
  457. public static Format(value: number, decimals: number = 2): string {
  458. return value.toFixed(decimals);
  459. }
  460. /**
  461. * Tries to copy an object by duplicating every property
  462. * @param source defines the source object
  463. * @param destination defines the target object
  464. * @param doNotCopyList defines a list of properties to avoid
  465. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  466. */
  467. public static DeepCopy(source: any, destination: any, doNotCopyList?: string[], mustCopyList?: string[]): void {
  468. DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList);
  469. }
  470. /**
  471. * Gets a boolean indicating if the given object has no own property
  472. * @param obj defines the object to test
  473. * @returns true if object has no own property
  474. */
  475. public static IsEmpty(obj: any): boolean {
  476. for (var i in obj) {
  477. if (obj.hasOwnProperty(i)) {
  478. return false;
  479. }
  480. }
  481. return true;
  482. }
  483. /**
  484. * Function used to register events at window level
  485. * @param windowElement defines the Window object to use
  486. * @param events defines the events to register
  487. */
  488. public static RegisterTopRootEvents(windowElement: Window, events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  489. for (var index = 0; index < events.length; index++) {
  490. var event = events[index];
  491. windowElement.addEventListener(event.name, <any>event.handler, false);
  492. try {
  493. if (window.parent) {
  494. window.parent.addEventListener(event.name, <any>event.handler, false);
  495. }
  496. } catch (e) {
  497. // Silently fails...
  498. }
  499. }
  500. }
  501. /**
  502. * Function used to unregister events from window level
  503. * @param windowElement defines the Window object to use
  504. * @param events defines the events to unregister
  505. */
  506. public static UnregisterTopRootEvents(windowElement: Window, events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  507. for (var index = 0; index < events.length; index++) {
  508. var event = events[index];
  509. windowElement.removeEventListener(event.name, <any>event.handler);
  510. try {
  511. if (windowElement.parent) {
  512. windowElement.parent.removeEventListener(event.name, <any>event.handler);
  513. }
  514. } catch (e) {
  515. // Silently fails...
  516. }
  517. }
  518. }
  519. /**
  520. * @ignore
  521. */
  522. public static _ScreenshotCanvas: HTMLCanvasElement;
  523. /**
  524. * Dumps the current bound framebuffer
  525. * @param width defines the rendering width
  526. * @param height defines the rendering height
  527. * @param engine defines the hosting engine
  528. * @param successCallback defines the callback triggered once the data are available
  529. * @param mimeType defines the mime type of the result
  530. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  531. */
  532. public static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string): void {
  533. // Read the contents of the framebuffer
  534. var numberOfChannelsByLine = width * 4;
  535. var halfHeight = height / 2;
  536. //Reading datas from WebGL
  537. var data = engine.readPixels(0, 0, width, height);
  538. //To flip image on Y axis.
  539. for (var i = 0; i < halfHeight; i++) {
  540. for (var j = 0; j < numberOfChannelsByLine; j++) {
  541. var currentCell = j + i * numberOfChannelsByLine;
  542. var targetLine = height - i - 1;
  543. var targetCell = j + targetLine * numberOfChannelsByLine;
  544. var temp = data[currentCell];
  545. data[currentCell] = data[targetCell];
  546. data[targetCell] = temp;
  547. }
  548. }
  549. // Create a 2D canvas to store the result
  550. if (!Tools._ScreenshotCanvas) {
  551. Tools._ScreenshotCanvas = document.createElement('canvas');
  552. }
  553. Tools._ScreenshotCanvas.width = width;
  554. Tools._ScreenshotCanvas.height = height;
  555. var context = Tools._ScreenshotCanvas.getContext('2d');
  556. if (context) {
  557. // Copy the pixels to a 2D canvas
  558. var imageData = context.createImageData(width, height);
  559. var castData = <any>(imageData.data);
  560. castData.set(data);
  561. context.putImageData(imageData, 0, 0);
  562. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  563. }
  564. }
  565. /**
  566. * Converts the canvas data to blob.
  567. * This acts as a polyfill for browsers not supporting the to blob function.
  568. * @param canvas Defines the canvas to extract the data from
  569. * @param successCallback Defines the callback triggered once the data are available
  570. * @param mimeType Defines the mime type of the result
  571. */
  572. static ToBlob(canvas: HTMLCanvasElement, successCallback: (blob: Nullable<Blob>) => void, mimeType: string = "image/png"): void {
  573. // We need HTMLCanvasElement.toBlob for HD screenshots
  574. if (!canvas.toBlob) {
  575. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  576. canvas.toBlob = function(callback, type, quality) {
  577. setTimeout(() => {
  578. var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
  579. len = binStr.length,
  580. arr = new Uint8Array(len);
  581. for (var i = 0; i < len; i++) {
  582. arr[i] = binStr.charCodeAt(i);
  583. }
  584. callback(new Blob([arr]));
  585. });
  586. };
  587. }
  588. canvas.toBlob(function(blob) {
  589. successCallback(blob);
  590. }, mimeType);
  591. }
  592. /**
  593. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  594. * @param successCallback defines the callback triggered once the data are available
  595. * @param mimeType defines the mime type of the result
  596. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  597. */
  598. static EncodeScreenshotCanvasData(successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string): void {
  599. if (successCallback) {
  600. var base64Image = Tools._ScreenshotCanvas.toDataURL(mimeType);
  601. successCallback(base64Image);
  602. }
  603. else {
  604. this.ToBlob(Tools._ScreenshotCanvas, function(blob) {
  605. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  606. if (("download" in document.createElement("a"))) {
  607. if (!fileName) {
  608. var date = new Date();
  609. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  610. fileName = "screenshot_" + stringDate + ".png";
  611. }
  612. Tools.Download(blob!, fileName);
  613. }
  614. else {
  615. var url = URL.createObjectURL(blob);
  616. var newWindow = window.open("");
  617. if (!newWindow) { return; }
  618. var img = newWindow.document.createElement("img");
  619. img.onload = function() {
  620. // no longer need to read the blob so it's revoked
  621. URL.revokeObjectURL(url);
  622. };
  623. img.src = url;
  624. newWindow.document.body.appendChild(img);
  625. }
  626. }, mimeType);
  627. }
  628. }
  629. /**
  630. * Downloads a blob in the browser
  631. * @param blob defines the blob to download
  632. * @param fileName defines the name of the downloaded file
  633. */
  634. public static Download(blob: Blob, fileName: string): void {
  635. if (navigator && navigator.msSaveBlob) {
  636. navigator.msSaveBlob(blob, fileName);
  637. return;
  638. }
  639. var url = window.URL.createObjectURL(blob);
  640. var a = document.createElement("a");
  641. document.body.appendChild(a);
  642. a.style.display = "none";
  643. a.href = url;
  644. a.download = fileName;
  645. a.addEventListener("click", () => {
  646. if (a.parentElement) {
  647. a.parentElement.removeChild(a);
  648. }
  649. });
  650. a.click();
  651. window.URL.revokeObjectURL(url);
  652. }
  653. /**
  654. * Captures a screenshot of the current rendering
  655. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  656. * @param engine defines the rendering engine
  657. * @param camera defines the source camera
  658. * @param size This parameter can be set to a single number or to an object with the
  659. * following (optional) properties: precision, width, height. If a single number is passed,
  660. * it will be used for both width and height. If an object is passed, the screenshot size
  661. * will be derived from the parameters. The precision property is a multiplier allowing
  662. * rendering at a higher or lower resolution
  663. * @param successCallback defines the callback receives a single parameter which contains the
  664. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  665. * src parameter of an <img> to display it
  666. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  667. * Check your browser for supported MIME types
  668. */
  669. public static CreateScreenshot(engine: Engine, camera: Camera, size: IScreenshotSize | number, successCallback?: (data: string) => void, mimeType: string = "image/png"): void {
  670. throw _DevTools.WarnImport("ScreenshotTools");
  671. }
  672. /**
  673. * Captures a screenshot of the current rendering
  674. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  675. * @param engine defines the rendering engine
  676. * @param camera defines the source camera
  677. * @param size This parameter can be set to a single number or to an object with the
  678. * following (optional) properties: precision, width, height. If a single number is passed,
  679. * it will be used for both width and height. If an object is passed, the screenshot size
  680. * will be derived from the parameters. The precision property is a multiplier allowing
  681. * rendering at a higher or lower resolution
  682. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  683. * Check your browser for supported MIME types
  684. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  685. * to the src parameter of an <img> to display it
  686. */
  687. public static CreateScreenshotAsync(engine: Engine, camera: Camera, size: IScreenshotSize | number, mimeType: string = "image/png"): Promise<string> {
  688. throw _DevTools.WarnImport("ScreenshotTools");
  689. }
  690. /**
  691. * Generates an image screenshot from the specified camera.
  692. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  693. * @param engine The engine to use for rendering
  694. * @param camera The camera to use for rendering
  695. * @param size This parameter can be set to a single number or to an object with the
  696. * following (optional) properties: precision, width, height. If a single number is passed,
  697. * it will be used for both width and height. If an object is passed, the screenshot size
  698. * will be derived from the parameters. The precision property is a multiplier allowing
  699. * rendering at a higher or lower resolution
  700. * @param successCallback The callback receives a single parameter which contains the
  701. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  702. * src parameter of an <img> to display it
  703. * @param mimeType The MIME type of the screenshot image (default: image/png).
  704. * Check your browser for supported MIME types
  705. * @param samples Texture samples (default: 1)
  706. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  707. * @param fileName A name for for the downloaded file.
  708. */
  709. public static CreateScreenshotUsingRenderTarget(engine: Engine, camera: Camera, size: IScreenshotSize | number, successCallback?: (data: string) => void, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string): void {
  710. throw _DevTools.WarnImport("ScreenshotTools");
  711. }
  712. /**
  713. * Generates an image screenshot from the specified camera.
  714. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  715. * @param engine The engine to use for rendering
  716. * @param camera The camera to use for rendering
  717. * @param size This parameter can be set to a single number or to an object with the
  718. * following (optional) properties: precision, width, height. If a single number is passed,
  719. * it will be used for both width and height. If an object is passed, the screenshot size
  720. * will be derived from the parameters. The precision property is a multiplier allowing
  721. * rendering at a higher or lower resolution
  722. * @param mimeType The MIME type of the screenshot image (default: image/png).
  723. * Check your browser for supported MIME types
  724. * @param samples Texture samples (default: 1)
  725. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  726. * @param fileName A name for for the downloaded file.
  727. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  728. * to the src parameter of an <img> to display it
  729. */
  730. public static CreateScreenshotUsingRenderTargetAsync(engine: Engine, camera: Camera, size: IScreenshotSize | number, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string): Promise<string> {
  731. throw _DevTools.WarnImport("ScreenshotTools");
  732. }
  733. /**
  734. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  735. * Be aware Math.random() could cause collisions, but:
  736. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  737. * @returns a pseudo random id
  738. */
  739. public static RandomId(): string {
  740. return GUID.RandomId();
  741. }
  742. /**
  743. * Test if the given uri is a base64 string
  744. * @param uri The uri to test
  745. * @return True if the uri is a base64 string or false otherwise
  746. */
  747. public static IsBase64(uri: string): boolean {
  748. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  749. }
  750. /**
  751. * Decode the given base64 uri.
  752. * @param uri The uri to decode
  753. * @return The decoded base64 data.
  754. */
  755. public static DecodeBase64(uri: string): ArrayBuffer {
  756. const decodedString = atob(uri.split(",")[1]);
  757. const bufferLength = decodedString.length;
  758. const bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  759. for (let i = 0; i < bufferLength; i++) {
  760. bufferView[i] = decodedString.charCodeAt(i);
  761. }
  762. return bufferView.buffer;
  763. }
  764. /**
  765. * Gets the absolute url.
  766. * @param url the input url
  767. * @return the absolute url
  768. */
  769. public static GetAbsoluteUrl(url: string): string {
  770. const a = document.createElement("a");
  771. a.href = url;
  772. return a.href;
  773. }
  774. // Logs
  775. /**
  776. * No log
  777. */
  778. public static readonly NoneLogLevel = Logger.NoneLogLevel;
  779. /**
  780. * Only message logs
  781. */
  782. public static readonly MessageLogLevel = Logger.MessageLogLevel;
  783. /**
  784. * Only warning logs
  785. */
  786. public static readonly WarningLogLevel = Logger.WarningLogLevel;
  787. /**
  788. * Only error logs
  789. */
  790. public static readonly ErrorLogLevel = Logger.ErrorLogLevel;
  791. /**
  792. * All logs
  793. */
  794. public static readonly AllLogLevel = Logger.AllLogLevel;
  795. /**
  796. * Gets a value indicating the number of loading errors
  797. * @ignorenaming
  798. */
  799. public static get errorsCount(): number {
  800. return Logger.errorsCount;
  801. }
  802. /**
  803. * Callback called when a new log is added
  804. */
  805. public static OnNewCacheEntry: (entry: string) => void;
  806. /**
  807. * Log a message to the console
  808. * @param message defines the message to log
  809. */
  810. public static Log(message: string): void {
  811. Logger.Log(message);
  812. }
  813. /**
  814. * Write a warning message to the console
  815. * @param message defines the message to log
  816. */
  817. public static Warn(message: string): void {
  818. Logger.Warn(message);
  819. }
  820. /**
  821. * Write an error message to the console
  822. * @param message defines the message to log
  823. */
  824. public static Error(message: string): void {
  825. Logger.Error(message);
  826. }
  827. /**
  828. * Gets current log cache (list of logs)
  829. */
  830. public static get LogCache(): string {
  831. return Logger.LogCache;
  832. }
  833. /**
  834. * Clears the log cache
  835. */
  836. public static ClearLogCache(): void {
  837. Logger.ClearLogCache();
  838. }
  839. /**
  840. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  841. */
  842. public static set LogLevels(level: number) {
  843. Logger.LogLevels = level;
  844. }
  845. /**
  846. * Checks if the window object exists
  847. * Back Compat only, please use DomManagement.IsWindowObjectExist instead.
  848. */
  849. public static IsWindowObjectExist = DomManagement.IsWindowObjectExist;
  850. // Performances
  851. /**
  852. * No performance log
  853. */
  854. public static readonly PerformanceNoneLogLevel = 0;
  855. /**
  856. * Use user marks to log performance
  857. */
  858. public static readonly PerformanceUserMarkLogLevel = 1;
  859. /**
  860. * Log performance to the console
  861. */
  862. public static readonly PerformanceConsoleLogLevel = 2;
  863. private static _performance: Performance;
  864. /**
  865. * Sets the current performance log level
  866. */
  867. public static set PerformanceLogLevel(level: number) {
  868. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  869. Tools.StartPerformanceCounter = Tools._StartUserMark;
  870. Tools.EndPerformanceCounter = Tools._EndUserMark;
  871. return;
  872. }
  873. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  874. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  875. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  876. return;
  877. }
  878. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  879. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  880. }
  881. private static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  882. }
  883. private static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  884. }
  885. private static _StartUserMark(counterName: string, condition = true): void {
  886. if (!Tools._performance) {
  887. if (!DomManagement.IsWindowObjectExist()) {
  888. return;
  889. }
  890. Tools._performance = window.performance;
  891. }
  892. if (!condition || !Tools._performance.mark) {
  893. return;
  894. }
  895. Tools._performance.mark(counterName + "-Begin");
  896. }
  897. private static _EndUserMark(counterName: string, condition = true): void {
  898. if (!condition || !Tools._performance.mark) {
  899. return;
  900. }
  901. Tools._performance.mark(counterName + "-End");
  902. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  903. }
  904. private static _StartPerformanceConsole(counterName: string, condition = true): void {
  905. if (!condition) {
  906. return;
  907. }
  908. Tools._StartUserMark(counterName, condition);
  909. if (console.time) {
  910. console.time(counterName);
  911. }
  912. }
  913. private static _EndPerformanceConsole(counterName: string, condition = true): void {
  914. if (!condition) {
  915. return;
  916. }
  917. Tools._EndUserMark(counterName, condition);
  918. if (console.time) {
  919. console.timeEnd(counterName);
  920. }
  921. }
  922. /**
  923. * Starts a performance counter
  924. */
  925. public static StartPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._StartPerformanceCounterDisabled;
  926. /**
  927. * Ends a specific performance coutner
  928. */
  929. public static EndPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._EndPerformanceCounterDisabled;
  930. /**
  931. * Gets either window.performance.now() if supported or Date.now() else
  932. */
  933. public static get Now(): number {
  934. return PrecisionDate.Now;
  935. }
  936. /**
  937. * This method will return the name of the class used to create the instance of the given object.
  938. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  939. * @param object the object to get the class name from
  940. * @param isType defines if the object is actually a type
  941. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  942. */
  943. public static GetClassName(object: any, isType: boolean = false): string {
  944. let name = null;
  945. if (!isType && object.getClassName) {
  946. name = object.getClassName();
  947. } else {
  948. if (object instanceof Object) {
  949. let classObj = isType ? object : Object.getPrototypeOf(object);
  950. name = classObj.constructor["__bjsclassName__"];
  951. }
  952. if (!name) {
  953. name = typeof object;
  954. }
  955. }
  956. return name;
  957. }
  958. /**
  959. * Gets the first element of an array satisfying a given predicate
  960. * @param array defines the array to browse
  961. * @param predicate defines the predicate to use
  962. * @returns null if not found or the element
  963. */
  964. public static First<T>(array: Array<T>, predicate: (item: T) => boolean): Nullable<T> {
  965. for (let el of array) {
  966. if (predicate(el)) {
  967. return el;
  968. }
  969. }
  970. return null;
  971. }
  972. /**
  973. * This method will return the name of the full name of the class, including its owning module (if any).
  974. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  975. * @param object the object to get the class name from
  976. * @param isType defines if the object is actually a type
  977. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  978. * @ignorenaming
  979. */
  980. public static getFullClassName(object: any, isType: boolean = false): Nullable<string> {
  981. let className = null;
  982. let moduleName = null;
  983. if (!isType && object.getClassName) {
  984. className = object.getClassName();
  985. } else {
  986. if (object instanceof Object) {
  987. let classObj = isType ? object : Object.getPrototypeOf(object);
  988. className = classObj.constructor["__bjsclassName__"];
  989. moduleName = classObj.constructor["__bjsmoduleName__"];
  990. }
  991. if (!className) {
  992. className = typeof object;
  993. }
  994. }
  995. if (!className) {
  996. return null;
  997. }
  998. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  999. }
  1000. /**
  1001. * Returns a promise that resolves after the given amount of time.
  1002. * @param delay Number of milliseconds to delay
  1003. * @returns Promise that resolves after the given amount of time
  1004. */
  1005. public static DelayAsync(delay: number): Promise<void> {
  1006. return new Promise((resolve) => {
  1007. setTimeout(() => {
  1008. resolve();
  1009. }, delay);
  1010. });
  1011. }
  1012. }
  1013. /**
  1014. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  1015. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  1016. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  1017. * @param name The name of the class, case should be preserved
  1018. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  1019. */
  1020. export function className(name: string, module?: string): (target: Object) => void {
  1021. return (target: Object) => {
  1022. (<any>target)["__bjsclassName__"] = name;
  1023. (<any>target)["__bjsmoduleName__"] = (module != null) ? module : null;
  1024. };
  1025. }
  1026. /**
  1027. * An implementation of a loop for asynchronous functions.
  1028. */
  1029. export class AsyncLoop {
  1030. /**
  1031. * Defines the current index of the loop.
  1032. */
  1033. public index: number;
  1034. private _done: boolean;
  1035. private _fn: (asyncLoop: AsyncLoop) => void;
  1036. private _successCallback: () => void;
  1037. /**
  1038. * Constructor.
  1039. * @param iterations the number of iterations.
  1040. * @param func the function to run each iteration
  1041. * @param successCallback the callback that will be called upon succesful execution
  1042. * @param offset starting offset.
  1043. */
  1044. constructor(
  1045. /**
  1046. * Defines the number of iterations for the loop
  1047. */
  1048. public iterations: number,
  1049. func: (asyncLoop: AsyncLoop) => void,
  1050. successCallback: () => void,
  1051. offset: number = 0) {
  1052. this.index = offset - 1;
  1053. this._done = false;
  1054. this._fn = func;
  1055. this._successCallback = successCallback;
  1056. }
  1057. /**
  1058. * Execute the next iteration. Must be called after the last iteration was finished.
  1059. */
  1060. public executeNext(): void {
  1061. if (!this._done) {
  1062. if (this.index + 1 < this.iterations) {
  1063. ++this.index;
  1064. this._fn(this);
  1065. } else {
  1066. this.breakLoop();
  1067. }
  1068. }
  1069. }
  1070. /**
  1071. * Break the loop and run the success callback.
  1072. */
  1073. public breakLoop(): void {
  1074. this._done = true;
  1075. this._successCallback();
  1076. }
  1077. /**
  1078. * Create and run an async loop.
  1079. * @param iterations the number of iterations.
  1080. * @param fn the function to run each iteration
  1081. * @param successCallback the callback that will be called upon succesful execution
  1082. * @param offset starting offset.
  1083. * @returns the created async loop object
  1084. */
  1085. public static Run(iterations: number, fn: (asyncLoop: AsyncLoop) => void, successCallback: () => void, offset: number = 0): AsyncLoop {
  1086. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  1087. loop.executeNext();
  1088. return loop;
  1089. }
  1090. /**
  1091. * A for-loop that will run a given number of iterations synchronous and the rest async.
  1092. * @param iterations total number of iterations
  1093. * @param syncedIterations number of synchronous iterations in each async iteration.
  1094. * @param fn the function to call each iteration.
  1095. * @param callback a success call back that will be called when iterating stops.
  1096. * @param breakFunction a break condition (optional)
  1097. * @param timeout timeout settings for the setTimeout function. default - 0.
  1098. * @returns the created async loop object
  1099. */
  1100. public static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout: number = 0): AsyncLoop {
  1101. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop: AsyncLoop) => {
  1102. if (breakFunction && breakFunction()) { loop.breakLoop(); }
  1103. else {
  1104. setTimeout(() => {
  1105. for (var i = 0; i < syncedIterations; ++i) {
  1106. var iteration = (loop.index * syncedIterations) + i;
  1107. if (iteration >= iterations) { break; }
  1108. fn(iteration);
  1109. if (breakFunction && breakFunction()) {
  1110. loop.breakLoop();
  1111. break;
  1112. }
  1113. }
  1114. loop.executeNext();
  1115. }, timeout);
  1116. }
  1117. }, callback);
  1118. }
  1119. }
  1120. // Will only be define if Tools is imported freeing up some space when only engine is required
  1121. EngineStore.FallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  1122. // Register promise fallback for IE
  1123. PromisePolyfill.Apply();