babylon.tools.js 33 KB

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