babylon.tools.js 39 KB

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