babylon.tools.js 33 KB

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