babylon.tools.js 33 KB

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