babylon.tools.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. module BABYLON {
  2. export interface IAnimatable {
  3. animations: Array<Animation>;
  4. }
  5. // Screenshots
  6. var screenshotCanvas: HTMLCanvasElement;
  7. var cloneValue = (source, destinationObject) => {
  8. if (!source)
  9. return null;
  10. if (source instanceof Mesh) {
  11. return null;
  12. }
  13. if (source instanceof SubMesh) {
  14. return source.clone(destinationObject);
  15. } else if (source.clone) {
  16. return source.clone();
  17. }
  18. return null;
  19. };
  20. export class Tools {
  21. public static BaseUrl = "";
  22. public static CorsBehavior: any = "anonymous";
  23. public static UseFallbackTexture = true;
  24. public static Instantiate(className: string): any {
  25. var arr = className.split(".");
  26. var fn = (window || this);
  27. for (var i = 0, len = arr.length; i < len; i++) {
  28. fn = fn[arr[i]];
  29. }
  30. if (typeof fn !== "function") {
  31. return null;
  32. }
  33. return fn;
  34. }
  35. public static SetImmediate(action: () => void) {
  36. if (window.setImmediate) {
  37. window.setImmediate(action);
  38. } else {
  39. setTimeout(action, 1);
  40. }
  41. }
  42. public static IsExponentOfTwo(value: number): boolean {
  43. var count = 1;
  44. do {
  45. count *= 2;
  46. } while (count < value);
  47. return count === value;
  48. }
  49. public static GetExponentOfTwo(value: number, max: number): number {
  50. var count = 1;
  51. do {
  52. count *= 2;
  53. } while (count < value);
  54. if (count > max)
  55. count = max;
  56. return count;
  57. }
  58. public static GetFilename(path: string): string {
  59. var index = path.lastIndexOf("/");
  60. if (index < 0)
  61. return path;
  62. return path.substring(index + 1);
  63. }
  64. public static GetDOMTextContent(element: HTMLElement): string {
  65. var result = "";
  66. var child = element.firstChild;
  67. while (child) {
  68. if (child.nodeType === 3) {
  69. result += child.textContent;
  70. }
  71. child = child.nextSibling;
  72. }
  73. return result;
  74. }
  75. public static ToDegrees(angle: number): number {
  76. return angle * 180 / Math.PI;
  77. }
  78. public static ToRadians(angle: number): number {
  79. return angle * Math.PI / 180;
  80. }
  81. public static EncodeArrayBufferTobase64(buffer: ArrayBuffer): string {
  82. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  83. var output = "";
  84. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  85. var i = 0;
  86. var bytes = new Uint8Array(buffer);
  87. while (i < bytes.length) {
  88. chr1 = bytes[i++];
  89. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  90. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  91. enc1 = chr1 >> 2;
  92. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  93. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  94. enc4 = chr3 & 63;
  95. if (isNaN(chr2)) {
  96. enc3 = enc4 = 64;
  97. } else if (isNaN(chr3)) {
  98. enc4 = 64;
  99. }
  100. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  101. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  102. }
  103. return "data:image/png;base64," + output;
  104. }
  105. public static ExtractMinAndMaxIndexed(positions: number[] | Float32Array, indices: number[] | Int32Array, indexStart: number, indexCount: number, bias: Vector2 = null): { minimum: Vector3; maximum: Vector3 } {
  106. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  107. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  108. for (var index = indexStart; index < indexStart + indexCount; index++) {
  109. var current = new Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  110. minimum = Vector3.Minimize(current, minimum);
  111. maximum = Vector3.Maximize(current, maximum);
  112. }
  113. if (bias) {
  114. minimum.x -= minimum.x * bias.x + bias.y;
  115. minimum.y -= minimum.y * bias.x + bias.y;
  116. minimum.z -= minimum.z * bias.x + bias.y;
  117. maximum.x += maximum.x * bias.x + bias.y;
  118. maximum.y += maximum.y * bias.x + bias.y;
  119. maximum.z += maximum.z * bias.x + bias.y;
  120. }
  121. return {
  122. minimum: minimum,
  123. maximum: maximum
  124. };
  125. }
  126. public static ExtractMinAndMax(positions: number[] | Float32Array, start: number, count: number, bias: Vector2 = null): { minimum: Vector3; maximum: Vector3 } {
  127. var minimum = new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  128. var maximum = new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  129. for (var index = start; index < start + count; index++) {
  130. var current = new Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  131. minimum = Vector3.Minimize(current, minimum);
  132. maximum = Vector3.Maximize(current, maximum);
  133. }
  134. if (bias) {
  135. minimum.x -= minimum.x * bias.x + bias.y;
  136. minimum.y -= minimum.y * bias.x + bias.y;
  137. minimum.z -= minimum.z * bias.x + bias.y;
  138. maximum.x += maximum.x * bias.x + bias.y;
  139. maximum.y += maximum.y * bias.x + bias.y;
  140. maximum.z += maximum.z * bias.x + bias.y;
  141. }
  142. return {
  143. minimum: minimum,
  144. maximum: maximum
  145. };
  146. }
  147. public static MakeArray(obj, allowsNullUndefined?: boolean): Array<any> {
  148. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  149. return undefined;
  150. return Array.isArray(obj) ? obj : [obj];
  151. }
  152. // Misc.
  153. public static GetPointerPrefix(): string {
  154. var eventPrefix = "pointer";
  155. // Check if pointer events are supported
  156. if (!window.PointerEvent && !navigator.pointerEnabled) {
  157. eventPrefix = "mouse";
  158. }
  159. return eventPrefix;
  160. }
  161. public static QueueNewFrame(func): void {
  162. if (window.requestAnimationFrame)
  163. window.requestAnimationFrame(func);
  164. else if (window.msRequestAnimationFrame)
  165. window.msRequestAnimationFrame(func);
  166. else if (window.webkitRequestAnimationFrame)
  167. window.webkitRequestAnimationFrame(func);
  168. else if (window.mozRequestAnimationFrame)
  169. window.mozRequestAnimationFrame(func);
  170. else if (window.oRequestAnimationFrame)
  171. window.oRequestAnimationFrame(func);
  172. else {
  173. window.setTimeout(func, 16);
  174. }
  175. }
  176. public static RequestFullscreen(element): void {
  177. if (element.requestFullscreen)
  178. element.requestFullscreen();
  179. else if (element.msRequestFullscreen)
  180. element.msRequestFullscreen();
  181. else if (element.webkitRequestFullscreen)
  182. element.webkitRequestFullscreen();
  183. else if (element.mozRequestFullScreen)
  184. element.mozRequestFullScreen();
  185. }
  186. public static ExitFullscreen(): void {
  187. if (document.exitFullscreen) {
  188. document.exitFullscreen();
  189. }
  190. else if (document.mozCancelFullScreen) {
  191. document.mozCancelFullScreen();
  192. }
  193. else if (document.webkitCancelFullScreen) {
  194. document.webkitCancelFullScreen();
  195. }
  196. else if (document.msCancelFullScreen) {
  197. document.msCancelFullScreen();
  198. }
  199. }
  200. // External files
  201. public static CleanUrl(url: string): string {
  202. url = url.replace(/#/mg, "%23");
  203. return url;
  204. }
  205. public static LoadImage(url: any, onload, onerror, database): HTMLImageElement {
  206. if (url instanceof ArrayBuffer) {
  207. url = Tools.EncodeArrayBufferTobase64(url);
  208. }
  209. url = Tools.CleanUrl(url);
  210. var img = new Image();
  211. if (url.substr(0, 5) !== "data:") {
  212. if (Tools.CorsBehavior) {
  213. switch (typeof (Tools.CorsBehavior)) {
  214. case "function":
  215. var result = Tools.CorsBehavior(url);
  216. if (result) {
  217. img.crossOrigin = result;
  218. }
  219. break;
  220. case "string":
  221. default:
  222. img.crossOrigin = Tools.CorsBehavior;
  223. break;
  224. }
  225. }
  226. }
  227. img.onload = () => {
  228. onload(img);
  229. };
  230. img.onerror = err => {
  231. Tools.Error("Error while trying to load texture: " + url);
  232. if (Tools.UseFallbackTexture) {
  233. img.src = "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";
  234. onload(img);
  235. } else {
  236. onerror();
  237. }
  238. };
  239. var noIndexedDB = () => {
  240. img.src = url;
  241. };
  242. var loadFromIndexedDB = () => {
  243. database.loadImageFromDB(url, img);
  244. };
  245. //ANY database to do!
  246. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && Database.IsUASupportingBlobStorage) {
  247. database.openAsync(loadFromIndexedDB, noIndexedDB);
  248. }
  249. else {
  250. if (url.indexOf("file:") === -1) {
  251. noIndexedDB();
  252. }
  253. else {
  254. try {
  255. var textureName = url.substring(5).toLowerCase();
  256. var blobURL;
  257. try {
  258. blobURL = URL.createObjectURL(FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  259. }
  260. catch (ex) {
  261. // Chrome doesn't support oneTimeOnly parameter
  262. blobURL = URL.createObjectURL(FilesInput.FilesTextures[textureName]);
  263. }
  264. img.src = blobURL;
  265. }
  266. catch (e) {
  267. img.src = null;
  268. }
  269. }
  270. }
  271. return img;
  272. }
  273. //ANY
  274. public static LoadFile(url: string, callback: (data: any) => void, progressCallBack?: () => void, database?, useArrayBuffer?: boolean, onError?: () => void): void {
  275. url = Tools.CleanUrl(url);
  276. var noIndexedDB = () => {
  277. var request = new XMLHttpRequest();
  278. var loadUrl = Tools.BaseUrl + url;
  279. request.open('GET', loadUrl, true);
  280. if (useArrayBuffer) {
  281. request.responseType = "arraybuffer";
  282. }
  283. request.onprogress = progressCallBack;
  284. request.onreadystatechange = () => {
  285. if (request.readyState === 4) {
  286. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  287. callback(!useArrayBuffer ? request.responseText : request.response);
  288. } else { // Failed
  289. if (onError) {
  290. onError();
  291. } else {
  292. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  293. }
  294. }
  295. }
  296. };
  297. request.send(null);
  298. };
  299. var loadFromIndexedDB = () => {
  300. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  301. };
  302. if (url.indexOf("file:") !== -1) {
  303. var fileName = url.substring(5).toLowerCase();
  304. Tools.ReadFile(FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  305. }
  306. else {
  307. // Caching all files
  308. if (database && database.enableSceneOffline) {
  309. database.openAsync(loadFromIndexedDB, noIndexedDB);
  310. }
  311. else {
  312. noIndexedDB();
  313. }
  314. }
  315. }
  316. public static ReadFileAsDataURL(fileToLoad, callback, progressCallback): void {
  317. var reader = new FileReader();
  318. reader.onload = e => {
  319. //target doesn't have result from ts 1.3
  320. callback(e.target['result']);
  321. };
  322. reader.onprogress = progressCallback;
  323. reader.readAsDataURL(fileToLoad);
  324. }
  325. public static ReadFile(fileToLoad, callback, progressCallBack, useArrayBuffer?: boolean): void {
  326. var reader = new FileReader();
  327. reader.onerror = e => {
  328. Tools.Log("Error while reading file: " + fileToLoad.name);
  329. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  330. };
  331. reader.onload = e => {
  332. //target doesn't have result from ts 1.3
  333. callback(e.target['result']);
  334. };
  335. reader.onprogress = progressCallBack;
  336. if (!useArrayBuffer) {
  337. // Asynchronous read
  338. reader.readAsText(fileToLoad);
  339. }
  340. else {
  341. reader.readAsArrayBuffer(fileToLoad);
  342. }
  343. }
  344. //returns a downloadable url to a file content.
  345. public static FileAsURL(content: string): string {
  346. var fileBlob = new Blob([content]);
  347. var url = window.URL || window.webkitURL;
  348. var link: string = url.createObjectURL(fileBlob);
  349. return link;
  350. }
  351. // Misc.
  352. public static Format(value: number, decimals: number = 2): string {
  353. return value.toFixed(decimals);
  354. }
  355. public static CheckExtends(v: Vector3, min: Vector3, max: Vector3): void {
  356. if (v.x < min.x)
  357. min.x = v.x;
  358. if (v.y < min.y)
  359. min.y = v.y;
  360. if (v.z < min.z)
  361. min.z = v.z;
  362. if (v.x > max.x)
  363. max.x = v.x;
  364. if (v.y > max.y)
  365. max.y = v.y;
  366. if (v.z > max.z)
  367. max.z = v.z;
  368. }
  369. public static DeepCopy(source, destination, doNotCopyList?: string[], mustCopyList?: string[]): void {
  370. for (var prop in source) {
  371. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  372. continue;
  373. }
  374. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  375. continue;
  376. }
  377. var sourceValue = source[prop];
  378. var typeOfSourceValue = typeof sourceValue;
  379. if (typeOfSourceValue === "function") {
  380. continue;
  381. }
  382. if (typeOfSourceValue === "object") {
  383. if (sourceValue instanceof Array) {
  384. destination[prop] = [];
  385. if (sourceValue.length > 0) {
  386. if (typeof sourceValue[0] == "object") {
  387. for (var index = 0; index < sourceValue.length; index++) {
  388. var clonedValue = cloneValue(sourceValue[index], destination);
  389. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  390. destination[prop].push(clonedValue);
  391. }
  392. }
  393. } else {
  394. destination[prop] = sourceValue.slice(0);
  395. }
  396. }
  397. } else {
  398. destination[prop] = cloneValue(sourceValue, destination);
  399. }
  400. } else {
  401. destination[prop] = sourceValue;
  402. }
  403. }
  404. }
  405. public static IsEmpty(obj): boolean {
  406. for (var i in obj) {
  407. return false;
  408. }
  409. return true;
  410. }
  411. public static RegisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  412. for (var index = 0; index < events.length; index++) {
  413. var event = events[index];
  414. window.addEventListener(event.name, event.handler, false);
  415. try {
  416. if (window.parent) {
  417. window.parent.addEventListener(event.name, event.handler, false);
  418. }
  419. } catch (e) {
  420. // Silently fails...
  421. }
  422. }
  423. }
  424. public static UnregisterTopRootEvents(events: { name: string; handler: EventListener }[]): void {
  425. for (var index = 0; index < events.length; index++) {
  426. var event = events[index];
  427. window.removeEventListener(event.name, event.handler);
  428. try {
  429. if (window.parent) {
  430. window.parent.removeEventListener(event.name, event.handler);
  431. }
  432. } catch (e) {
  433. // Silently fails...
  434. }
  435. }
  436. }
  437. public static DumpFramebuffer(width: number, height: number, engine: Engine, successCallback?: (data: string) => void): void {
  438. // Read the contents of the framebuffer
  439. var numberOfChannelsByLine = width * 4;
  440. var halfHeight = height / 2;
  441. //Reading datas from WebGL
  442. var data = engine.readPixels(0, 0, width, height);
  443. //To flip image on Y axis.
  444. for (var i = 0; i < halfHeight; i++) {
  445. for (var j = 0; j < numberOfChannelsByLine; j++) {
  446. var currentCell = j + i * numberOfChannelsByLine;
  447. var targetLine = height - i - 1;
  448. var targetCell = j + targetLine * numberOfChannelsByLine;
  449. var temp = data[currentCell];
  450. data[currentCell] = data[targetCell];
  451. data[targetCell] = temp;
  452. }
  453. }
  454. // Create a 2D canvas to store the result
  455. if (!screenshotCanvas) {
  456. screenshotCanvas = document.createElement('canvas');
  457. }
  458. screenshotCanvas.width = width;
  459. screenshotCanvas.height = height;
  460. var context = screenshotCanvas.getContext('2d');
  461. // Copy the pixels to a 2D canvas
  462. var imageData = context.createImageData(width, height);
  463. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  464. var castData = <Uint8Array>(<any>imageData.data);
  465. castData.set(data);
  466. context.putImageData(imageData, 0, 0);
  467. var base64Image = screenshotCanvas.toDataURL();
  468. if (successCallback) {
  469. successCallback(base64Image);
  470. } else {
  471. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  472. if (("download" in document.createElement("a"))) {
  473. var a = window.document.createElement("a");
  474. a.href = base64Image;
  475. var date = new Date();
  476. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  477. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  478. window.document.body.appendChild(a);
  479. a.addEventListener("click", () => {
  480. a.parentElement.removeChild(a);
  481. });
  482. a.click();
  483. //Or opening a new tab with the image if it is not possible to automatically start download.
  484. } else {
  485. var newWindow = window.open("");
  486. var img = newWindow.document.createElement("img");
  487. img.src = base64Image;
  488. newWindow.document.body.appendChild(img);
  489. }
  490. }
  491. }
  492. public static CreateScreenshot(engine: Engine, camera: Camera, size: any, successCallback?: (data: string) => void): void {
  493. var width: number;
  494. var height: number;
  495. //If a precision value is specified
  496. if (size.precision) {
  497. width = Math.round(engine.getRenderWidth() * size.precision);
  498. height = Math.round(width / engine.getAspectRatio(camera));
  499. size = { width: width, height: height };
  500. }
  501. else if (size.width && size.height) {
  502. width = size.width;
  503. height = size.height;
  504. }
  505. //If passing only width, computing height to keep display canvas ratio.
  506. else if (size.width && !size.height) {
  507. width = size.width;
  508. height = Math.round(width / engine.getAspectRatio(camera));
  509. size = { width: width, height: height };
  510. }
  511. //If passing only height, computing width to keep display canvas ratio.
  512. else if (size.height && !size.width) {
  513. height = size.height;
  514. width = Math.round(height * engine.getAspectRatio(camera));
  515. size = { width: width, height: height };
  516. }
  517. //Assuming here that "size" parameter is a number
  518. else if (!isNaN(size)) {
  519. height = size;
  520. width = size;
  521. }
  522. else {
  523. Tools.Error("Invalid 'size' parameter !");
  524. return;
  525. }
  526. var scene = camera.getScene();
  527. var previousCamera: Camera = null;
  528. if (scene.activeCamera !== camera) {
  529. previousCamera = scene.activeCamera;
  530. scene.activeCamera = camera;
  531. }
  532. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  533. var texture = new RenderTargetTexture("screenShot", size, scene, false, false);
  534. texture.renderList = scene.meshes;
  535. texture.onAfterRender = () => {
  536. Tools.DumpFramebuffer(width, height, engine, successCallback);
  537. };
  538. scene.incrementRenderId();
  539. texture.render(true);
  540. texture.dispose();
  541. if (previousCamera) {
  542. scene.activeCamera = previousCamera;
  543. }
  544. camera.getProjectionMatrix(true); // Force cache refresh;
  545. }
  546. // XHR response validator for local file scenario
  547. public static ValidateXHRData(xhr: XMLHttpRequest, dataType = 7): boolean {
  548. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  549. try {
  550. if (dataType & 1) {
  551. if (xhr.responseText && xhr.responseText.length > 0) {
  552. return true;
  553. } else if (dataType === 1) {
  554. return false;
  555. }
  556. }
  557. if (dataType & 2) {
  558. // Check header width and height since there is no "TGA" magic number
  559. var tgaHeader = Internals.TGATools.GetTGAHeader(xhr.response);
  560. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  561. return true;
  562. } else if (dataType === 2) {
  563. return false;
  564. }
  565. }
  566. if (dataType & 4) {
  567. // Check for the "DDS" magic number
  568. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  569. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  570. return true;
  571. } else {
  572. return false;
  573. }
  574. }
  575. } catch (e) {
  576. // Global protection
  577. }
  578. return false;
  579. }
  580. public static getClassName(obj): string {
  581. var funcNameRegex = /function (.{1,})\(/;
  582. var results = (funcNameRegex).exec((obj).constructor.toString());
  583. return (results && results.length > 1) ? results[1] : "";
  584. }
  585. // Logs
  586. private static _NoneLogLevel = 0;
  587. private static _MessageLogLevel = 1;
  588. private static _WarningLogLevel = 2;
  589. private static _ErrorLogLevel = 4;
  590. private static _LogCache = "";
  591. public static errorsCount = 0;
  592. public static OnNewCacheEntry: (entry: string) => void;
  593. static get NoneLogLevel(): number {
  594. return Tools._NoneLogLevel;
  595. }
  596. static get MessageLogLevel(): number {
  597. return Tools._MessageLogLevel;
  598. }
  599. static get WarningLogLevel(): number {
  600. return Tools._WarningLogLevel;
  601. }
  602. static get ErrorLogLevel(): number {
  603. return Tools._ErrorLogLevel;
  604. }
  605. static get AllLogLevel(): number {
  606. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  607. }
  608. private static _AddLogEntry(entry: string) {
  609. Tools._LogCache = entry + Tools._LogCache;
  610. if (Tools.OnNewCacheEntry) {
  611. Tools.OnNewCacheEntry(entry);
  612. }
  613. }
  614. private static _FormatMessage(message: string): string {
  615. var padStr = i => (i < 10) ? "0" + i : "" + i;
  616. var date = new Date();
  617. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  618. }
  619. public static Log: (message: string) => void = Tools._LogEnabled;
  620. private static _LogDisabled(message: string): void {
  621. // nothing to do
  622. }
  623. private static _LogEnabled(message: string): void {
  624. var formattedMessage = Tools._FormatMessage(message);
  625. console.log("BJS - " + formattedMessage);
  626. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  627. Tools._AddLogEntry(entry);
  628. }
  629. public static Warn: (message: string) => void = Tools._WarnEnabled;
  630. private static _WarnDisabled(message: string): void {
  631. // nothing to do
  632. }
  633. private static _WarnEnabled(message: string): void {
  634. var formattedMessage = Tools._FormatMessage(message);
  635. console.warn("BJS - " + formattedMessage);
  636. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  637. Tools._AddLogEntry(entry);
  638. }
  639. public static Error: (message: string) => void = Tools._ErrorEnabled;
  640. private static _ErrorDisabled(message: string): void {
  641. // nothing to do
  642. }
  643. private static _ErrorEnabled(message: string): void {
  644. Tools.errorsCount++;
  645. var formattedMessage = Tools._FormatMessage(message);
  646. console.error("BJS - " + formattedMessage);
  647. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  648. Tools._AddLogEntry(entry);
  649. }
  650. public static get LogCache(): string {
  651. return Tools._LogCache;
  652. }
  653. public static ClearLogCache(): void {
  654. Tools._LogCache = "";
  655. Tools.errorsCount = 0;
  656. }
  657. public static set LogLevels(level: number) {
  658. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  659. Tools.Log = Tools._LogEnabled;
  660. }
  661. else {
  662. Tools.Log = Tools._LogDisabled;
  663. }
  664. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  665. Tools.Warn = Tools._WarnEnabled;
  666. }
  667. else {
  668. Tools.Warn = Tools._WarnDisabled;
  669. }
  670. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  671. Tools.Error = Tools._ErrorEnabled;
  672. }
  673. else {
  674. Tools.Error = Tools._ErrorDisabled;
  675. }
  676. }
  677. // Performances
  678. private static _PerformanceNoneLogLevel = 0;
  679. private static _PerformanceUserMarkLogLevel = 1;
  680. private static _PerformanceConsoleLogLevel = 2;
  681. private static _performance: Performance = window.performance;
  682. static get PerformanceNoneLogLevel(): number {
  683. return Tools._PerformanceNoneLogLevel;
  684. }
  685. static get PerformanceUserMarkLogLevel(): number {
  686. return Tools._PerformanceUserMarkLogLevel;
  687. }
  688. static get PerformanceConsoleLogLevel(): number {
  689. return Tools._PerformanceConsoleLogLevel;
  690. }
  691. public static set PerformanceLogLevel(level: number) {
  692. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  693. Tools.StartPerformanceCounter = Tools._StartUserMark;
  694. Tools.EndPerformanceCounter = Tools._EndUserMark;
  695. return;
  696. }
  697. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  698. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  699. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  700. return;
  701. }
  702. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  703. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  704. }
  705. static _StartPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  706. }
  707. static _EndPerformanceCounterDisabled(counterName: string, condition?: boolean): void {
  708. }
  709. static _StartUserMark(counterName: string, condition = true): void {
  710. if (!condition || !Tools._performance.mark) {
  711. return;
  712. }
  713. Tools._performance.mark(counterName + "-Begin");
  714. }
  715. static _EndUserMark(counterName: string, condition = true): void {
  716. if (!condition || !Tools._performance.mark) {
  717. return;
  718. }
  719. Tools._performance.mark(counterName + "-End");
  720. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  721. }
  722. static _StartPerformanceConsole(counterName: string, condition = true): void {
  723. if (!condition) {
  724. return;
  725. }
  726. Tools._StartUserMark(counterName, condition);
  727. if (console.time) {
  728. console.time(counterName);
  729. }
  730. }
  731. static _EndPerformanceConsole(counterName: string, condition = true): void {
  732. if (!condition) {
  733. return;
  734. }
  735. Tools._EndUserMark(counterName, condition);
  736. if (console.time) {
  737. console.timeEnd(counterName);
  738. }
  739. }
  740. public static StartPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._StartPerformanceCounterDisabled;
  741. public static EndPerformanceCounter: (counterName: string, condition?: boolean) => void = Tools._EndPerformanceCounterDisabled;
  742. public static get Now(): number {
  743. if (window.performance && window.performance.now) {
  744. return window.performance.now();
  745. }
  746. return new Date().getTime();
  747. }
  748. }
  749. /**
  750. * An implementation of a loop for asynchronous functions.
  751. */
  752. export class AsyncLoop {
  753. public index: number;
  754. private _done: boolean;
  755. /**
  756. * Constroctor.
  757. * @param iterations the number of iterations.
  758. * @param _fn the function to run each iteration
  759. * @param _successCallback the callback that will be called upon succesful execution
  760. * @param offset starting offset.
  761. */
  762. constructor(public iterations: number, private _fn: (asyncLoop: AsyncLoop) => void, private _successCallback: () => void, offset: number = 0) {
  763. this.index = offset - 1;
  764. this._done = false;
  765. }
  766. /**
  767. * Execute the next iteration. Must be called after the last iteration was finished.
  768. */
  769. public executeNext(): void {
  770. if (!this._done) {
  771. if (this.index + 1 < this.iterations) {
  772. ++this.index;
  773. this._fn(this);
  774. } else {
  775. this.breakLoop();
  776. }
  777. }
  778. }
  779. /**
  780. * Break the loop and run the success callback.
  781. */
  782. public breakLoop(): void {
  783. this._done = true;
  784. this._successCallback();
  785. }
  786. /**
  787. * Helper function
  788. */
  789. public static Run(iterations: number, _fn: (asyncLoop: AsyncLoop) => void, _successCallback: () => void, offset: number = 0): AsyncLoop {
  790. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  791. loop.executeNext();
  792. return loop;
  793. }
  794. /**
  795. * A for-loop that will run a given number of iterations synchronous and the rest async.
  796. * @param iterations total number of iterations
  797. * @param syncedIterations number of synchronous iterations in each async iteration.
  798. * @param fn the function to call each iteration.
  799. * @param callback a success call back that will be called when iterating stops.
  800. * @param breakFunction a break condition (optional)
  801. * @param timeout timeout settings for the setTimeout function. default - 0.
  802. * @constructor
  803. */
  804. public static SyncAsyncForLoop(iterations: number, syncedIterations: number, fn: (iteration: number) => void, callback: () => void, breakFunction?: () => boolean, timeout: number = 0) {
  805. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), (loop: AsyncLoop) => {
  806. if (breakFunction && breakFunction()) loop.breakLoop();
  807. else {
  808. setTimeout(() => {
  809. for (var i = 0; i < syncedIterations; ++i) {
  810. var iteration = (loop.index * syncedIterations) + i;
  811. if (iteration >= iterations) break;
  812. fn(iteration);
  813. if (breakFunction && breakFunction()) {
  814. loop.breakLoop();
  815. break;
  816. }
  817. }
  818. loop.executeNext();
  819. }, timeout);
  820. }
  821. }, callback);
  822. }
  823. }
  824. }