babylon.tools.ts 93 KB

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