babylon.tools.js 24 KB

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