babylon.tools.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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 || 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. 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. //target doesn't have result from ts 1.3
  224. callback(e.target['result']);
  225. };
  226. reader.onprogress = progressCallback;
  227. reader.readAsDataURL(fileToLoad);
  228. };
  229. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  230. var reader = new FileReader();
  231. reader.onload = function (e) {
  232. //target doesn't have result from ts 1.3
  233. callback(e.target['result']);
  234. };
  235. reader.onprogress = progressCallBack;
  236. if (!useArrayBuffer) {
  237. // Asynchronous read
  238. reader.readAsText(fileToLoad);
  239. }
  240. else {
  241. reader.readAsArrayBuffer(fileToLoad);
  242. }
  243. };
  244. // Misc.
  245. Tools.Clamp = function (value, min, max) {
  246. if (min === void 0) { min = 0; }
  247. if (max === void 0) { max = 1; }
  248. return Math.min(max, Math.max(min, value));
  249. };
  250. // Returns -1 when value is a negative number and
  251. // +1 when value is a positive number.
  252. Tools.Sign = function (value) {
  253. value = +value; // convert to a number
  254. if (value === 0 || isNaN(value))
  255. return value;
  256. return value > 0 ? 1 : -1;
  257. };
  258. Tools.Format = function (value, decimals) {
  259. if (decimals === void 0) { decimals = 2; }
  260. return value.toFixed(decimals);
  261. };
  262. Tools.CheckExtends = function (v, min, max) {
  263. if (v.x < min.x)
  264. min.x = v.x;
  265. if (v.y < min.y)
  266. min.y = v.y;
  267. if (v.z < min.z)
  268. min.z = v.z;
  269. if (v.x > max.x)
  270. max.x = v.x;
  271. if (v.y > max.y)
  272. max.y = v.y;
  273. if (v.z > max.z)
  274. max.z = v.z;
  275. };
  276. Tools.WithinEpsilon = function (a, b, epsilon) {
  277. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  278. var num = a - b;
  279. return -epsilon <= num && num <= epsilon;
  280. };
  281. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  282. for (var prop in source) {
  283. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  284. continue;
  285. }
  286. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  287. continue;
  288. }
  289. var sourceValue = source[prop];
  290. var typeOfSourceValue = typeof sourceValue;
  291. if (typeOfSourceValue === "function") {
  292. continue;
  293. }
  294. if (typeOfSourceValue === "object") {
  295. if (sourceValue instanceof Array) {
  296. destination[prop] = [];
  297. if (sourceValue.length > 0) {
  298. if (typeof sourceValue[0] == "object") {
  299. for (var index = 0; index < sourceValue.length; index++) {
  300. var clonedValue = cloneValue(sourceValue[index], destination);
  301. if (destination[prop].indexOf(clonedValue) === -1) {
  302. destination[prop].push(clonedValue);
  303. }
  304. }
  305. }
  306. else {
  307. destination[prop] = sourceValue.slice(0);
  308. }
  309. }
  310. }
  311. else {
  312. destination[prop] = cloneValue(sourceValue, destination);
  313. }
  314. }
  315. else {
  316. destination[prop] = sourceValue;
  317. }
  318. }
  319. };
  320. Tools.IsEmpty = function (obj) {
  321. for (var i in obj) {
  322. return false;
  323. }
  324. return true;
  325. };
  326. Tools.RegisterTopRootEvents = function (events) {
  327. for (var index = 0; index < events.length; index++) {
  328. var event = events[index];
  329. window.addEventListener(event.name, event.handler, false);
  330. try {
  331. if (window.parent) {
  332. window.parent.addEventListener(event.name, event.handler, false);
  333. }
  334. }
  335. catch (e) {
  336. }
  337. }
  338. };
  339. Tools.UnregisterTopRootEvents = function (events) {
  340. for (var index = 0; index < events.length; index++) {
  341. var event = events[index];
  342. window.removeEventListener(event.name, event.handler);
  343. try {
  344. if (window.parent) {
  345. window.parent.removeEventListener(event.name, event.handler);
  346. }
  347. }
  348. catch (e) {
  349. }
  350. }
  351. };
  352. Tools.CreateScreenshot = function (engine, camera, size) {
  353. var width;
  354. var height;
  355. var scene = camera.getScene();
  356. var previousCamera = null;
  357. if (scene.activeCamera !== camera) {
  358. previousCamera = scene.activeCamera;
  359. scene.activeCamera = camera;
  360. }
  361. //If a precision value is specified
  362. if (size.precision) {
  363. width = Math.round(engine.getRenderWidth() * size.precision);
  364. height = Math.round(width / engine.getAspectRatio(camera));
  365. size = { width: width, height: height };
  366. }
  367. else if (size.width && size.height) {
  368. width = size.width;
  369. height = size.height;
  370. }
  371. else if (size.width && !size.height) {
  372. width = size.width;
  373. height = Math.round(width / engine.getAspectRatio(camera));
  374. size = { width: width, height: height };
  375. }
  376. else if (size.height && !size.width) {
  377. height = size.height;
  378. width = Math.round(height * engine.getAspectRatio(camera));
  379. size = { width: width, height: height };
  380. }
  381. else if (!isNaN(size)) {
  382. height = size;
  383. width = size;
  384. }
  385. else {
  386. Tools.Error("Invalid 'size' parameter !");
  387. return;
  388. }
  389. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  390. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  391. texture.renderList = scene.meshes;
  392. texture.onAfterRender = function () {
  393. // Read the contents of the framebuffer
  394. var numberOfChannelsByLine = width * 4;
  395. var halfHeight = height / 2;
  396. //Reading datas from WebGL
  397. var data = engine.readPixels(0, 0, width, height);
  398. for (var i = 0; i < halfHeight; i++) {
  399. for (var j = 0; j < numberOfChannelsByLine; j++) {
  400. var currentCell = j + i * numberOfChannelsByLine;
  401. var targetLine = height - i - 1;
  402. var targetCell = j + targetLine * numberOfChannelsByLine;
  403. var temp = data[currentCell];
  404. data[currentCell] = data[targetCell];
  405. data[targetCell] = temp;
  406. }
  407. }
  408. // Create a 2D canvas to store the result
  409. if (!screenshotCanvas) {
  410. screenshotCanvas = document.createElement('canvas');
  411. }
  412. screenshotCanvas.width = width;
  413. screenshotCanvas.height = height;
  414. var context = screenshotCanvas.getContext('2d');
  415. // Copy the pixels to a 2D canvas
  416. var imageData = context.createImageData(width, height);
  417. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  418. var data = imageData.data;
  419. data.set(data);
  420. context.putImageData(imageData, 0, 0);
  421. var base64Image = screenshotCanvas.toDataURL();
  422. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  423. if (("download" in document.createElement("a"))) {
  424. var a = window.document.createElement("a");
  425. a.href = base64Image;
  426. var date = new Date();
  427. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  428. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  429. window.document.body.appendChild(a);
  430. a.addEventListener("click", function () {
  431. a.parentElement.removeChild(a);
  432. });
  433. a.click();
  434. }
  435. else {
  436. var newWindow = window.open("");
  437. var img = newWindow.document.createElement("img");
  438. img.src = base64Image;
  439. newWindow.document.body.appendChild(img);
  440. }
  441. };
  442. scene.incrementRenderId();
  443. texture.render(true);
  444. texture.dispose();
  445. if (previousCamera) {
  446. scene.activeCamera = previousCamera;
  447. }
  448. };
  449. // XHR response validator for local file scenario
  450. Tools.ValidateXHRData = function (xhr, dataType) {
  451. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  452. if (dataType === void 0) { dataType = 7; }
  453. try {
  454. if (dataType & 1) {
  455. if (xhr.responseText && xhr.responseText.length > 0) {
  456. return true;
  457. }
  458. else if (dataType === 1) {
  459. return false;
  460. }
  461. }
  462. if (dataType & 2) {
  463. // Check header width and height since there is no "TGA" magic number
  464. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  465. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  466. return true;
  467. }
  468. else if (dataType === 2) {
  469. return false;
  470. }
  471. }
  472. if (dataType & 4) {
  473. // Check for the "DDS" magic number
  474. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  475. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  476. return true;
  477. }
  478. else {
  479. return false;
  480. }
  481. }
  482. }
  483. catch (e) {
  484. }
  485. return false;
  486. };
  487. Object.defineProperty(Tools, "NoneLogLevel", {
  488. get: function () {
  489. return Tools._NoneLogLevel;
  490. },
  491. enumerable: true,
  492. configurable: true
  493. });
  494. Object.defineProperty(Tools, "MessageLogLevel", {
  495. get: function () {
  496. return Tools._MessageLogLevel;
  497. },
  498. enumerable: true,
  499. configurable: true
  500. });
  501. Object.defineProperty(Tools, "WarningLogLevel", {
  502. get: function () {
  503. return Tools._WarningLogLevel;
  504. },
  505. enumerable: true,
  506. configurable: true
  507. });
  508. Object.defineProperty(Tools, "ErrorLogLevel", {
  509. get: function () {
  510. return Tools._ErrorLogLevel;
  511. },
  512. enumerable: true,
  513. configurable: true
  514. });
  515. Object.defineProperty(Tools, "AllLogLevel", {
  516. get: function () {
  517. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  518. },
  519. enumerable: true,
  520. configurable: true
  521. });
  522. Tools._AddLogEntry = function (entry) {
  523. Tools._LogCache = entry + Tools._LogCache;
  524. if (Tools.OnNewCacheEntry) {
  525. Tools.OnNewCacheEntry(entry);
  526. }
  527. };
  528. Tools._FormatMessage = function (message) {
  529. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  530. var date = new Date();
  531. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  532. };
  533. Tools._LogDisabled = function (message) {
  534. // nothing to do
  535. };
  536. Tools._LogEnabled = function (message) {
  537. var formattedMessage = Tools._FormatMessage(message);
  538. console.log("BJS - " + formattedMessage);
  539. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  540. Tools._AddLogEntry(entry);
  541. };
  542. Tools._WarnDisabled = function (message) {
  543. // nothing to do
  544. };
  545. Tools._WarnEnabled = function (message) {
  546. var formattedMessage = Tools._FormatMessage(message);
  547. console.warn("BJS - " + formattedMessage);
  548. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  549. Tools._AddLogEntry(entry);
  550. };
  551. Tools._ErrorDisabled = function (message) {
  552. // nothing to do
  553. };
  554. Tools._ErrorEnabled = function (message) {
  555. var formattedMessage = Tools._FormatMessage(message);
  556. console.error("BJS - " + formattedMessage);
  557. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  558. Tools._AddLogEntry(entry);
  559. };
  560. Object.defineProperty(Tools, "LogCache", {
  561. get: function () {
  562. return Tools._LogCache;
  563. },
  564. enumerable: true,
  565. configurable: true
  566. });
  567. Object.defineProperty(Tools, "LogLevels", {
  568. set: function (level) {
  569. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  570. Tools.Log = Tools._LogEnabled;
  571. }
  572. else {
  573. Tools.Log = Tools._LogDisabled;
  574. }
  575. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  576. Tools.Warn = Tools._WarnEnabled;
  577. }
  578. else {
  579. Tools.Warn = Tools._WarnDisabled;
  580. }
  581. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  582. Tools.Error = Tools._ErrorEnabled;
  583. }
  584. else {
  585. Tools.Error = Tools._ErrorDisabled;
  586. }
  587. },
  588. enumerable: true,
  589. configurable: true
  590. });
  591. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  592. get: function () {
  593. return Tools._PerformanceNoneLogLevel;
  594. },
  595. enumerable: true,
  596. configurable: true
  597. });
  598. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  599. get: function () {
  600. return Tools._PerformanceUserMarkLogLevel;
  601. },
  602. enumerable: true,
  603. configurable: true
  604. });
  605. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  606. get: function () {
  607. return Tools._PerformanceConsoleLogLevel;
  608. },
  609. enumerable: true,
  610. configurable: true
  611. });
  612. Object.defineProperty(Tools, "PerformanceLogLevel", {
  613. set: function (level) {
  614. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  615. Tools.StartPerformanceCounter = Tools._StartUserMark;
  616. Tools.EndPerformanceCounter = Tools._EndUserMark;
  617. return;
  618. }
  619. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  620. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  621. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  622. return;
  623. }
  624. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  625. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  626. },
  627. enumerable: true,
  628. configurable: true
  629. });
  630. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  631. };
  632. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  633. };
  634. Tools._StartUserMark = function (counterName, condition) {
  635. if (condition === void 0) { condition = true; }
  636. if (!condition || !Tools._performance.mark) {
  637. return;
  638. }
  639. Tools._performance.mark(counterName + "-Begin");
  640. };
  641. Tools._EndUserMark = function (counterName, condition) {
  642. if (condition === void 0) { condition = true; }
  643. if (!condition || !Tools._performance.mark) {
  644. return;
  645. }
  646. Tools._performance.mark(counterName + "-End");
  647. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  648. };
  649. Tools._StartPerformanceConsole = function (counterName, condition) {
  650. if (condition === void 0) { condition = true; }
  651. if (!condition) {
  652. return;
  653. }
  654. Tools._StartUserMark(counterName, condition);
  655. if (console.time) {
  656. console.time(counterName);
  657. }
  658. };
  659. Tools._EndPerformanceConsole = function (counterName, condition) {
  660. if (condition === void 0) { condition = true; }
  661. if (!condition) {
  662. return;
  663. }
  664. Tools._EndUserMark(counterName, condition);
  665. if (console.time) {
  666. console.timeEnd(counterName);
  667. }
  668. };
  669. Object.defineProperty(Tools, "Now", {
  670. get: function () {
  671. if (window.performance && window.performance.now) {
  672. return window.performance.now();
  673. }
  674. return new Date().getTime();
  675. },
  676. enumerable: true,
  677. configurable: true
  678. });
  679. // Deprecated
  680. Tools.GetFps = function () {
  681. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  682. return 0;
  683. };
  684. Tools.BaseUrl = "";
  685. Tools.GetExponantOfTwo = function (value, max) {
  686. var count = 1;
  687. do {
  688. count *= 2;
  689. } while (count < value);
  690. if (count > max)
  691. count = max;
  692. return count;
  693. };
  694. // Logs
  695. Tools._NoneLogLevel = 0;
  696. Tools._MessageLogLevel = 1;
  697. Tools._WarningLogLevel = 2;
  698. Tools._ErrorLogLevel = 4;
  699. Tools._LogCache = "";
  700. Tools.Log = Tools._LogEnabled;
  701. Tools.Warn = Tools._WarnEnabled;
  702. Tools.Error = Tools._ErrorEnabled;
  703. // Performances
  704. Tools._PerformanceNoneLogLevel = 0;
  705. Tools._PerformanceUserMarkLogLevel = 1;
  706. Tools._PerformanceConsoleLogLevel = 2;
  707. Tools._performance = window.performance;
  708. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  709. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  710. return Tools;
  711. })();
  712. BABYLON.Tools = Tools;
  713. /**
  714. * An implementation of a loop for asynchronous functions.
  715. */
  716. var AsyncLoop = (function () {
  717. /**
  718. * Constroctor.
  719. * @param iterations the number of iterations.
  720. * @param _fn the function to run each iteration
  721. * @param _successCallback the callback that will be called upon succesful execution
  722. * @param offset starting offset.
  723. */
  724. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  725. if (offset === void 0) { offset = 0; }
  726. this.iterations = iterations;
  727. this._fn = _fn;
  728. this._successCallback = _successCallback;
  729. this.index = offset - 1;
  730. this._done = false;
  731. }
  732. /**
  733. * Execute the next iteration. Must be called after the last iteration was finished.
  734. */
  735. AsyncLoop.prototype.executeNext = function () {
  736. if (!this._done) {
  737. if (this.index + 1 < this.iterations) {
  738. ++this.index;
  739. this._fn(this);
  740. }
  741. else {
  742. this.breakLoop();
  743. }
  744. }
  745. };
  746. /**
  747. * Break the loop and run the success callback.
  748. */
  749. AsyncLoop.prototype.breakLoop = function () {
  750. this._done = true;
  751. this._successCallback();
  752. };
  753. /**
  754. * Helper function
  755. */
  756. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  757. if (offset === void 0) { offset = 0; }
  758. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  759. loop.executeNext();
  760. return loop;
  761. };
  762. /**
  763. * A for-loop that will run a given number of iterations synchronous and the rest async.
  764. * @param iterations total number of iterations
  765. * @param syncedIterations number of synchronous iterations in each async iteration.
  766. * @param fn the function to call each iteration.
  767. * @param callback a success call back that will be called when iterating stops.
  768. * @param breakFunction a break condition (optional)
  769. * @param timeout timeout settings for the setTimeout function. default - 0.
  770. * @constructor
  771. */
  772. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  773. if (timeout === void 0) { timeout = 0; }
  774. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  775. if (breakFunction && breakFunction())
  776. loop.breakLoop();
  777. else {
  778. setTimeout(function () {
  779. for (var i = 0; i < syncedIterations; ++i) {
  780. var iteration = (loop.index * syncedIterations) + i;
  781. if (iteration >= iterations)
  782. break;
  783. fn(iteration);
  784. if (breakFunction && breakFunction()) {
  785. loop.breakLoop();
  786. break;
  787. }
  788. }
  789. loop.executeNext();
  790. }, timeout);
  791. }
  792. }, callback);
  793. };
  794. return AsyncLoop;
  795. })();
  796. BABYLON.AsyncLoop = AsyncLoop;
  797. })(BABYLON || (BABYLON = {}));
  798. //# sourceMappingURL=babylon.tools.js.map