babylon.tools.js 33 KB

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