babylon.tools.js 33 KB

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