babylon.tools.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. 
  2. var BABYLON;
  3. (function (BABYLON) {
  4. // Screenshots
  5. var screenshotCanvas;
  6. // FPS
  7. var fpsRange = 60;
  8. var previousFramesDuration = [];
  9. var fps = 60;
  10. var deltaTime = 0;
  11. var cloneValue = function (source, destinationObject) {
  12. if (!source)
  13. return null;
  14. if (source instanceof BABYLON.Mesh) {
  15. return null;
  16. }
  17. if (source instanceof BABYLON.SubMesh) {
  18. return source.clone(destinationObject);
  19. } else if (source.clone) {
  20. return source.clone();
  21. }
  22. return null;
  23. };
  24. var Tools = (function () {
  25. function Tools() {
  26. }
  27. Tools.GetFilename = function (path) {
  28. var index = path.lastIndexOf("/");
  29. if (index < 0)
  30. return path;
  31. return path.substring(index + 1);
  32. };
  33. Tools.GetDOMTextContent = function (element) {
  34. var result = "";
  35. var child = element.firstChild;
  36. while (child) {
  37. if (child.nodeType == 3) {
  38. result += child.textContent;
  39. }
  40. child = child.nextSibling;
  41. }
  42. return result;
  43. };
  44. Tools.ToDegrees = function (angle) {
  45. return angle * 180 / Math.PI;
  46. };
  47. Tools.ToRadians = function (angle) {
  48. return angle * Math.PI / 180;
  49. };
  50. Tools.ExtractMinAndMax = function (positions, start, count) {
  51. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  52. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  53. for (var index = start; index < start + count; index++) {
  54. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  55. minimum = BABYLON.Vector3.Minimize(current, minimum);
  56. maximum = BABYLON.Vector3.Maximize(current, maximum);
  57. }
  58. return {
  59. minimum: minimum,
  60. maximum: maximum
  61. };
  62. };
  63. Tools.MakeArray = function (obj, allowsNullUndefined) {
  64. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  65. return undefined;
  66. return Array.isArray(obj) ? obj : [obj];
  67. };
  68. // Misc.
  69. Tools.GetPointerPrefix = function () {
  70. var eventPrefix = "pointer";
  71. // Check if hand.js is referenced or if the browser natively supports pointer events
  72. if (!navigator.pointerEnabled) {
  73. eventPrefix = "mouse";
  74. }
  75. return eventPrefix;
  76. };
  77. Tools.QueueNewFrame = function (func) {
  78. if (window.requestAnimationFrame)
  79. window.requestAnimationFrame(func);
  80. else if (window.msRequestAnimationFrame)
  81. window.msRequestAnimationFrame(func);
  82. else if (window.webkitRequestAnimationFrame)
  83. window.webkitRequestAnimationFrame(func);
  84. else if (window.mozRequestAnimationFrame)
  85. window.mozRequestAnimationFrame(func);
  86. else if (window.oRequestAnimationFrame)
  87. window.oRequestAnimationFrame(func);
  88. else {
  89. window.setTimeout(func, 16);
  90. }
  91. };
  92. Tools.RequestFullscreen = function (element) {
  93. if (element.requestFullscreen)
  94. element.requestFullscreen();
  95. else if (element.msRequestFullscreen)
  96. element.msRequestFullscreen();
  97. else if (element.webkitRequestFullscreen)
  98. element.webkitRequestFullscreen();
  99. else if (element.mozRequestFullScreen)
  100. element.mozRequestFullScreen();
  101. };
  102. Tools.ExitFullscreen = function () {
  103. if (document.exitFullscreen) {
  104. document.exitFullscreen();
  105. } else if (document.mozCancelFullScreen) {
  106. document.mozCancelFullScreen();
  107. } else if (document.webkitCancelFullScreen) {
  108. document.webkitCancelFullScreen();
  109. } else if (document.msCancelFullScreen) {
  110. document.msCancelFullScreen();
  111. }
  112. };
  113. // External files
  114. Tools.CleanUrl = function (url) {
  115. url = url.replace(/#/mg, "%23");
  116. return url;
  117. };
  118. Tools.LoadImage = function (url, onload, onerror, database) {
  119. url = Tools.CleanUrl(url);
  120. var img = new Image();
  121. img.crossOrigin = 'anonymous';
  122. img.onload = function () {
  123. onload(img);
  124. };
  125. img.onerror = function (err) {
  126. onerror(img, err);
  127. };
  128. var noIndexedDB = function () {
  129. img.src = url;
  130. };
  131. var loadFromIndexedDB = function () {
  132. database.loadImageFromDB(url, img);
  133. };
  134. //ANY database to do!
  135. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  136. database.openAsync(loadFromIndexedDB, noIndexedDB);
  137. } else {
  138. if (url.indexOf("file:") === -1) {
  139. noIndexedDB();
  140. } else {
  141. try {
  142. var textureName = url.substring(5);
  143. var blobURL;
  144. try {
  145. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  146. } catch (ex) {
  147. // Chrome doesn't support oneTimeOnly parameter
  148. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  149. }
  150. img.src = blobURL;
  151. } catch (e) {
  152. Tools.Log("Error while trying to load texture: " + textureName);
  153. img.src = null;
  154. }
  155. }
  156. }
  157. return img;
  158. };
  159. //ANY
  160. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer) {
  161. url = Tools.CleanUrl(url);
  162. var noIndexedDB = function () {
  163. var request = new XMLHttpRequest();
  164. var loadUrl = Tools.BaseUrl + url;
  165. request.open('GET', loadUrl, true);
  166. if (useArrayBuffer) {
  167. request.responseType = "arraybuffer";
  168. }
  169. request.onprogress = progressCallBack;
  170. request.onreadystatechange = function () {
  171. if (request.readyState == 4) {
  172. if (request.status == 200) {
  173. callback(!useArrayBuffer ? request.responseText : request.response);
  174. } else {
  175. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  176. }
  177. }
  178. };
  179. request.send(null);
  180. };
  181. var loadFromIndexedDB = function () {
  182. database.loadSceneFromDB(url, callback, progressCallBack, noIndexedDB);
  183. };
  184. // Caching only scenes files
  185. if (database && url.indexOf(".babylon") !== -1 && (database.enableSceneOffline)) {
  186. database.openAsync(loadFromIndexedDB, noIndexedDB);
  187. } else {
  188. noIndexedDB();
  189. }
  190. };
  191. Tools.ReadFile = function (fileToLoad, callback, progressCallBack) {
  192. var reader = new FileReader();
  193. reader.onload = function (e) {
  194. callback(e.target.result);
  195. };
  196. reader.onprogress = progressCallBack;
  197. // Asynchronous read
  198. reader.readAsText(fileToLoad);
  199. };
  200. // Misc.
  201. Tools.WithinEpsilon = function (a, b) {
  202. var num = a - b;
  203. return -1.401298E-45 <= num && num <= 1.401298E-45;
  204. };
  205. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  206. for (var prop in source) {
  207. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  208. continue;
  209. }
  210. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  211. continue;
  212. }
  213. var sourceValue = source[prop];
  214. var typeOfSourceValue = typeof sourceValue;
  215. if (typeOfSourceValue == "function") {
  216. continue;
  217. }
  218. if (typeOfSourceValue == "object") {
  219. if (sourceValue instanceof Array) {
  220. destination[prop] = [];
  221. if (sourceValue.length > 0) {
  222. if (typeof sourceValue[0] == "object") {
  223. for (var index = 0; index < sourceValue.length; index++) {
  224. var clonedValue = cloneValue(sourceValue[index], destination);
  225. if (destination[prop].indexOf(clonedValue) === -1) {
  226. destination[prop].push(clonedValue);
  227. }
  228. }
  229. } else {
  230. destination[prop] = sourceValue.slice(0);
  231. }
  232. }
  233. } else {
  234. destination[prop] = cloneValue(sourceValue, destination);
  235. }
  236. } else {
  237. destination[prop] = sourceValue;
  238. }
  239. }
  240. };
  241. Tools.IsEmpty = function (obj) {
  242. for (var i in obj) {
  243. return false;
  244. }
  245. return true;
  246. };
  247. Tools.RegisterTopRootEvents = function (events) {
  248. for (var index = 0; index < events.length; index++) {
  249. var event = events[index];
  250. window.addEventListener(event.name, event.handler, false);
  251. try {
  252. if (window.parent) {
  253. window.parent.addEventListener(event.name, event.handler, false);
  254. }
  255. } catch (e) {
  256. // Silently fails...
  257. }
  258. }
  259. };
  260. Tools.UnregisterTopRootEvents = function (events) {
  261. for (var index = 0; index < events.length; index++) {
  262. var event = events[index];
  263. window.removeEventListener(event.name, event.handler);
  264. try {
  265. if (window.parent) {
  266. window.parent.removeEventListener(event.name, event.handler);
  267. }
  268. } catch (e) {
  269. // Silently fails...
  270. }
  271. }
  272. };
  273. Tools.GetFps = function () {
  274. return fps;
  275. };
  276. Tools.GetDeltaTime = function () {
  277. return deltaTime;
  278. };
  279. Tools._MeasureFps = function () {
  280. previousFramesDuration.push((new Date).getTime());
  281. var length = previousFramesDuration.length;
  282. if (length >= 2) {
  283. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  284. }
  285. if (length >= fpsRange) {
  286. if (length > fpsRange) {
  287. previousFramesDuration.splice(0, 1);
  288. length = previousFramesDuration.length;
  289. }
  290. var sum = 0;
  291. for (var id = 0; id < length - 1; id++) {
  292. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  293. }
  294. fps = 1000.0 / (sum / (length - 1));
  295. }
  296. };
  297. Tools.CreateScreenshot = function (engine, camera, size) {
  298. var width;
  299. var height;
  300. var scene = camera.getScene();
  301. var previousCamera = null;
  302. if (scene.activeCamera !== camera) {
  303. previousCamera = scene.activeCamera;
  304. scene.activeCamera = camera;
  305. }
  306. //If a precision value is specified
  307. if (size.precision) {
  308. width = Math.round(engine.getRenderWidth() * size.precision);
  309. height = Math.round(width / engine.getAspectRatio(camera));
  310. size = { width: width, height: height };
  311. } else if (size.width && size.height) {
  312. width = size.width;
  313. height = size.height;
  314. } else if (size.width && !size.height) {
  315. width = size.width;
  316. height = Math.round(width / engine.getAspectRatio(camera));
  317. size = { width: width, height: height };
  318. } else if (size.height && !size.width) {
  319. height = size.height;
  320. width = Math.round(height * engine.getAspectRatio(camera));
  321. size = { width: width, height: height };
  322. } else if (!isNaN(size)) {
  323. height = size;
  324. width = size;
  325. } else {
  326. Tools.Error("Invalid 'size' parameter !");
  327. return;
  328. }
  329. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  330. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0]);
  331. texture.renderList = engine.scenes[0].meshes;
  332. texture.onAfterRender = function () {
  333. // Read the contents of the framebuffer
  334. var numberOfChannelsByLine = width * 4;
  335. var halfHeight = height / 2;
  336. //Reading datas from WebGL
  337. var data = engine.readPixels(0, 0, width, height);
  338. for (var i = 0; i < halfHeight; i++) {
  339. for (var j = 0; j < numberOfChannelsByLine; j++) {
  340. var currentCell = j + i * numberOfChannelsByLine;
  341. var targetLine = height - i - 1;
  342. var targetCell = j + targetLine * numberOfChannelsByLine;
  343. var temp = data[currentCell];
  344. data[currentCell] = data[targetCell];
  345. data[targetCell] = temp;
  346. }
  347. }
  348. // Create a 2D canvas to store the result
  349. if (!screenshotCanvas) {
  350. screenshotCanvas = document.createElement('canvas');
  351. }
  352. screenshotCanvas.width = width;
  353. screenshotCanvas.height = height;
  354. var context = screenshotCanvas.getContext('2d');
  355. // Copy the pixels to a 2D canvas
  356. var imageData = context.createImageData(width, height);
  357. imageData.data.set(data);
  358. context.putImageData(imageData, 0, 0);
  359. var base64Image = screenshotCanvas.toDataURL();
  360. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  361. if (("download" in document.createElement("a"))) {
  362. var a = window.document.createElement("a");
  363. a.href = base64Image;
  364. var date = new Date();
  365. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  366. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  367. window.document.body.appendChild(a);
  368. a.addEventListener("click", function () {
  369. a.parentElement.removeChild(a);
  370. });
  371. a.click();
  372. //Or opening a new tab with the image if it is not possible to automatically start download.
  373. } else {
  374. var newWindow = window.open("");
  375. var img = newWindow.document.createElement("img");
  376. img.src = base64Image;
  377. newWindow.document.body.appendChild(img);
  378. }
  379. };
  380. texture.render(true);
  381. texture.dispose();
  382. if (previousCamera) {
  383. scene.activeCamera = previousCamera;
  384. }
  385. };
  386. Object.defineProperty(Tools, "NoneLogLevel", {
  387. get: function () {
  388. return Tools._NoneLogLevel;
  389. },
  390. enumerable: true,
  391. configurable: true
  392. });
  393. Object.defineProperty(Tools, "MessageLogLevel", {
  394. get: function () {
  395. return Tools._MessageLogLevel;
  396. },
  397. enumerable: true,
  398. configurable: true
  399. });
  400. Object.defineProperty(Tools, "WarningLogLevel", {
  401. get: function () {
  402. return Tools._WarningLogLevel;
  403. },
  404. enumerable: true,
  405. configurable: true
  406. });
  407. Object.defineProperty(Tools, "ErrorLogLevel", {
  408. get: function () {
  409. return Tools._ErrorLogLevel;
  410. },
  411. enumerable: true,
  412. configurable: true
  413. });
  414. Object.defineProperty(Tools, "AllLogLevel", {
  415. get: function () {
  416. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  417. ;
  418. },
  419. enumerable: true,
  420. configurable: true
  421. });
  422. Tools._FormatMessage = function (message) {
  423. var padStr = function (i) {
  424. return (i < 10) ? "0" + i : "" + i;
  425. };
  426. var date = new Date();
  427. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  428. };
  429. Tools._LogDisabled = function (message) {
  430. // nothing to do
  431. };
  432. Tools._LogEnabled = function (message) {
  433. console.log(Tools._FormatMessage(message));
  434. };
  435. Tools._WarnDisabled = function (message) {
  436. // nothing to do
  437. };
  438. Tools._WarnEnabled = function (message) {
  439. console.warn(Tools._FormatMessage(message));
  440. };
  441. Tools._ErrorDisabled = function (message) {
  442. // nothing to do
  443. };
  444. Tools._ErrorEnabled = function (message) {
  445. console.error(Tools._FormatMessage(message));
  446. };
  447. Object.defineProperty(Tools, "LogLevels", {
  448. set: function (level) {
  449. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  450. Tools.Log = Tools._LogEnabled;
  451. } else {
  452. Tools.Log = Tools._LogDisabled;
  453. }
  454. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  455. Tools.Warn = Tools._WarnEnabled;
  456. } else {
  457. Tools.Warn = Tools._WarnDisabled;
  458. }
  459. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  460. Tools.Error = Tools._ErrorEnabled;
  461. } else {
  462. Tools.Error = Tools._ErrorDisabled;
  463. }
  464. },
  465. enumerable: true,
  466. configurable: true
  467. });
  468. Tools.BaseUrl = "";
  469. Tools._NoneLogLevel = 0;
  470. Tools._MessageLogLevel = 1;
  471. Tools._WarningLogLevel = 2;
  472. Tools._ErrorLogLevel = 4;
  473. Tools.Log = Tools._LogEnabled;
  474. Tools.Warn = Tools._WarnEnabled;
  475. Tools.Error = Tools._ErrorEnabled;
  476. return Tools;
  477. })();
  478. BABYLON.Tools = Tools;
  479. })(BABYLON || (BABYLON = {}));
  480. //# sourceMappingURL=babylon.tools.js.map