tools.ts 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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. * @returns the HTMLImageElement of the loaded image
  313. */
  314. public static LoadImage(input: string | ArrayBuffer | Blob, onLoad: (img: HTMLImageElement) => void, onError: (message?: string, exception?: any) => void, offlineProvider: Nullable<IOfflineProvider>): HTMLImageElement {
  315. return FileTools.LoadImage(input, onLoad, onError, offlineProvider);
  316. }
  317. /**
  318. * Loads a file
  319. * @param url url string, ArrayBuffer, or Blob to load
  320. * @param onSuccess callback called when the file successfully loads
  321. * @param onProgress callback called while file is loading (if the server supports this mode)
  322. * @param offlineProvider defines the offline provider for caching
  323. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  324. * @param onError callback called when the file fails to load
  325. * @returns a file request object
  326. */
  327. 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 {
  328. return FileTools.LoadFile(url, onSuccess, onProgress, offlineProvider, useArrayBuffer, onError);
  329. }
  330. /**
  331. * Loads a file from a url
  332. * @param url the file url to load
  333. * @returns a promise containing an ArrayBuffer corrisponding to the loaded file
  334. */
  335. public static LoadFileAsync(url: string): Promise<ArrayBuffer> {
  336. return new Promise((resolve, reject) => {
  337. FileTools.LoadFile(url, (data) => {
  338. resolve(data as ArrayBuffer);
  339. }, undefined, undefined, true, (request, exception) => {
  340. reject(exception);
  341. });
  342. });
  343. }
  344. /**
  345. * Load a script (identified by an url). When the url returns, the
  346. * content of this file is added into a new script element, attached to the DOM (body element)
  347. * @param scriptUrl defines the url of the script to laod
  348. * @param onSuccess defines the callback called when the script is loaded
  349. * @param onError defines the callback to call if an error occurs
  350. * @param scriptId defines the id of the script element
  351. */
  352. public static LoadScript(scriptUrl: string, onSuccess: () => void, onError?: (message?: string, exception?: any) => void, scriptId?: string) {
  353. if (!DomManagement.IsWindowObjectExist()) {
  354. return;
  355. }
  356. var head = document.getElementsByTagName('head')[0];
  357. var script = document.createElement('script');
  358. script.setAttribute('type', 'text/javascript');
  359. script.setAttribute('src', scriptUrl);
  360. if (scriptId) {
  361. script.id = scriptId;
  362. }
  363. script.onload = () => {
  364. if (onSuccess) {
  365. onSuccess();
  366. }
  367. };
  368. script.onerror = (e) => {
  369. if (onError) {
  370. onError(`Unable to load script '${scriptUrl}'`, e);
  371. }
  372. };
  373. head.appendChild(script);
  374. }
  375. /**
  376. * Load an asynchronous script (identified by an url). When the url returns, the
  377. * content of this file is added into a new script element, attached to the DOM (body element)
  378. * @param scriptUrl defines the url of the script to laod
  379. * @param scriptId defines the id of the script element
  380. * @returns a promise request object
  381. */
  382. public static LoadScriptAsync(scriptUrl: string, scriptId?: string): Promise<boolean> {
  383. return new Promise<boolean>((resolve, reject) => {
  384. if (!DomManagement.IsWindowObjectExist()) {
  385. resolve(false);
  386. return;
  387. }
  388. var head = document.getElementsByTagName('head')[0];
  389. var script = document.createElement('script');
  390. script.setAttribute('type', 'text/javascript');
  391. script.setAttribute('src', scriptUrl);
  392. if (scriptId) {
  393. script.id = scriptId;
  394. }
  395. script.onload = () => {
  396. resolve(true);
  397. };
  398. script.onerror = (e) => {
  399. resolve(false);
  400. };
  401. head.appendChild(script);
  402. });
  403. }
  404. /**
  405. * Loads a file from a blob
  406. * @param fileToLoad defines the blob to use
  407. * @param callback defines the callback to call when data is loaded
  408. * @param progressCallback defines the callback to call during loading process
  409. * @returns a file request object
  410. */
  411. public static ReadFileAsDataURL(fileToLoad: Blob, callback: (data: any) => void, progressCallback: (ev: ProgressEvent) => any): IFileRequest {
  412. let reader = new FileReader();
  413. let request: IFileRequest = {
  414. onCompleteObservable: new Observable<IFileRequest>(),
  415. abort: () => reader.abort(),
  416. };
  417. reader.onloadend = (e) => {
  418. request.onCompleteObservable.notifyObservers(request);
  419. };
  420. reader.onload = (e) => {
  421. //target doesn't have result from ts 1.3
  422. callback((<any>e.target)['result']);
  423. };
  424. reader.onprogress = progressCallback;
  425. reader.readAsDataURL(fileToLoad);
  426. return request;
  427. }
  428. /**
  429. * Loads a file
  430. * @param fileToLoad defines the file to load
  431. * @param callback defines the callback to call when data is loaded
  432. * @param progressCallBack defines the callback to call during loading process
  433. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  434. * @returns a file request object
  435. */
  436. public static ReadFile(fileToLoad: File, callback: (data: any) => void, progressCallBack?: (ev: ProgressEvent) => any, useArrayBuffer?: boolean): IFileRequest {
  437. return FileTools.ReadFile(fileToLoad, callback, progressCallBack, useArrayBuffer);
  438. }
  439. /**
  440. * Creates a data url from a given string content
  441. * @param content defines the content to convert
  442. * @returns the new data url link
  443. */
  444. public static FileAsURL(content: string): string {
  445. var fileBlob = new Blob([content]);
  446. var url = window.URL || window.webkitURL;
  447. var link: string = url.createObjectURL(fileBlob);
  448. return link;
  449. }
  450. /**
  451. * Format the given number to a specific decimal format
  452. * @param value defines the number to format
  453. * @param decimals defines the number of decimals to use
  454. * @returns the formatted string
  455. */
  456. public static Format(value: number, decimals: number = 2): string {
  457. return value.toFixed(decimals);
  458. }
  459. /**
  460. * Tries to copy an object by duplicating every property
  461. * @param source defines the source object
  462. * @param destination defines the target object
  463. * @param doNotCopyList defines a list of properties to avoid
  464. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  465. */
  466. public static DeepCopy(source: any, destination: any, doNotCopyList?: string[], mustCopyList?: string[]): void {
  467. DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList);
  468. }
  469. /**
  470. * Gets a boolean indicating if the given object has no own property
  471. * @param obj defines the object to test
  472. * @returns true if object has no own property
  473. */
  474. public static IsEmpty(obj: any): boolean {
  475. for (var i in obj) {
  476. if (obj.hasOwnProperty(i)) {
  477. return false;
  478. }
  479. }
  480. return true;
  481. }
  482. /**
  483. * Function used to register events at window level
  484. * @param windowElement defines the Window object to use
  485. * @param events defines the events to register
  486. */
  487. public static RegisterTopRootEvents(windowElement: Window, events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  488. for (var index = 0; index < events.length; index++) {
  489. var event = events[index];
  490. windowElement.addEventListener(event.name, <any>event.handler, false);
  491. try {
  492. if (window.parent) {
  493. window.parent.addEventListener(event.name, <any>event.handler, false);
  494. }
  495. } catch (e) {
  496. // Silently fails...
  497. }
  498. }
  499. }
  500. /**
  501. * Function used to unregister events from window level
  502. * @param windowElement defines the Window object to use
  503. * @param events defines the events to unregister
  504. */
  505. public static UnregisterTopRootEvents(windowElement: Window, events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  506. for (var index = 0; index < events.length; index++) {
  507. var event = events[index];
  508. windowElement.removeEventListener(event.name, <any>event.handler);
  509. try {
  510. if (windowElement.parent) {
  511. windowElement.parent.removeEventListener(event.name, <any>event.handler);
  512. }
  513. } catch (e) {
  514. // Silently fails...
  515. }
  516. }
  517. }
  518. /**
  519. * @ignore
  520. */
  521. public static _ScreenshotCanvas: HTMLCanvasElement;
  522. /**
  523. * Dumps the current bound framebuffer
  524. * @param width defines the rendering width
  525. * @param height defines the rendering height
  526. * @param engine defines the hosting engine
  527. * @param successCallback defines the callback triggered once the data are available
  528. * @param mimeType defines the mime type of the result
  529. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  530. */
  531. public static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string): void {
  532. // Read the contents of the framebuffer
  533. var numberOfChannelsByLine = width * 4;
  534. var halfHeight = height / 2;
  535. //Reading datas from WebGL
  536. var data = engine.readPixels(0, 0, width, height);
  537. //To flip image on Y axis.
  538. for (var i = 0; i < halfHeight; i++) {
  539. for (var j = 0; j < numberOfChannelsByLine; j++) {
  540. var currentCell = j + i * numberOfChannelsByLine;
  541. var targetLine = height - i - 1;
  542. var targetCell = j + targetLine * numberOfChannelsByLine;
  543. var temp = data[currentCell];
  544. data[currentCell] = data[targetCell];
  545. data[targetCell] = temp;
  546. }
  547. }
  548. // Create a 2D canvas to store the result
  549. if (!Tools._ScreenshotCanvas) {
  550. Tools._ScreenshotCanvas = document.createElement('canvas');
  551. }
  552. Tools._ScreenshotCanvas.width = width;
  553. Tools._ScreenshotCanvas.height = height;
  554. var context = Tools._ScreenshotCanvas.getContext('2d');
  555. if (context) {
  556. // Copy the pixels to a 2D canvas
  557. var imageData = context.createImageData(width, height);
  558. var castData = <any>(imageData.data);
  559. castData.set(data);
  560. context.putImageData(imageData, 0, 0);
  561. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  562. }
  563. }
  564. /**
  565. * Converts the canvas data to blob.
  566. * This acts as a polyfill for browsers not supporting the to blob function.
  567. * @param canvas Defines the canvas to extract the data from
  568. * @param successCallback Defines the callback triggered once the data are available
  569. * @param mimeType Defines the mime type of the result
  570. */
  571. static ToBlob(canvas: HTMLCanvasElement, successCallback: (blob: Nullable<Blob>) => void, mimeType: string = "image/png"): void {
  572. // We need HTMLCanvasElement.toBlob for HD screenshots
  573. if (!canvas.toBlob) {
  574. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  575. canvas.toBlob = function(callback, type, quality) {
  576. setTimeout(() => {
  577. var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
  578. len = binStr.length,
  579. arr = new Uint8Array(len);
  580. for (var i = 0; i < len; i++) {
  581. arr[i] = binStr.charCodeAt(i);
  582. }
  583. callback(new Blob([arr]));
  584. });
  585. };
  586. }
  587. canvas.toBlob(function(blob) {
  588. successCallback(blob);
  589. }, mimeType);
  590. }
  591. /**
  592. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  593. * @param successCallback defines the callback triggered once the data are available
  594. * @param mimeType defines the mime type of the result
  595. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  596. */
  597. static EncodeScreenshotCanvasData(successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string): void {
  598. if (successCallback) {
  599. var base64Image = Tools._ScreenshotCanvas.toDataURL(mimeType);
  600. successCallback(base64Image);
  601. }
  602. else {
  603. this.ToBlob(Tools._ScreenshotCanvas, function(blob) {
  604. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  605. if (("download" in document.createElement("a"))) {
  606. if (!fileName) {
  607. var date = new Date();
  608. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  609. fileName = "screenshot_" + stringDate + ".png";
  610. }
  611. Tools.Download(blob!, fileName);
  612. }
  613. else {
  614. var url = URL.createObjectURL(blob);
  615. var newWindow = window.open("");
  616. if (!newWindow) { return; }
  617. var img = newWindow.document.createElement("img");
  618. img.onload = function() {
  619. // no longer need to read the blob so it's revoked
  620. URL.revokeObjectURL(url);
  621. };
  622. img.src = url;
  623. newWindow.document.body.appendChild(img);
  624. }
  625. }, mimeType);
  626. }
  627. }
  628. /**
  629. * Downloads a blob in the browser
  630. * @param blob defines the blob to download
  631. * @param fileName defines the name of the downloaded file
  632. */
  633. public static Download(blob: Blob, fileName: string): void {
  634. if (navigator && navigator.msSaveBlob) {
  635. navigator.msSaveBlob(blob, fileName);
  636. return;
  637. }
  638. var url = window.URL.createObjectURL(blob);
  639. var a = document.createElement("a");
  640. document.body.appendChild(a);
  641. a.style.display = "none";
  642. a.href = url;
  643. a.download = fileName;
  644. a.addEventListener("click", () => {
  645. if (a.parentElement) {
  646. a.parentElement.removeChild(a);
  647. }
  648. });
  649. a.click();
  650. window.URL.revokeObjectURL(url);
  651. }
  652. /**
  653. * Captures a screenshot of the current rendering
  654. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  655. * @param engine defines the rendering engine
  656. * @param camera defines the source camera
  657. * @param size This parameter can be set to a single number or to an object with the
  658. * following (optional) properties: precision, width, height. If a single number is passed,
  659. * it will be used for both width and height. If an object is passed, the screenshot size
  660. * will be derived from the parameters. The precision property is a multiplier allowing
  661. * rendering at a higher or lower resolution
  662. * @param successCallback defines the callback receives a single parameter which contains the
  663. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  664. * src parameter of an <img> to display it
  665. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  666. * Check your browser for supported MIME types
  667. */
  668. public static CreateScreenshot(engine: Engine, camera: Camera, size: IScreenshotSize | number, successCallback?: (data: string) => void, mimeType: string = "image/png"): void {
  669. throw _DevTools.WarnImport("ScreenshotTools");
  670. }
  671. /**
  672. * Captures a screenshot of the current rendering
  673. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  674. * @param engine defines the rendering engine
  675. * @param camera defines the source camera
  676. * @param size This parameter can be set to a single number or to an object with the
  677. * following (optional) properties: precision, width, height. If a single number is passed,
  678. * it will be used for both width and height. If an object is passed, the screenshot size
  679. * will be derived from the parameters. The precision property is a multiplier allowing
  680. * rendering at a higher or lower resolution
  681. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  682. * Check your browser for supported MIME types
  683. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  684. * to the src parameter of an <img> to display it
  685. */
  686. public static CreateScreenshotAsync(engine: Engine, camera: Camera, size: IScreenshotSize | number, mimeType: string = "image/png"): Promise<string> {
  687. throw _DevTools.WarnImport("ScreenshotTools");
  688. }
  689. /**
  690. * Generates an image screenshot from the specified camera.
  691. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  692. * @param engine The engine to use for rendering
  693. * @param camera The camera to use for rendering
  694. * @param size This parameter can be set to a single number or to an object with the
  695. * following (optional) properties: precision, width, height. If a single number is passed,
  696. * it will be used for both width and height. If an object is passed, the screenshot size
  697. * will be derived from the parameters. The precision property is a multiplier allowing
  698. * rendering at a higher or lower resolution
  699. * @param successCallback The callback receives a single parameter which contains the
  700. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  701. * src parameter of an <img> to display it
  702. * @param mimeType The MIME type of the screenshot image (default: image/png).
  703. * Check your browser for supported MIME types
  704. * @param samples Texture samples (default: 1)
  705. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  706. * @param fileName A name for for the downloaded file.
  707. */
  708. 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 {
  709. throw _DevTools.WarnImport("ScreenshotTools");
  710. }
  711. /**
  712. * Generates an image screenshot from the specified camera.
  713. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  714. * @param engine The engine to use for rendering
  715. * @param camera The camera to use for rendering
  716. * @param size This parameter can be set to a single number or to an object with the
  717. * following (optional) properties: precision, width, height. If a single number is passed,
  718. * it will be used for both width and height. If an object is passed, the screenshot size
  719. * will be derived from the parameters. The precision property is a multiplier allowing
  720. * rendering at a higher or lower resolution
  721. * @param mimeType The MIME type of the screenshot image (default: image/png).
  722. * Check your browser for supported MIME types
  723. * @param samples Texture samples (default: 1)
  724. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  725. * @param fileName A name for for the downloaded file.
  726. * @returns screenshot as a string of base64-encoded characters. This string can be assigned
  727. * to the src parameter of an <img> to display it
  728. */
  729. public static CreateScreenshotUsingRenderTargetAsync(engine: Engine, camera: Camera, size: IScreenshotSize | number, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string): Promise<string> {
  730. throw _DevTools.WarnImport("ScreenshotTools");
  731. }
  732. /**
  733. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  734. * Be aware Math.random() could cause collisions, but:
  735. * "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"
  736. * @returns a pseudo random id
  737. */
  738. public static RandomId(): string {
  739. return GUID.RandomId();
  740. }
  741. /**
  742. * Test if the given uri is a base64 string
  743. * @param uri The uri to test
  744. * @return True if the uri is a base64 string or false otherwise
  745. */
  746. public static IsBase64(uri: string): boolean {
  747. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  748. }
  749. /**
  750. * Decode the given base64 uri.
  751. * @param uri The uri to decode
  752. * @return The decoded base64 data.
  753. */
  754. public static DecodeBase64(uri: string): ArrayBuffer {
  755. const decodedString = atob(uri.split(",")[1]);
  756. const bufferLength = decodedString.length;
  757. const bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  758. for (let i = 0; i < bufferLength; i++) {
  759. bufferView[i] = decodedString.charCodeAt(i);
  760. }
  761. return bufferView.buffer;
  762. }
  763. /**
  764. * Gets the absolute url.
  765. * @param url the input url
  766. * @return the absolute url
  767. */
  768. public static GetAbsoluteUrl(url: string): string {
  769. const a = document.createElement("a");
  770. a.href = url;
  771. return a.href;
  772. }
  773. // Logs
  774. /**
  775. * No log
  776. */
  777. public static readonly NoneLogLevel = Logger.NoneLogLevel;
  778. /**
  779. * Only message logs
  780. */
  781. public static readonly MessageLogLevel = Logger.MessageLogLevel;
  782. /**
  783. * Only warning logs
  784. */
  785. public static readonly WarningLogLevel = Logger.WarningLogLevel;
  786. /**
  787. * Only error logs
  788. */
  789. public static readonly ErrorLogLevel = Logger.ErrorLogLevel;
  790. /**
  791. * All logs
  792. */
  793. public static readonly AllLogLevel = Logger.AllLogLevel;
  794. /**
  795. * Gets a value indicating the number of loading errors
  796. * @ignorenaming
  797. */
  798. public static get errorsCount(): number {
  799. return Logger.errorsCount;
  800. }
  801. /**
  802. * Callback called when a new log is added
  803. */
  804. public static OnNewCacheEntry: (entry: string) => void;
  805. /**
  806. * Log a message to the console
  807. * @param message defines the message to log
  808. */
  809. public static Log(message: string): void {
  810. Logger.Log(message);
  811. }
  812. /**
  813. * Write a warning message to the console
  814. * @param message defines the message to log
  815. */
  816. public static Warn(message: string): void {
  817. Logger.Warn(message);
  818. }
  819. /**
  820. * Write an error message to the console
  821. * @param message defines the message to log
  822. */
  823. public static Error(message: string): void {
  824. Logger.Error(message);
  825. }
  826. /**
  827. * Gets current log cache (list of logs)
  828. */
  829. public static get LogCache(): string {
  830. return Logger.LogCache;
  831. }
  832. /**
  833. * Clears the log cache
  834. */
  835. public static ClearLogCache(): void {
  836. Logger.ClearLogCache();
  837. }
  838. /**
  839. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  840. */
  841. public static set LogLevels(level: number) {
  842. Logger.LogLevels = level;
  843. }
  844. /**
  845. * Checks if the window object exists
  846. * Back Compat only, please use DomManagement.IsWindowObjectExist instead.
  847. */
  848. public static IsWindowObjectExist = DomManagement.IsWindowObjectExist;
  849. // Performances
  850. /**
  851. * No performance log
  852. */
  853. public static readonly PerformanceNoneLogLevel = 0;
  854. /**
  855. * Use user marks to log performance
  856. */
  857. public static readonly PerformanceUserMarkLogLevel = 1;
  858. /**
  859. * Log performance to the console
  860. */
  861. public static readonly PerformanceConsoleLogLevel = 2;
  862. private static _performance: Performance;
  863. /**
  864. * Sets the current performance log level
  865. */
  866. public static set PerformanceLogLevel(level: number) {
  867. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  868. Tools.StartPerformanceCounter = Tools._StartUserMark;
  869. Tools.EndPerformanceCounter = Tools._EndUserMark;
  870. return;
  871. }
  872. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  873. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  874. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  875. return;
  876. }
  877. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  878. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  879. }
  880. private static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  881. }
  882. private static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  883. }
  884. private static _StartUserMark(counterName: string, condition = true): void {
  885. if (!Tools._performance) {
  886. if (!DomManagement.IsWindowObjectExist()) {
  887. return;
  888. }
  889. Tools._performance = window.performance;
  890. }
  891. if (!condition || !Tools._performance.mark) {
  892. return;
  893. }
  894. Tools._performance.mark(counterName + "-Begin");
  895. }
  896. private static _EndUserMark(counterName: string, condition = true): void {
  897. if (!condition || !Tools._performance.mark) {
  898. return;
  899. }
  900. Tools._performance.mark(counterName + "-End");
  901. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  902. }
  903. private static _StartPerformanceConsole(counterName: string, condition = true): void {
  904. if (!condition) {
  905. return;
  906. }
  907. Tools._StartUserMark(counterName, condition);
  908. if (console.time) {
  909. console.time(counterName);
  910. }
  911. }
  912. private static _EndPerformanceConsole(counterName: string, condition = true): void {
  913. if (!condition) {
  914. return;
  915. }
  916. Tools._EndUserMark(counterName, condition);
  917. if (console.time) {
  918. console.timeEnd(counterName);
  919. }
  920. }
  921. /**
  922. * Starts a performance counter
  923. */
  924. public static StartPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._StartPerformanceCounterDisabled;
  925. /**
  926. * Ends a specific performance coutner
  927. */
  928. public static EndPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._EndPerformanceCounterDisabled;
  929. /**
  930. * Gets either window.performance.now() if supported or Date.now() else
  931. */
  932. public static get Now(): number {
  933. return PrecisionDate.Now;
  934. }
  935. /**
  936. * This method will return the name of the class used to create the instance of the given object.
  937. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  938. * @param object the object to get the class name from
  939. * @param isType defines if the object is actually a type
  940. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  941. */
  942. public static GetClassName(object: any, isType: boolean = false): string {
  943. let name = null;
  944. if (!isType && object.getClassName) {
  945. name = object.getClassName();
  946. } else {
  947. if (object instanceof Object) {
  948. let classObj = isType ? object : Object.getPrototypeOf(object);
  949. name = classObj.constructor["__bjsclassName__"];
  950. }
  951. if (!name) {
  952. name = typeof object;
  953. }
  954. }
  955. return name;
  956. }
  957. /**
  958. * Gets the first element of an array satisfying a given predicate
  959. * @param array defines the array to browse
  960. * @param predicate defines the predicate to use
  961. * @returns null if not found or the element
  962. */
  963. public static First<T>(array: Array<T>, predicate: (item: T) => boolean): Nullable<T> {
  964. for (let el of array) {
  965. if (predicate(el)) {
  966. return el;
  967. }
  968. }
  969. return null;
  970. }
  971. /**
  972. * This method will return the name of the full name of the class, including its owning module (if any).
  973. * 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).
  974. * @param object the object to get the class name from
  975. * @param isType defines if the object is actually a type
  976. * @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.
  977. * @ignorenaming
  978. */
  979. public static getFullClassName(object: any, isType: boolean = false): Nullable<string> {
  980. let className = null;
  981. let moduleName = null;
  982. if (!isType && object.getClassName) {
  983. className = object.getClassName();
  984. } else {
  985. if (object instanceof Object) {
  986. let classObj = isType ? object : Object.getPrototypeOf(object);
  987. className = classObj.constructor["__bjsclassName__"];
  988. moduleName = classObj.constructor["__bjsmoduleName__"];
  989. }
  990. if (!className) {
  991. className = typeof object;
  992. }
  993. }
  994. if (!className) {
  995. return null;
  996. }
  997. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  998. }
  999. /**
  1000. * Returns a promise that resolves after the given amount of time.
  1001. * @param delay Number of milliseconds to delay
  1002. * @returns Promise that resolves after the given amount of time
  1003. */
  1004. public static DelayAsync(delay: number): Promise<void> {
  1005. return new Promise((resolve) => {
  1006. setTimeout(() => {
  1007. resolve();
  1008. }, delay);
  1009. });
  1010. }
  1011. }
  1012. /**
  1013. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  1014. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  1015. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  1016. * @param name The name of the class, case should be preserved
  1017. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  1018. */
  1019. export function className(name: string, module?: string): (target: Object) => void {
  1020. return (target: Object) => {
  1021. (<any>target)["__bjsclassName__"] = name;
  1022. (<any>target)["__bjsmoduleName__"] = (module != null) ? module : null;
  1023. };
  1024. }
  1025. /**
  1026. * An implementation of a loop for asynchronous functions.
  1027. */
  1028. export class AsyncLoop {
  1029. /**
  1030. * Defines the current index of the loop.
  1031. */
  1032. public index: number;
  1033. private _done: boolean;
  1034. private _fn: (asyncLoop: AsyncLoop) => void;
  1035. private _successCallback: () => void;
  1036. /**
  1037. * Constructor.
  1038. * @param iterations the number of iterations.
  1039. * @param func the function to run each iteration
  1040. * @param successCallback the callback that will be called upon succesful execution
  1041. * @param offset starting offset.
  1042. */
  1043. constructor(
  1044. /**
  1045. * Defines the number of iterations for the loop
  1046. */
  1047. public iterations: number,
  1048. func: (asyncLoop: AsyncLoop) => void,
  1049. successCallback: () => void,
  1050. offset: number = 0) {
  1051. this.index = offset - 1;
  1052. this._done = false;
  1053. this._fn = func;
  1054. this._successCallback = successCallback;
  1055. }
  1056. /**
  1057. * Execute the next iteration. Must be called after the last iteration was finished.
  1058. */
  1059. public executeNext(): void {
  1060. if (!this._done) {
  1061. if (this.index + 1 < this.iterations) {
  1062. ++this.index;
  1063. this._fn(this);
  1064. } else {
  1065. this.breakLoop();
  1066. }
  1067. }
  1068. }
  1069. /**
  1070. * Break the loop and run the success callback.
  1071. */
  1072. public breakLoop(): void {
  1073. this._done = true;
  1074. this._successCallback();
  1075. }
  1076. /**
  1077. * Create and run an async loop.
  1078. * @param iterations the number of iterations.
  1079. * @param fn the function to run each iteration
  1080. * @param successCallback the callback that will be called upon succesful execution
  1081. * @param offset starting offset.
  1082. * @returns the created async loop object
  1083. */
  1084. public static Run(iterations: number, fn: (asyncLoop: AsyncLoop) => void, successCallback: () => void, offset: number = 0): AsyncLoop {
  1085. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  1086. loop.executeNext();
  1087. return loop;
  1088. }
  1089. /**
  1090. * A for-loop that will run a given number of iterations synchronous and the rest async.
  1091. * @param iterations total number of iterations
  1092. * @param syncedIterations number of synchronous iterations in each async iteration.
  1093. * @param fn the function to call each iteration.
  1094. * @param callback a success call back that will be called when iterating stops.
  1095. * @param breakFunction a break condition (optional)
  1096. * @param timeout timeout settings for the setTimeout function. default - 0.
  1097. * @returns the created async loop object
  1098. */
  1099. public static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout: number = 0): AsyncLoop {
  1100. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop: AsyncLoop) => {
  1101. if (breakFunction && breakFunction()) { loop.breakLoop(); }
  1102. else {
  1103. setTimeout(() => {
  1104. for (var i = 0; i < syncedIterations; ++i) {
  1105. var iteration = (loop.index * syncedIterations) + i;
  1106. if (iteration >= iterations) { break; }
  1107. fn(iteration);
  1108. if (breakFunction && breakFunction()) {
  1109. loop.breakLoop();
  1110. break;
  1111. }
  1112. }
  1113. loop.executeNext();
  1114. }, timeout);
  1115. }
  1116. }, callback);
  1117. }
  1118. }
  1119. // Will only be define if Tools is imported freeing up some space when only engine is required
  1120. 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";
  1121. // Register promise fallback for IE
  1122. PromisePolyfill.Apply();