babylon.tools.js 40 KB

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