babylon.tools.js 33 KB

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