babylon.tools.js 40 KB

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