tools.ts 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068
  1. import { FloatArray, IndicesArray, Nullable } from "../types";
  2. import { Color4, Color3, Vector2, Vector3 } from "../Maths/math";
  3. import { Scalar } from "../Maths/math.scalar";
  4. import { IOfflineProvider } from "../Offline/IOfflineProvider";
  5. import { Observable } from "./observable";
  6. import { FilesInputStore } from "./filesInputStore";
  7. import { Constants } from "../Engines/constants";
  8. import { DomManagement } from "./domManagement";
  9. import { Logger } from "./logger";
  10. import { _TypeStore } from "./typeStore";
  11. import { DeepCopier } from "./deepCopier";
  12. import { PrecisionDate } from './precisionDate';
  13. import { _DevTools } from './devTools';
  14. import { WebRequest } from './webRequest';
  15. declare type Camera = import("../Cameras/camera").Camera;
  16. declare type Engine = import("../Engines/engine").Engine;
  17. declare type Animation = import("../Animations/animation").Animation;
  18. /**
  19. * Interface for any object that can request an animation frame
  20. */
  21. export interface ICustomAnimationFrameRequester {
  22. /**
  23. * This function will be called when the render loop is ready. If this is not populated, the engine's renderloop function will be called
  24. */
  25. renderFunction?: Function;
  26. /**
  27. * Called to request the next frame to render to
  28. * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
  29. */
  30. requestAnimationFrame: Function;
  31. /**
  32. * You can pass this value to cancelAnimationFrame() to cancel the refresh callback request
  33. * @see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame#Return_value
  34. */
  35. requestID?: number;
  36. }
  37. /**
  38. * Interface containing an array of animations
  39. */
  40. export interface IAnimatable {
  41. /**
  42. * Array of animations
  43. */
  44. animations: Array<Animation>;
  45. }
  46. /** Interface used by value gradients (color, factor, ...) */
  47. export interface IValueGradient {
  48. /**
  49. * Gets or sets the gradient value (between 0 and 1)
  50. */
  51. gradient: number;
  52. }
  53. /** Class used to store color4 gradient */
  54. export class ColorGradient implements IValueGradient {
  55. /**
  56. * Gets or sets the gradient value (between 0 and 1)
  57. */
  58. public gradient: number;
  59. /**
  60. * Gets or sets first associated color
  61. */
  62. public color1: Color4;
  63. /**
  64. * Gets or sets second associated color
  65. */
  66. public color2?: Color4;
  67. /**
  68. * Will get a color picked randomly between color1 and color2.
  69. * If color2 is undefined then color1 will be used
  70. * @param result defines the target Color4 to store the result in
  71. */
  72. public getColorToRef(result: Color4) {
  73. if (!this.color2) {
  74. result.copyFrom(this.color1);
  75. return;
  76. }
  77. Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  78. }
  79. }
  80. /** Class used to store color 3 gradient */
  81. export class Color3Gradient implements IValueGradient {
  82. /**
  83. * Gets or sets the gradient value (between 0 and 1)
  84. */
  85. public gradient: number;
  86. /**
  87. * Gets or sets the associated color
  88. */
  89. public color: Color3;
  90. }
  91. /** Class used to store factor gradient */
  92. export class FactorGradient implements IValueGradient {
  93. /**
  94. * Gets or sets the gradient value (between 0 and 1)
  95. */
  96. public gradient: number;
  97. /**
  98. * Gets or sets first associated factor
  99. */
  100. public factor1: number;
  101. /**
  102. * Gets or sets second associated factor
  103. */
  104. public factor2?: number;
  105. /**
  106. * Will get a number picked randomly between factor1 and factor2.
  107. * If factor2 is undefined then factor1 will be used
  108. * @returns the picked number
  109. */
  110. public getFactor(): number {
  111. if (this.factor2 === undefined) {
  112. return this.factor1;
  113. }
  114. return Scalar.Lerp(this.factor1, this.factor2, Math.random());
  115. }
  116. }
  117. /**
  118. * @ignore
  119. * Application error to support additional information when loading a file
  120. */
  121. export class LoadFileError extends Error {
  122. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  123. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  124. // Polyfill for Object.setPrototypeOf if necessary.
  125. private static _setPrototypeOf: (o: any, proto: object | null) => any =
  126. (Object as any).setPrototypeOf || ((o, proto) => { o.__proto__ = proto; return o; });
  127. /**
  128. * Creates a new LoadFileError
  129. * @param message defines the message of the error
  130. * @param request defines the optional web request
  131. */
  132. constructor(
  133. message: string,
  134. /** defines the optional web request */
  135. public request?: WebRequest
  136. ) {
  137. super(message);
  138. this.name = "LoadFileError";
  139. LoadFileError._setPrototypeOf(this, LoadFileError.prototype);
  140. }
  141. }
  142. /**
  143. * Class used to define a retry strategy when error happens while loading assets
  144. */
  145. export class RetryStrategy {
  146. /**
  147. * Function used to defines an exponential back off strategy
  148. * @param maxRetries defines the maximum number of retries (3 by default)
  149. * @param baseInterval defines the interval between retries
  150. * @returns the strategy function to use
  151. */
  152. public static ExponentialBackoff(maxRetries = 3, baseInterval = 500) {
  153. return (url: string, request: WebRequest, retryIndex: number): number => {
  154. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  155. return -1;
  156. }
  157. return Math.pow(2, retryIndex) * baseInterval;
  158. };
  159. }
  160. }
  161. /**
  162. * File request interface
  163. */
  164. export interface IFileRequest {
  165. /**
  166. * Raised when the request is complete (success or error).
  167. */
  168. onCompleteObservable: Observable<IFileRequest>;
  169. /**
  170. * Aborts the request for a file.
  171. */
  172. abort: () => void;
  173. }
  174. /**
  175. * Class containing a set of static utilities functions
  176. */
  177. export class Tools {
  178. /**
  179. * Gets or sets the base URL to use to load assets
  180. */
  181. public static BaseUrl = "";
  182. /**
  183. * Enable/Disable Custom HTTP Request Headers globally.
  184. * default = false
  185. * @see CustomRequestHeaders
  186. */
  187. public static UseCustomRequestHeaders: boolean = false;
  188. /**
  189. * Custom HTTP Request Headers to be sent with XMLHttpRequests
  190. * i.e. when loading files, where the server/service expects an Authorization header
  191. */
  192. public static CustomRequestHeaders = WebRequest.CustomRequestHeaders;
  193. /**
  194. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  195. */
  196. public static DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  197. /**
  198. * Default behaviour for cors in the application.
  199. * It can be a string if the expected behavior is identical in the entire app.
  200. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  201. */
  202. public static CorsBehavior: string | ((url: string | string[]) => string) = "anonymous";
  203. /**
  204. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  205. * @ignorenaming
  206. */
  207. public static UseFallbackTexture = true;
  208. /**
  209. * Use this object to register external classes like custom textures or material
  210. * to allow the laoders to instantiate them
  211. */
  212. public static RegisteredExternalClasses: { [key: string]: Object } = {};
  213. /**
  214. * Texture content used if a texture cannot loaded
  215. * @ignorenaming
  216. */
  217. public static 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";
  218. /**
  219. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  220. * @param u defines the coordinate on X axis
  221. * @param v defines the coordinate on Y axis
  222. * @param width defines the width of the source data
  223. * @param height defines the height of the source data
  224. * @param pixels defines the source byte array
  225. * @param color defines the output color
  226. */
  227. public static FetchToRef(u: number, v: number, width: number, height: number, pixels: Uint8Array, color: Color4): void {
  228. let wrappedU = ((Math.abs(u) * width) % width) | 0;
  229. let wrappedV = ((Math.abs(v) * height) % height) | 0;
  230. let position = (wrappedU + wrappedV * width) * 4;
  231. color.r = pixels[position] / 255;
  232. color.g = pixels[position + 1] / 255;
  233. color.b = pixels[position + 2] / 255;
  234. color.a = pixels[position + 3] / 255;
  235. }
  236. /**
  237. * Interpolates between a and b via alpha
  238. * @param a The lower value (returned when alpha = 0)
  239. * @param b The upper value (returned when alpha = 1)
  240. * @param alpha The interpolation-factor
  241. * @return The mixed value
  242. */
  243. public static Mix(a: number, b: number, alpha: number): number {
  244. return a * (1 - alpha) + b * alpha;
  245. }
  246. /**
  247. * Tries to instantiate a new object from a given class name
  248. * @param className defines the class name to instantiate
  249. * @returns the new object or null if the system was not able to do the instantiation
  250. */
  251. public static Instantiate(className: string): any {
  252. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  253. return Tools.RegisteredExternalClasses[className];
  254. }
  255. const internalClass = _TypeStore.GetClass(className);
  256. if (internalClass) {
  257. return internalClass;
  258. }
  259. Logger.Warn(className + " not found, you may have missed an import.");
  260. var arr = className.split(".");
  261. var fn: any = (window || this);
  262. for (var i = 0, len = arr.length; i < len; i++) {
  263. fn = fn[arr[i]];
  264. }
  265. if (typeof fn !== "function") {
  266. return null;
  267. }
  268. return fn;
  269. }
  270. /**
  271. * Provides a slice function that will work even on IE
  272. * @param data defines the array to slice
  273. * @param start defines the start of the data (optional)
  274. * @param end defines the end of the data (optional)
  275. * @returns the new sliced array
  276. */
  277. public static Slice<T>(data: T, start?: number, end?: number): T {
  278. if ((data as any).slice) {
  279. return (data as any).slice(start, end);
  280. }
  281. return Array.prototype.slice.call(data, start, end);
  282. }
  283. /**
  284. * Polyfill for setImmediate
  285. * @param action defines the action to execute after the current execution block
  286. */
  287. public static SetImmediate(action: () => void) {
  288. if (DomManagement.IsWindowObjectExist() && window.setImmediate) {
  289. window.setImmediate(action);
  290. } else {
  291. setTimeout(action, 1);
  292. }
  293. }
  294. /**
  295. * Function indicating if a number is an exponent of 2
  296. * @param value defines the value to test
  297. * @returns true if the value is an exponent of 2
  298. */
  299. public static IsExponentOfTwo(value: number): boolean {
  300. var count = 1;
  301. do {
  302. count *= 2;
  303. } while (count < value);
  304. return count === value;
  305. }
  306. private static _tmpFloatArray = new Float32Array(1);
  307. /**
  308. * Returns the nearest 32-bit single precision float representation of a Number
  309. * @param value A Number. If the parameter is of a different type, it will get converted
  310. * to a number or to NaN if it cannot be converted
  311. * @returns number
  312. */
  313. public static FloatRound(value: number): number {
  314. if (Math.fround) {
  315. return Math.fround(value);
  316. }
  317. return (Tools._tmpFloatArray[0] = value);
  318. }
  319. /**
  320. * Find the next highest power of two.
  321. * @param x Number to start search from.
  322. * @return Next highest power of two.
  323. */
  324. public static CeilingPOT(x: number): number {
  325. x--;
  326. x |= x >> 1;
  327. x |= x >> 2;
  328. x |= x >> 4;
  329. x |= x >> 8;
  330. x |= x >> 16;
  331. x++;
  332. return x;
  333. }
  334. /**
  335. * Find the next lowest power of two.
  336. * @param x Number to start search from.
  337. * @return Next lowest power of two.
  338. */
  339. public static FloorPOT(x: number): number {
  340. x = x | (x >> 1);
  341. x = x | (x >> 2);
  342. x = x | (x >> 4);
  343. x = x | (x >> 8);
  344. x = x | (x >> 16);
  345. return x - (x >> 1);
  346. }
  347. /**
  348. * Find the nearest power of two.
  349. * @param x Number to start search from.
  350. * @return Next nearest power of two.
  351. */
  352. public static NearestPOT(x: number): number {
  353. var c = Tools.CeilingPOT(x);
  354. var f = Tools.FloorPOT(x);
  355. return (c - x) > (x - f) ? f : c;
  356. }
  357. /**
  358. * Get the closest exponent of two
  359. * @param value defines the value to approximate
  360. * @param max defines the maximum value to return
  361. * @param mode defines how to define the closest value
  362. * @returns closest exponent of two of the given value
  363. */
  364. public static GetExponentOfTwo(value: number, max: number, mode = Constants.SCALEMODE_NEAREST): number {
  365. let pot;
  366. switch (mode) {
  367. case Constants.SCALEMODE_FLOOR:
  368. pot = Tools.FloorPOT(value);
  369. break;
  370. case Constants.SCALEMODE_NEAREST:
  371. pot = Tools.NearestPOT(value);
  372. break;
  373. case Constants.SCALEMODE_CEILING:
  374. default:
  375. pot = Tools.CeilingPOT(value);
  376. break;
  377. }
  378. return Math.min(pot, max);
  379. }
  380. /**
  381. * Extracts the filename from a path
  382. * @param path defines the path to use
  383. * @returns the filename
  384. */
  385. public static GetFilename(path: string): string {
  386. var index = path.lastIndexOf("/");
  387. if (index < 0) {
  388. return path;
  389. }
  390. return path.substring(index + 1);
  391. }
  392. /**
  393. * Extracts the "folder" part of a path (everything before the filename).
  394. * @param uri The URI to extract the info from
  395. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  396. * @returns The "folder" part of the path
  397. */
  398. public static GetFolderPath(uri: string, returnUnchangedIfNoSlash = false): string {
  399. var index = uri.lastIndexOf("/");
  400. if (index < 0) {
  401. if (returnUnchangedIfNoSlash) {
  402. return uri;
  403. }
  404. return "";
  405. }
  406. return uri.substring(0, index + 1);
  407. }
  408. /**
  409. * Extracts text content from a DOM element hierarchy
  410. * Back Compat only, please use DomManagement.GetDOMTextContent instead.
  411. */
  412. public static GetDOMTextContent = DomManagement.GetDOMTextContent;
  413. /**
  414. * Convert an angle in radians to degrees
  415. * @param angle defines the angle to convert
  416. * @returns the angle in degrees
  417. */
  418. public static ToDegrees(angle: number): number {
  419. return angle * 180 / Math.PI;
  420. }
  421. /**
  422. * Convert an angle in degrees to radians
  423. * @param angle defines the angle to convert
  424. * @returns the angle in radians
  425. */
  426. public static ToRadians(angle: number): number {
  427. return angle * Math.PI / 180;
  428. }
  429. /**
  430. * Encode a buffer to a base64 string
  431. * @param buffer defines the buffer to encode
  432. * @returns the encoded string
  433. */
  434. public static EncodeArrayBufferTobase64(buffer: ArrayBuffer): string {
  435. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  436. var output = "";
  437. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  438. var i = 0;
  439. var bytes = new Uint8Array(buffer);
  440. while (i < bytes.length) {
  441. chr1 = bytes[i++];
  442. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  443. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  444. enc1 = chr1 >> 2;
  445. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  446. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  447. enc4 = chr3 & 63;
  448. if (isNaN(chr2)) {
  449. enc3 = enc4 = 64;
  450. } else if (isNaN(chr3)) {
  451. enc4 = 64;
  452. }
  453. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  454. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  455. }
  456. return "data:image/png;base64," + output;
  457. }
  458. /**
  459. * Extracts minimum and maximum values from a list of indexed positions
  460. * @param positions defines the positions to use
  461. * @param indices defines the indices to the positions
  462. * @param indexStart defines the start index
  463. * @param indexCount defines the end index
  464. * @param bias defines bias value to add to the result
  465. * @return minimum and maximum values
  466. */
  467. public static ExtractMinAndMaxIndexed(positions: FloatArray, indices: IndicesArray, indexStart: number, indexCount: number, bias: Nullable<Vector2> = null): { minimum: Vector3; maximum: Vector3 } {
  468. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  469. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  470. for (var index = indexStart; index < indexStart + indexCount; index++) {
  471. const offset = indices[index] * 3;
  472. const x = positions[offset];
  473. const y = positions[offset + 1];
  474. const z = positions[offset + 2];
  475. minimum.minimizeInPlaceFromFloats(x, y, z);
  476. maximum.maximizeInPlaceFromFloats(x, y, z);
  477. }
  478. if (bias) {
  479. minimum.x -= minimum.x * bias.x + bias.y;
  480. minimum.y -= minimum.y * bias.x + bias.y;
  481. minimum.z -= minimum.z * bias.x + bias.y;
  482. maximum.x += maximum.x * bias.x + bias.y;
  483. maximum.y += maximum.y * bias.x + bias.y;
  484. maximum.z += maximum.z * bias.x + bias.y;
  485. }
  486. return {
  487. minimum: minimum,
  488. maximum: maximum
  489. };
  490. }
  491. /**
  492. * Extracts minimum and maximum values from a list of positions
  493. * @param positions defines the positions to use
  494. * @param start defines the start index in the positions array
  495. * @param count defines the number of positions to handle
  496. * @param bias defines bias value to add to the result
  497. * @param stride defines the stride size to use (distance between two positions in the positions array)
  498. * @return minimum and maximum values
  499. */
  500. public static ExtractMinAndMax(positions: FloatArray, start: number, count: number, bias: Nullable<Vector2> = null, stride?: number): { minimum: Vector3; maximum: Vector3 } {
  501. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  502. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  503. if (!stride) {
  504. stride = 3;
  505. }
  506. for (var index = start, offset = start * stride; index < start + count; index++ , offset += stride) {
  507. const x = positions[offset];
  508. const y = positions[offset + 1];
  509. const z = positions[offset + 2];
  510. minimum.minimizeInPlaceFromFloats(x, y, z);
  511. maximum.maximizeInPlaceFromFloats(x, y, z);
  512. }
  513. if (bias) {
  514. minimum.x -= minimum.x * bias.x + bias.y;
  515. minimum.y -= minimum.y * bias.x + bias.y;
  516. minimum.z -= minimum.z * bias.x + bias.y;
  517. maximum.x += maximum.x * bias.x + bias.y;
  518. maximum.y += maximum.y * bias.x + bias.y;
  519. maximum.z += maximum.z * bias.x + bias.y;
  520. }
  521. return {
  522. minimum: minimum,
  523. maximum: maximum
  524. };
  525. }
  526. /**
  527. * Returns an array if obj is not an array
  528. * @param obj defines the object to evaluate as an array
  529. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  530. * @returns either obj directly if obj is an array or a new array containing obj
  531. */
  532. public static MakeArray(obj: any, allowsNullUndefined?: boolean): Nullable<Array<any>> {
  533. if (allowsNullUndefined !== true && (obj === undefined || obj == null)) {
  534. return null;
  535. }
  536. return Array.isArray(obj) ? obj : [obj];
  537. }
  538. /**
  539. * Gets the pointer prefix to use
  540. * @returns "pointer" if touch is enabled. Else returns "mouse"
  541. */
  542. public static GetPointerPrefix(): string {
  543. var eventPrefix = "pointer";
  544. // Check if pointer events are supported
  545. if (DomManagement.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  546. eventPrefix = "mouse";
  547. }
  548. return eventPrefix;
  549. }
  550. /**
  551. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  552. * @param func - the function to be called
  553. * @param requester - the object that will request the next frame. Falls back to window.
  554. * @returns frame number
  555. */
  556. public static QueueNewFrame(func: () => void, requester?: any): number {
  557. if (!DomManagement.IsWindowObjectExist()) {
  558. return setTimeout(func, 16);
  559. }
  560. if (!requester) {
  561. requester = window;
  562. }
  563. if (requester.requestAnimationFrame) {
  564. return requester.requestAnimationFrame(func);
  565. }
  566. else if (requester.msRequestAnimationFrame) {
  567. return requester.msRequestAnimationFrame(func);
  568. }
  569. else if (requester.webkitRequestAnimationFrame) {
  570. return requester.webkitRequestAnimationFrame(func);
  571. }
  572. else if (requester.mozRequestAnimationFrame) {
  573. return requester.mozRequestAnimationFrame(func);
  574. }
  575. else if (requester.oRequestAnimationFrame) {
  576. return requester.oRequestAnimationFrame(func);
  577. }
  578. else {
  579. return window.setTimeout(func, 16);
  580. }
  581. }
  582. /**
  583. * Ask the browser to promote the current element to fullscreen rendering mode
  584. * @param element defines the DOM element to promote
  585. */
  586. public static RequestFullscreen(element: HTMLElement): void {
  587. var requestFunction = element.requestFullscreen || (<any>element).msRequestFullscreen || (<any>element).webkitRequestFullscreen || (<any>element).mozRequestFullScreen;
  588. if (!requestFunction) { return; }
  589. requestFunction.call(element);
  590. }
  591. /**
  592. * Asks the browser to exit fullscreen mode
  593. */
  594. public static ExitFullscreen(): void {
  595. let anyDoc = document as any;
  596. if (document.exitFullscreen) {
  597. document.exitFullscreen();
  598. }
  599. else if (anyDoc.mozCancelFullScreen) {
  600. anyDoc.mozCancelFullScreen();
  601. }
  602. else if (anyDoc.webkitCancelFullScreen) {
  603. anyDoc.webkitCancelFullScreen();
  604. }
  605. else if (anyDoc.msCancelFullScreen) {
  606. anyDoc.msCancelFullScreen();
  607. }
  608. }
  609. /**
  610. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  611. * @param url define the url we are trying
  612. * @param element define the dom element where to configure the cors policy
  613. */
  614. public static SetCorsBehavior(url: string | string[], element: { crossOrigin: string | null }): void {
  615. if (url && url.indexOf("data:") === 0) {
  616. return;
  617. }
  618. if (Tools.CorsBehavior) {
  619. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  620. element.crossOrigin = <string>Tools.CorsBehavior;
  621. }
  622. else {
  623. var result = Tools.CorsBehavior(url);
  624. if (result) {
  625. element.crossOrigin = result;
  626. }
  627. }
  628. }
  629. }
  630. // External files
  631. /**
  632. * Removes unwanted characters from an url
  633. * @param url defines the url to clean
  634. * @returns the cleaned url
  635. */
  636. public static CleanUrl(url: string): string {
  637. url = url.replace(/#/mg, "%23");
  638. return url;
  639. }
  640. /**
  641. * Gets or sets a function used to pre-process url before using them to load assets
  642. */
  643. public static PreprocessUrl = (url: string) => {
  644. return url;
  645. }
  646. /**
  647. * Loads an image as an HTMLImageElement.
  648. * @param input url string, ArrayBuffer, or Blob to load
  649. * @param onLoad callback called when the image successfully loads
  650. * @param onError callback called when the image fails to load
  651. * @param offlineProvider offline provider for caching
  652. * @returns the HTMLImageElement of the loaded image
  653. */
  654. public static LoadImage(input: string | ArrayBuffer | Blob, onLoad: (img: HTMLImageElement) => void, onError: (message?: string, exception?: any) => void, offlineProvider: Nullable<IOfflineProvider>): HTMLImageElement {
  655. let url: string;
  656. let usingObjectURL = false;
  657. if (input instanceof ArrayBuffer) {
  658. url = URL.createObjectURL(new Blob([input]));
  659. usingObjectURL = true;
  660. }
  661. else if (input instanceof Blob) {
  662. url = URL.createObjectURL(input);
  663. usingObjectURL = true;
  664. }
  665. else {
  666. url = Tools.CleanUrl(input);
  667. url = Tools.PreprocessUrl(input);
  668. }
  669. var img = new Image();
  670. Tools.SetCorsBehavior(url, img);
  671. const loadHandler = () => {
  672. img.removeEventListener("load", loadHandler);
  673. img.removeEventListener("error", errorHandler);
  674. onLoad(img);
  675. // Must revoke the URL after calling onLoad to avoid security exceptions in
  676. // certain scenarios (e.g. when hosted in vscode).
  677. if (usingObjectURL && img.src) {
  678. URL.revokeObjectURL(img.src);
  679. }
  680. };
  681. const errorHandler = (err: any) => {
  682. img.removeEventListener("load", loadHandler);
  683. img.removeEventListener("error", errorHandler);
  684. Logger.Error("Error while trying to load image: " + input);
  685. if (onError) {
  686. onError("Error while trying to load image: " + input, err);
  687. }
  688. if (usingObjectURL && img.src) {
  689. URL.revokeObjectURL(img.src);
  690. }
  691. };
  692. img.addEventListener("load", loadHandler);
  693. img.addEventListener("error", errorHandler);
  694. var noOfflineSupport = () => {
  695. img.src = url;
  696. };
  697. var loadFromOfflineSupport = () => {
  698. if (offlineProvider) {
  699. offlineProvider.loadImage(url, img);
  700. }
  701. };
  702. if (url.substr(0, 5) !== "data:" && offlineProvider && offlineProvider.enableTexturesOffline) {
  703. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  704. }
  705. else {
  706. if (url.indexOf("file:") !== -1) {
  707. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  708. if (FilesInputStore.FilesToLoad[textureName]) {
  709. try {
  710. var blobURL;
  711. try {
  712. blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);
  713. }
  714. catch (ex) {
  715. // Chrome doesn't support oneTimeOnly parameter
  716. blobURL = URL.createObjectURL(FilesInputStore.FilesToLoad[textureName]);
  717. }
  718. img.src = blobURL;
  719. usingObjectURL = true;
  720. }
  721. catch (e) {
  722. img.src = "";
  723. }
  724. return img;
  725. }
  726. }
  727. noOfflineSupport();
  728. }
  729. return img;
  730. }
  731. /**
  732. * Loads a file
  733. * @param url url string, ArrayBuffer, or Blob to load
  734. * @param onSuccess callback called when the file successfully loads
  735. * @param onProgress callback called while file is loading (if the server supports this mode)
  736. * @param offlineProvider defines the offline provider for caching
  737. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  738. * @param onError callback called when the file fails to load
  739. * @returns a file request object
  740. */
  741. 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 {
  742. url = Tools.CleanUrl(url);
  743. url = Tools.PreprocessUrl(url);
  744. // If file and file input are set
  745. if (url.indexOf("file:") !== -1) {
  746. const fileName = decodeURIComponent(url.substring(5).toLowerCase());
  747. if (FilesInputStore.FilesToLoad[fileName]) {
  748. return Tools.ReadFile(FilesInputStore.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  749. }
  750. }
  751. const loadUrl = Tools.BaseUrl + url;
  752. let aborted = false;
  753. const fileRequest: IFileRequest = {
  754. onCompleteObservable: new Observable<IFileRequest>(),
  755. abort: () => aborted = true,
  756. };
  757. const requestFile = () => {
  758. let request = new WebRequest();
  759. let retryHandle: Nullable<number> = null;
  760. fileRequest.abort = () => {
  761. aborted = true;
  762. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  763. request.abort();
  764. }
  765. if (retryHandle !== null) {
  766. clearTimeout(retryHandle);
  767. retryHandle = null;
  768. }
  769. };
  770. const retryLoop = (retryIndex: number) => {
  771. request.open('GET', loadUrl);
  772. if (useArrayBuffer) {
  773. request.responseType = "arraybuffer";
  774. }
  775. if (onProgress) {
  776. request.addEventListener("progress", onProgress);
  777. }
  778. const onLoadEnd = () => {
  779. request.removeEventListener("loadend", onLoadEnd);
  780. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  781. fileRequest.onCompleteObservable.clear();
  782. };
  783. request.addEventListener("loadend", onLoadEnd);
  784. const onReadyStateChange = () => {
  785. if (aborted) {
  786. return;
  787. }
  788. // In case of undefined state in some browsers.
  789. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  790. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  791. request.removeEventListener("readystatechange", onReadyStateChange);
  792. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!DomManagement.IsWindowObjectExist() || Tools.IsFileURL()))) {
  793. onSuccess(!useArrayBuffer ? request.responseText : <ArrayBuffer>request.response, request.responseURL);
  794. return;
  795. }
  796. let retryStrategy = Tools.DefaultRetryStrategy;
  797. if (retryStrategy) {
  798. let waitTime = retryStrategy(loadUrl, request, retryIndex);
  799. if (waitTime !== -1) {
  800. // Prevent the request from completing for retry.
  801. request.removeEventListener("loadend", onLoadEnd);
  802. request = new WebRequest();
  803. retryHandle = setTimeout(() => retryLoop(retryIndex + 1), waitTime);
  804. return;
  805. }
  806. }
  807. let e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  808. if (onError) {
  809. onError(request, e);
  810. } else {
  811. throw e;
  812. }
  813. }
  814. };
  815. request.addEventListener("readystatechange", onReadyStateChange);
  816. request.send();
  817. };
  818. retryLoop(0);
  819. };
  820. // Caching all files
  821. if (offlineProvider && offlineProvider.enableSceneOffline) {
  822. const noOfflineSupport = (request?: any) => {
  823. if (request && request.status > 400) {
  824. if (onError) {
  825. onError(request);
  826. }
  827. } else {
  828. if (!aborted) {
  829. requestFile();
  830. }
  831. }
  832. };
  833. const loadFromOfflineSupport = () => {
  834. // TODO: database needs to support aborting and should return a IFileRequest
  835. if (aborted) {
  836. return;
  837. }
  838. if (offlineProvider) {
  839. offlineProvider.loadFile(url, (data) => {
  840. if (!aborted) {
  841. onSuccess(data);
  842. }
  843. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  844. }, onProgress ? (event) => {
  845. if (!aborted) {
  846. onProgress(event);
  847. }
  848. } : undefined, noOfflineSupport, useArrayBuffer);
  849. }
  850. };
  851. offlineProvider.open(loadFromOfflineSupport, noOfflineSupport);
  852. }
  853. else {
  854. requestFile();
  855. }
  856. return fileRequest;
  857. }
  858. /**
  859. * Load a script (identified by an url). When the url returns, the
  860. * content of this file is added into a new script element, attached to the DOM (body element)
  861. * @param scriptUrl defines the url of the script to laod
  862. * @param onSuccess defines the callback called when the script is loaded
  863. * @param onError defines the callback to call if an error occurs
  864. * @param scriptId defines the id of the script element
  865. */
  866. public static LoadScript(scriptUrl: string, onSuccess: () => void, onError?: (message?: string, exception?: any) => void, scriptId?: string) {
  867. if (!DomManagement.IsWindowObjectExist()) {
  868. return;
  869. }
  870. var head = document.getElementsByTagName('head')[0];
  871. var script = document.createElement('script');
  872. script.setAttribute('type', 'text/javascript');
  873. script.setAttribute('src', scriptUrl);
  874. if (scriptId) {
  875. script.id = scriptId;
  876. }
  877. script.onload = () => {
  878. if (onSuccess) {
  879. onSuccess();
  880. }
  881. };
  882. script.onerror = (e) => {
  883. if (onError) {
  884. onError(`Unable to load script '${scriptUrl}'`, e);
  885. }
  886. };
  887. head.appendChild(script);
  888. }
  889. /**
  890. * Load an asynchronous script (identified by an url). When the url returns, the
  891. * content of this file is added into a new script element, attached to the DOM (body element)
  892. * @param scriptUrl defines the url of the script to laod
  893. * @param scriptId defines the id of the script element
  894. * @returns a promise request object
  895. */
  896. public static LoadScriptAsync(scriptUrl: string, scriptId?: string): Nullable<Promise<boolean>> {
  897. return new Promise<boolean>((resolve, reject) => {
  898. if (!DomManagement.IsWindowObjectExist()) {
  899. resolve(false);
  900. return;
  901. }
  902. var head = document.getElementsByTagName('head')[0];
  903. var script = document.createElement('script');
  904. script.setAttribute('type', 'text/javascript');
  905. script.setAttribute('src', scriptUrl);
  906. if (scriptId) {
  907. script.id = scriptId;
  908. }
  909. script.onload = () => {
  910. resolve(true);
  911. };
  912. script.onerror = (e) => {
  913. resolve(false);
  914. };
  915. head.appendChild(script);
  916. });
  917. }
  918. /**
  919. * Loads a file from a blob
  920. * @param fileToLoad defines the blob to use
  921. * @param callback defines the callback to call when data is loaded
  922. * @param progressCallback defines the callback to call during loading process
  923. * @returns a file request object
  924. */
  925. public static ReadFileAsDataURL(fileToLoad: Blob, callback: (data: any) => void, progressCallback: (ev: ProgressEvent) => any): IFileRequest {
  926. let reader = new FileReader();
  927. let request: IFileRequest = {
  928. onCompleteObservable: new Observable<IFileRequest>(),
  929. abort: () => reader.abort(),
  930. };
  931. reader.onloadend = (e) => {
  932. request.onCompleteObservable.notifyObservers(request);
  933. };
  934. reader.onload = (e) => {
  935. //target doesn't have result from ts 1.3
  936. callback((<any>e.target)['result']);
  937. };
  938. reader.onprogress = progressCallback;
  939. reader.readAsDataURL(fileToLoad);
  940. return request;
  941. }
  942. /**
  943. * Loads a file
  944. * @param fileToLoad defines the file to load
  945. * @param callback defines the callback to call when data is loaded
  946. * @param progressCallBack defines the callback to call during loading process
  947. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  948. * @returns a file request object
  949. */
  950. public static ReadFile(fileToLoad: File, callback: (data: any) => void, progressCallBack?: (ev: ProgressEvent) => any, useArrayBuffer?: boolean): IFileRequest {
  951. let reader = new FileReader();
  952. let request: IFileRequest = {
  953. onCompleteObservable: new Observable<IFileRequest>(),
  954. abort: () => reader.abort(),
  955. };
  956. reader.onloadend = (e) => request.onCompleteObservable.notifyObservers(request);
  957. reader.onerror = (e) => {
  958. Logger.Log("Error while reading file: " + fileToLoad.name);
  959. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  960. };
  961. reader.onload = (e) => {
  962. //target doesn't have result from ts 1.3
  963. callback((<any>e.target)['result']);
  964. };
  965. if (progressCallBack) {
  966. reader.onprogress = progressCallBack;
  967. }
  968. if (!useArrayBuffer) {
  969. // Asynchronous read
  970. reader.readAsText(fileToLoad);
  971. }
  972. else {
  973. reader.readAsArrayBuffer(fileToLoad);
  974. }
  975. return request;
  976. }
  977. /**
  978. * Creates a data url from a given string content
  979. * @param content defines the content to convert
  980. * @returns the new data url link
  981. */
  982. public static FileAsURL(content: string): string {
  983. var fileBlob = new Blob([content]);
  984. var url = window.URL || window.webkitURL;
  985. var link: string = url.createObjectURL(fileBlob);
  986. return link;
  987. }
  988. /**
  989. * Format the given number to a specific decimal format
  990. * @param value defines the number to format
  991. * @param decimals defines the number of decimals to use
  992. * @returns the formatted string
  993. */
  994. public static Format(value: number, decimals: number = 2): string {
  995. return value.toFixed(decimals);
  996. }
  997. /**
  998. * Checks if a given vector is inside a specific range
  999. * @param v defines the vector to test
  1000. * @param min defines the minimum range
  1001. * @param max defines the maximum range
  1002. */
  1003. public static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void {
  1004. min.minimizeInPlace(v);
  1005. max.maximizeInPlace(v);
  1006. }
  1007. /**
  1008. * Tries to copy an object by duplicating every property
  1009. * @param source defines the source object
  1010. * @param destination defines the target object
  1011. * @param doNotCopyList defines a list of properties to avoid
  1012. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  1013. */
  1014. public static DeepCopy(source: any, destination: any, doNotCopyList?: string[], mustCopyList?: string[]): void {
  1015. DeepCopier.DeepCopy(source, destination, doNotCopyList, mustCopyList);
  1016. }
  1017. /**
  1018. * Gets a boolean indicating if the given object has no own property
  1019. * @param obj defines the object to test
  1020. * @returns true if object has no own property
  1021. */
  1022. public static IsEmpty(obj: any): boolean {
  1023. for (var i in obj) {
  1024. if (obj.hasOwnProperty(i)) {
  1025. return false;
  1026. }
  1027. }
  1028. return true;
  1029. }
  1030. /**
  1031. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  1032. * @param str Source string
  1033. * @param suffix Suffix to search for in the source string
  1034. * @returns Boolean indicating whether the suffix was found (true) or not (false)
  1035. */
  1036. public static EndsWith(str: string, suffix: string): boolean {
  1037. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  1038. }
  1039. /**
  1040. * Function used to register events at window level
  1041. * @param events defines the events to register
  1042. */
  1043. public static RegisterTopRootEvents(events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  1044. for (var index = 0; index < events.length; index++) {
  1045. var event = events[index];
  1046. window.addEventListener(event.name, <any>event.handler, false);
  1047. try {
  1048. if (window.parent) {
  1049. window.parent.addEventListener(event.name, <any>event.handler, false);
  1050. }
  1051. } catch (e) {
  1052. // Silently fails...
  1053. }
  1054. }
  1055. }
  1056. /**
  1057. * Function used to unregister events from window level
  1058. * @param events defines the events to unregister
  1059. */
  1060. public static UnregisterTopRootEvents(events: { name: string; handler: Nullable<(e: FocusEvent) => any> }[]): void {
  1061. for (var index = 0; index < events.length; index++) {
  1062. var event = events[index];
  1063. window.removeEventListener(event.name, <any>event.handler);
  1064. try {
  1065. if (window.parent) {
  1066. window.parent.removeEventListener(event.name, <any>event.handler);
  1067. }
  1068. } catch (e) {
  1069. // Silently fails...
  1070. }
  1071. }
  1072. }
  1073. /**
  1074. * @ignore
  1075. */
  1076. public static _ScreenshotCanvas: HTMLCanvasElement;
  1077. /**
  1078. * Dumps the current bound framebuffer
  1079. * @param width defines the rendering width
  1080. * @param height defines the rendering height
  1081. * @param engine defines the hosting engine
  1082. * @param successCallback defines the callback triggered once the data are available
  1083. * @param mimeType defines the mime type of the result
  1084. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  1085. */
  1086. public static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string): void {
  1087. // Read the contents of the framebuffer
  1088. var numberOfChannelsByLine = width * 4;
  1089. var halfHeight = height / 2;
  1090. //Reading datas from WebGL
  1091. var data = engine.readPixels(0, 0, width, height);
  1092. //To flip image on Y axis.
  1093. for (var i = 0; i < halfHeight; i++) {
  1094. for (var j = 0; j < numberOfChannelsByLine; j++) {
  1095. var currentCell = j + i * numberOfChannelsByLine;
  1096. var targetLine = height - i - 1;
  1097. var targetCell = j + targetLine * numberOfChannelsByLine;
  1098. var temp = data[currentCell];
  1099. data[currentCell] = data[targetCell];
  1100. data[targetCell] = temp;
  1101. }
  1102. }
  1103. // Create a 2D canvas to store the result
  1104. if (!Tools._ScreenshotCanvas) {
  1105. Tools._ScreenshotCanvas = document.createElement('canvas');
  1106. }
  1107. Tools._ScreenshotCanvas.width = width;
  1108. Tools._ScreenshotCanvas.height = height;
  1109. var context = Tools._ScreenshotCanvas.getContext('2d');
  1110. if (context) {
  1111. // Copy the pixels to a 2D canvas
  1112. var imageData = context.createImageData(width, height);
  1113. var castData = <any>(imageData.data);
  1114. castData.set(data);
  1115. context.putImageData(imageData, 0, 0);
  1116. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  1117. }
  1118. }
  1119. /**
  1120. * Converts the canvas data to blob.
  1121. * This acts as a polyfill for browsers not supporting the to blob function.
  1122. * @param canvas Defines the canvas to extract the data from
  1123. * @param successCallback Defines the callback triggered once the data are available
  1124. * @param mimeType Defines the mime type of the result
  1125. */
  1126. static ToBlob(canvas: HTMLCanvasElement, successCallback: (blob: Nullable<Blob>) => void, mimeType: string = "image/png"): void {
  1127. // We need HTMLCanvasElement.toBlob for HD screenshots
  1128. if (!canvas.toBlob) {
  1129. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  1130. canvas.toBlob = function(callback, type, quality) {
  1131. setTimeout(() => {
  1132. var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
  1133. len = binStr.length,
  1134. arr = new Uint8Array(len);
  1135. for (var i = 0; i < len; i++) {
  1136. arr[i] = binStr.charCodeAt(i);
  1137. }
  1138. callback(new Blob([arr]));
  1139. });
  1140. };
  1141. }
  1142. canvas.toBlob(function(blob) {
  1143. successCallback(blob);
  1144. }, mimeType);
  1145. }
  1146. /**
  1147. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  1148. * @param successCallback defines the callback triggered once the data are available
  1149. * @param mimeType defines the mime type of the result
  1150. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  1151. */
  1152. static EncodeScreenshotCanvasData(successCallback?: (data: string) => void, mimeType: string = "image/png", fileName?: string): void {
  1153. if (successCallback) {
  1154. var base64Image = Tools._ScreenshotCanvas.toDataURL(mimeType);
  1155. successCallback(base64Image);
  1156. }
  1157. else {
  1158. this.ToBlob(Tools._ScreenshotCanvas, function(blob) {
  1159. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  1160. if (("download" in document.createElement("a"))) {
  1161. if (!fileName) {
  1162. var date = new Date();
  1163. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  1164. fileName = "screenshot_" + stringDate + ".png";
  1165. }
  1166. Tools.Download(blob!, fileName);
  1167. }
  1168. else {
  1169. var url = URL.createObjectURL(blob);
  1170. var newWindow = window.open("");
  1171. if (!newWindow) { return; }
  1172. var img = newWindow.document.createElement("img");
  1173. img.onload = function() {
  1174. // no longer need to read the blob so it's revoked
  1175. URL.revokeObjectURL(url);
  1176. };
  1177. img.src = url;
  1178. newWindow.document.body.appendChild(img);
  1179. }
  1180. }, mimeType);
  1181. }
  1182. }
  1183. /**
  1184. * Downloads a blob in the browser
  1185. * @param blob defines the blob to download
  1186. * @param fileName defines the name of the downloaded file
  1187. */
  1188. public static Download(blob: Blob, fileName: string): void {
  1189. if (navigator && navigator.msSaveBlob) {
  1190. navigator.msSaveBlob(blob, fileName);
  1191. return;
  1192. }
  1193. var url = window.URL.createObjectURL(blob);
  1194. var a = document.createElement("a");
  1195. document.body.appendChild(a);
  1196. a.style.display = "none";
  1197. a.href = url;
  1198. a.download = fileName;
  1199. a.addEventListener("click", () => {
  1200. if (a.parentElement) {
  1201. a.parentElement.removeChild(a);
  1202. }
  1203. });
  1204. a.click();
  1205. window.URL.revokeObjectURL(url);
  1206. }
  1207. /**
  1208. * Captures a screenshot of the current rendering
  1209. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  1210. * @param engine defines the rendering engine
  1211. * @param camera defines the source camera
  1212. * @param size This parameter can be set to a single number or to an object with the
  1213. * following (optional) properties: precision, width, height. If a single number is passed,
  1214. * it will be used for both width and height. If an object is passed, the screenshot size
  1215. * will be derived from the parameters. The precision property is a multiplier allowing
  1216. * rendering at a higher or lower resolution
  1217. * @param successCallback defines the callback receives a single parameter which contains the
  1218. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  1219. * src parameter of an <img> to display it
  1220. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  1221. * Check your browser for supported MIME types
  1222. */
  1223. public static CreateScreenshot(engine: Engine, camera: Camera, size: any, successCallback?: (data: string) => void, mimeType: string = "image/png"): void {
  1224. throw _DevTools.WarnImport("ScreenshotTools");
  1225. }
  1226. /**
  1227. * Generates an image screenshot from the specified camera.
  1228. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  1229. * @param engine The engine to use for rendering
  1230. * @param camera The camera to use for rendering
  1231. * @param size This parameter can be set to a single number or to an object with the
  1232. * following (optional) properties: precision, width, height. If a single number is passed,
  1233. * it will be used for both width and height. If an object is passed, the screenshot size
  1234. * will be derived from the parameters. The precision property is a multiplier allowing
  1235. * rendering at a higher or lower resolution
  1236. * @param successCallback The callback receives a single parameter which contains the
  1237. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  1238. * src parameter of an <img> to display it
  1239. * @param mimeType The MIME type of the screenshot image (default: image/png).
  1240. * Check your browser for supported MIME types
  1241. * @param samples Texture samples (default: 1)
  1242. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  1243. * @param fileName A name for for the downloaded file.
  1244. */
  1245. public static CreateScreenshotUsingRenderTarget(engine: Engine, camera: Camera, size: any, successCallback?: (data: string) => void, mimeType: string = "image/png", samples: number = 1, antialiasing: boolean = false, fileName?: string): void {
  1246. throw _DevTools.WarnImport("ScreenshotTools");
  1247. }
  1248. /**
  1249. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  1250. * Be aware Math.random() could cause collisions, but:
  1251. * "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"
  1252. * @returns a pseudo random id
  1253. */
  1254. public static RandomId(): string {
  1255. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  1256. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  1257. return v.toString(16);
  1258. });
  1259. }
  1260. /**
  1261. * Test if the given uri is a base64 string
  1262. * @param uri The uri to test
  1263. * @return True if the uri is a base64 string or false otherwise
  1264. */
  1265. public static IsBase64(uri: string): boolean {
  1266. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1267. }
  1268. /**
  1269. * Decode the given base64 uri.
  1270. * @param uri The uri to decode
  1271. * @return The decoded base64 data.
  1272. */
  1273. public static DecodeBase64(uri: string): ArrayBuffer {
  1274. const decodedString = atob(uri.split(",")[1]);
  1275. const bufferLength = decodedString.length;
  1276. const bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1277. for (let i = 0; i < bufferLength; i++) {
  1278. bufferView[i] = decodedString.charCodeAt(i);
  1279. }
  1280. return bufferView.buffer;
  1281. }
  1282. /**
  1283. * Gets the absolute url.
  1284. * @param url the input url
  1285. * @return the absolute url
  1286. */
  1287. public static GetAbsoluteUrl(url: string): string {
  1288. const a = document.createElement("a");
  1289. a.href = url;
  1290. return a.href;
  1291. }
  1292. // Logs
  1293. /**
  1294. * No log
  1295. */
  1296. public static readonly NoneLogLevel = Logger.NoneLogLevel;
  1297. /**
  1298. * Only message logs
  1299. */
  1300. public static readonly MessageLogLevel = Logger.MessageLogLevel;
  1301. /**
  1302. * Only warning logs
  1303. */
  1304. public static readonly WarningLogLevel = Logger.WarningLogLevel;
  1305. /**
  1306. * Only error logs
  1307. */
  1308. public static readonly ErrorLogLevel = Logger.ErrorLogLevel;
  1309. /**
  1310. * All logs
  1311. */
  1312. public static readonly AllLogLevel = Logger.AllLogLevel;
  1313. /**
  1314. * Gets a value indicating the number of loading errors
  1315. * @ignorenaming
  1316. */
  1317. public static get errorsCount(): number {
  1318. return Logger.errorsCount;
  1319. }
  1320. /**
  1321. * Callback called when a new log is added
  1322. */
  1323. public static OnNewCacheEntry: (entry: string) => void;
  1324. /**
  1325. * Log a message to the console
  1326. * @param message defines the message to log
  1327. */
  1328. public static Log(message: string): void {
  1329. Logger.Log(message);
  1330. }
  1331. /**
  1332. * Write a warning message to the console
  1333. * @param message defines the message to log
  1334. */
  1335. public static Warn(message: string): void {
  1336. Logger.Warn(message);
  1337. }
  1338. /**
  1339. * Write an error message to the console
  1340. * @param message defines the message to log
  1341. */
  1342. public static Error(message: string): void {
  1343. Logger.Error(message);
  1344. }
  1345. /**
  1346. * Gets current log cache (list of logs)
  1347. */
  1348. public static get LogCache(): string {
  1349. return Logger.LogCache;
  1350. }
  1351. /**
  1352. * Clears the log cache
  1353. */
  1354. public static ClearLogCache(): void {
  1355. Logger.ClearLogCache();
  1356. }
  1357. /**
  1358. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  1359. */
  1360. public static set LogLevels(level: number) {
  1361. Logger.LogLevels = level;
  1362. }
  1363. /**
  1364. * Checks if the loaded document was accessed via `file:`-Protocol.
  1365. * @returns boolean
  1366. */
  1367. public static IsFileURL(): boolean {
  1368. return location.protocol === "file:";
  1369. }
  1370. /**
  1371. * Checks if the window object exists
  1372. * Back Compat only, please use DomManagement.IsWindowObjectExist instead.
  1373. */
  1374. public static IsWindowObjectExist = DomManagement.IsWindowObjectExist;
  1375. // Performances
  1376. /**
  1377. * No performance log
  1378. */
  1379. public static readonly PerformanceNoneLogLevel = 0;
  1380. /**
  1381. * Use user marks to log performance
  1382. */
  1383. public static readonly PerformanceUserMarkLogLevel = 1;
  1384. /**
  1385. * Log performance to the console
  1386. */
  1387. public static readonly PerformanceConsoleLogLevel = 2;
  1388. private static _performance: Performance;
  1389. /**
  1390. * Sets the current performance log level
  1391. */
  1392. public static set PerformanceLogLevel(level: number) {
  1393. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  1394. Tools.StartPerformanceCounter = Tools._StartUserMark;
  1395. Tools.EndPerformanceCounter = Tools._EndUserMark;
  1396. return;
  1397. }
  1398. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  1399. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  1400. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  1401. return;
  1402. }
  1403. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  1404. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  1405. }
  1406. private static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  1407. }
  1408. private static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  1409. }
  1410. private static _StartUserMark(counterName: string, condition = true): void {
  1411. if (!Tools._performance) {
  1412. if (!DomManagement.IsWindowObjectExist()) {
  1413. return;
  1414. }
  1415. Tools._performance = window.performance;
  1416. }
  1417. if (!condition || !Tools._performance.mark) {
  1418. return;
  1419. }
  1420. Tools._performance.mark(counterName + "-Begin");
  1421. }
  1422. private static _EndUserMark(counterName: string, condition = true): void {
  1423. if (!condition || !Tools._performance.mark) {
  1424. return;
  1425. }
  1426. Tools._performance.mark(counterName + "-End");
  1427. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  1428. }
  1429. private static _StartPerformanceConsole(counterName: string, condition = true): void {
  1430. if (!condition) {
  1431. return;
  1432. }
  1433. Tools._StartUserMark(counterName, condition);
  1434. if (console.time) {
  1435. console.time(counterName);
  1436. }
  1437. }
  1438. private static _EndPerformanceConsole(counterName: string, condition = true): void {
  1439. if (!condition) {
  1440. return;
  1441. }
  1442. Tools._EndUserMark(counterName, condition);
  1443. if (console.time) {
  1444. console.timeEnd(counterName);
  1445. }
  1446. }
  1447. /**
  1448. * Starts a performance counter
  1449. */
  1450. public static StartPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._StartPerformanceCounterDisabled;
  1451. /**
  1452. * Ends a specific performance coutner
  1453. */
  1454. public static EndPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._EndPerformanceCounterDisabled;
  1455. /**
  1456. * Gets either window.performance.now() if supported or Date.now() else
  1457. */
  1458. public static get Now(): number {
  1459. return PrecisionDate.Now;
  1460. }
  1461. /**
  1462. * This method will return the name of the class used to create the instance of the given object.
  1463. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  1464. * @param object the object to get the class name from
  1465. * @param isType defines if the object is actually a type
  1466. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  1467. */
  1468. public static GetClassName(object: any, isType: boolean = false): string {
  1469. let name = null;
  1470. if (!isType && object.getClassName) {
  1471. name = object.getClassName();
  1472. } else {
  1473. if (object instanceof Object) {
  1474. let classObj = isType ? object : Object.getPrototypeOf(object);
  1475. name = classObj.constructor["__bjsclassName__"];
  1476. }
  1477. if (!name) {
  1478. name = typeof object;
  1479. }
  1480. }
  1481. return name;
  1482. }
  1483. /**
  1484. * Gets the first element of an array satisfying a given predicate
  1485. * @param array defines the array to browse
  1486. * @param predicate defines the predicate to use
  1487. * @returns null if not found or the element
  1488. */
  1489. public static First<T>(array: Array<T>, predicate: (item: T) => boolean): Nullable<T> {
  1490. for (let el of array) {
  1491. if (predicate(el)) {
  1492. return el;
  1493. }
  1494. }
  1495. return null;
  1496. }
  1497. /**
  1498. * This method will return the name of the full name of the class, including its owning module (if any).
  1499. * 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).
  1500. * @param object the object to get the class name from
  1501. * @param isType defines if the object is actually a type
  1502. * @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.
  1503. * @ignorenaming
  1504. */
  1505. public static getFullClassName(object: any, isType: boolean = false): Nullable<string> {
  1506. let className = null;
  1507. let moduleName = null;
  1508. if (!isType && object.getClassName) {
  1509. className = object.getClassName();
  1510. } else {
  1511. if (object instanceof Object) {
  1512. let classObj = isType ? object : Object.getPrototypeOf(object);
  1513. className = classObj.constructor["__bjsclassName__"];
  1514. moduleName = classObj.constructor["__bjsmoduleName__"];
  1515. }
  1516. if (!className) {
  1517. className = typeof object;
  1518. }
  1519. }
  1520. if (!className) {
  1521. return null;
  1522. }
  1523. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  1524. }
  1525. /**
  1526. * Returns a promise that resolves after the given amount of time.
  1527. * @param delay Number of milliseconds to delay
  1528. * @returns Promise that resolves after the given amount of time
  1529. */
  1530. public static DelayAsync(delay: number): Promise<void> {
  1531. return new Promise((resolve) => {
  1532. setTimeout(() => {
  1533. resolve();
  1534. }, delay);
  1535. });
  1536. }
  1537. /**
  1538. * Gets the current gradient from an array of IValueGradient
  1539. * @param ratio defines the current ratio to get
  1540. * @param gradients defines the array of IValueGradient
  1541. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  1542. */
  1543. public static GetCurrentGradient(ratio: number, gradients: IValueGradient[], updateFunc: (current: IValueGradient, next: IValueGradient, scale: number) => void) {
  1544. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  1545. let currentGradient = gradients[gradientIndex];
  1546. let nextGradient = gradients[gradientIndex + 1];
  1547. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  1548. let scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  1549. updateFunc(currentGradient, nextGradient, scale);
  1550. return;
  1551. }
  1552. }
  1553. // Use last index if over
  1554. const lastIndex = gradients.length - 1;
  1555. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  1556. }
  1557. }
  1558. /**
  1559. * This class is used to track a performance counter which is number based.
  1560. * The user has access to many properties which give statistics of different nature.
  1561. *
  1562. * The implementer can track two kinds of Performance Counter: time and count.
  1563. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  1564. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  1565. */
  1566. export class PerfCounter {
  1567. /**
  1568. * Gets or sets a global boolean to turn on and off all the counters
  1569. */
  1570. public static Enabled = true;
  1571. /**
  1572. * Returns the smallest value ever
  1573. */
  1574. public get min(): number {
  1575. return this._min;
  1576. }
  1577. /**
  1578. * Returns the biggest value ever
  1579. */
  1580. public get max(): number {
  1581. return this._max;
  1582. }
  1583. /**
  1584. * Returns the average value since the performance counter is running
  1585. */
  1586. public get average(): number {
  1587. return this._average;
  1588. }
  1589. /**
  1590. * Returns the average value of the last second the counter was monitored
  1591. */
  1592. public get lastSecAverage(): number {
  1593. return this._lastSecAverage;
  1594. }
  1595. /**
  1596. * Returns the current value
  1597. */
  1598. public get current(): number {
  1599. return this._current;
  1600. }
  1601. /**
  1602. * Gets the accumulated total
  1603. */
  1604. public get total(): number {
  1605. return this._totalAccumulated;
  1606. }
  1607. /**
  1608. * Gets the total value count
  1609. */
  1610. public get count(): number {
  1611. return this._totalValueCount;
  1612. }
  1613. /**
  1614. * Creates a new counter
  1615. */
  1616. constructor() {
  1617. this._startMonitoringTime = 0;
  1618. this._min = 0;
  1619. this._max = 0;
  1620. this._average = 0;
  1621. this._lastSecAverage = 0;
  1622. this._current = 0;
  1623. this._totalValueCount = 0;
  1624. this._totalAccumulated = 0;
  1625. this._lastSecAccumulated = 0;
  1626. this._lastSecTime = 0;
  1627. this._lastSecValueCount = 0;
  1628. }
  1629. /**
  1630. * Call this method to start monitoring a new frame.
  1631. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  1632. */
  1633. public fetchNewFrame() {
  1634. this._totalValueCount++;
  1635. this._current = 0;
  1636. this._lastSecValueCount++;
  1637. }
  1638. /**
  1639. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  1640. * @param newCount the count value to add to the monitored count
  1641. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  1642. */
  1643. public addCount(newCount: number, fetchResult: boolean) {
  1644. if (!PerfCounter.Enabled) {
  1645. return;
  1646. }
  1647. this._current += newCount;
  1648. if (fetchResult) {
  1649. this._fetchResult();
  1650. }
  1651. }
  1652. /**
  1653. * Start monitoring this performance counter
  1654. */
  1655. public beginMonitoring() {
  1656. if (!PerfCounter.Enabled) {
  1657. return;
  1658. }
  1659. this._startMonitoringTime = PrecisionDate.Now;
  1660. }
  1661. /**
  1662. * Compute the time lapsed since the previous beginMonitoring() call.
  1663. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  1664. */
  1665. public endMonitoring(newFrame: boolean = true) {
  1666. if (!PerfCounter.Enabled) {
  1667. return;
  1668. }
  1669. if (newFrame) {
  1670. this.fetchNewFrame();
  1671. }
  1672. let currentTime = PrecisionDate.Now;
  1673. this._current = currentTime - this._startMonitoringTime;
  1674. if (newFrame) {
  1675. this._fetchResult();
  1676. }
  1677. }
  1678. private _fetchResult() {
  1679. this._totalAccumulated += this._current;
  1680. this._lastSecAccumulated += this._current;
  1681. // Min/Max update
  1682. this._min = Math.min(this._min, this._current);
  1683. this._max = Math.max(this._max, this._current);
  1684. this._average = this._totalAccumulated / this._totalValueCount;
  1685. // Reset last sec?
  1686. let now = PrecisionDate.Now;
  1687. if ((now - this._lastSecTime) > 1000) {
  1688. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  1689. this._lastSecTime = now;
  1690. this._lastSecAccumulated = 0;
  1691. this._lastSecValueCount = 0;
  1692. }
  1693. }
  1694. private _startMonitoringTime: number;
  1695. private _min: number;
  1696. private _max: number;
  1697. private _average: number;
  1698. private _current: number;
  1699. private _totalValueCount: number;
  1700. private _totalAccumulated: number;
  1701. private _lastSecAverage: number;
  1702. private _lastSecAccumulated: number;
  1703. private _lastSecTime: number;
  1704. private _lastSecValueCount: number;
  1705. }
  1706. /**
  1707. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  1708. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  1709. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  1710. * @param name The name of the class, case should be preserved
  1711. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  1712. */
  1713. export function className(name: string, module?: string): (target: Object) => void {
  1714. return (target: Object) => {
  1715. (<any>target)["__bjsclassName__"] = name;
  1716. (<any>target)["__bjsmoduleName__"] = (module != null) ? module : null;
  1717. };
  1718. }
  1719. /**
  1720. * An implementation of a loop for asynchronous functions.
  1721. */
  1722. export class AsyncLoop {
  1723. /**
  1724. * Defines the current index of the loop.
  1725. */
  1726. public index: number;
  1727. private _done: boolean;
  1728. private _fn: (asyncLoop: AsyncLoop) => void;
  1729. private _successCallback: () => void;
  1730. /**
  1731. * Constructor.
  1732. * @param iterations the number of iterations.
  1733. * @param func the function to run each iteration
  1734. * @param successCallback the callback that will be called upon succesful execution
  1735. * @param offset starting offset.
  1736. */
  1737. constructor(
  1738. /**
  1739. * Defines the number of iterations for the loop
  1740. */
  1741. public iterations: number,
  1742. func: (asyncLoop: AsyncLoop) => void,
  1743. successCallback: () => void,
  1744. offset: number = 0) {
  1745. this.index = offset - 1;
  1746. this._done = false;
  1747. this._fn = func;
  1748. this._successCallback = successCallback;
  1749. }
  1750. /**
  1751. * Execute the next iteration. Must be called after the last iteration was finished.
  1752. */
  1753. public executeNext(): void {
  1754. if (!this._done) {
  1755. if (this.index + 1 < this.iterations) {
  1756. ++this.index;
  1757. this._fn(this);
  1758. } else {
  1759. this.breakLoop();
  1760. }
  1761. }
  1762. }
  1763. /**
  1764. * Break the loop and run the success callback.
  1765. */
  1766. public breakLoop(): void {
  1767. this._done = true;
  1768. this._successCallback();
  1769. }
  1770. /**
  1771. * Create and run an async loop.
  1772. * @param iterations the number of iterations.
  1773. * @param fn the function to run each iteration
  1774. * @param successCallback the callback that will be called upon succesful execution
  1775. * @param offset starting offset.
  1776. * @returns the created async loop object
  1777. */
  1778. public static Run(iterations: number, fn: (asyncLoop: AsyncLoop) => void, successCallback: () => void, offset: number = 0): AsyncLoop {
  1779. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  1780. loop.executeNext();
  1781. return loop;
  1782. }
  1783. /**
  1784. * A for-loop that will run a given number of iterations synchronous and the rest async.
  1785. * @param iterations total number of iterations
  1786. * @param syncedIterations number of synchronous iterations in each async iteration.
  1787. * @param fn the function to call each iteration.
  1788. * @param callback a success call back that will be called when iterating stops.
  1789. * @param breakFunction a break condition (optional)
  1790. * @param timeout timeout settings for the setTimeout function. default - 0.
  1791. * @returns the created async loop object
  1792. */
  1793. public static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout: number = 0): AsyncLoop {
  1794. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop: AsyncLoop) => {
  1795. if (breakFunction && breakFunction()) { loop.breakLoop(); }
  1796. else {
  1797. setTimeout(() => {
  1798. for (var i = 0; i < syncedIterations; ++i) {
  1799. var iteration = (loop.index * syncedIterations) + i;
  1800. if (iteration >= iterations) { break; }
  1801. fn(iteration);
  1802. if (breakFunction && breakFunction()) {
  1803. loop.breakLoop();
  1804. break;
  1805. }
  1806. }
  1807. loop.executeNext();
  1808. }, timeout);
  1809. }
  1810. }, callback);
  1811. }
  1812. }