babylon.tools.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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, onError) {
  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. if (onError) {
  188. onError();
  189. } else {
  190. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  191. }
  192. }
  193. }
  194. };
  195. request.send(null);
  196. };
  197. var loadFromIndexedDB = function () {
  198. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  199. };
  200. if (url.indexOf("file:") !== -1) {
  201. var fileName = url.substring(5);
  202. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  203. } else {
  204. // Caching all files
  205. if (database && database.enableSceneOffline) {
  206. database.openAsync(loadFromIndexedDB, noIndexedDB);
  207. } else {
  208. noIndexedDB();
  209. }
  210. }
  211. };
  212. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  213. var reader = new FileReader();
  214. reader.onload = function (e) {
  215. callback(e.target.result);
  216. };
  217. reader.onprogress = progressCallBack;
  218. if (!useArrayBuffer) {
  219. // Asynchronous read
  220. reader.readAsText(fileToLoad);
  221. } else {
  222. reader.readAsArrayBuffer(fileToLoad);
  223. }
  224. };
  225. // Misc.
  226. Tools.CheckExtends = function (v, min, max) {
  227. if (v.x < min.x)
  228. min.x = v.x;
  229. if (v.y < min.y)
  230. min.y = v.y;
  231. if (v.z < min.z)
  232. min.z = v.z;
  233. if (v.x > max.x)
  234. max.x = v.x;
  235. if (v.y > max.y)
  236. max.y = v.y;
  237. if (v.z > max.z)
  238. max.z = v.z;
  239. };
  240. Tools.WithinEpsilon = function (a, b) {
  241. var num = a - b;
  242. return -1.401298E-45 <= num && num <= 1.401298E-45;
  243. };
  244. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  245. for (var prop in source) {
  246. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  247. continue;
  248. }
  249. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  250. continue;
  251. }
  252. var sourceValue = source[prop];
  253. var typeOfSourceValue = typeof sourceValue;
  254. if (typeOfSourceValue == "function") {
  255. continue;
  256. }
  257. if (typeOfSourceValue == "object") {
  258. if (sourceValue instanceof Array) {
  259. destination[prop] = [];
  260. if (sourceValue.length > 0) {
  261. if (typeof sourceValue[0] == "object") {
  262. for (var index = 0; index < sourceValue.length; index++) {
  263. var clonedValue = cloneValue(sourceValue[index], destination);
  264. if (destination[prop].indexOf(clonedValue) === -1) {
  265. destination[prop].push(clonedValue);
  266. }
  267. }
  268. } else {
  269. destination[prop] = sourceValue.slice(0);
  270. }
  271. }
  272. } else {
  273. destination[prop] = cloneValue(sourceValue, destination);
  274. }
  275. } else {
  276. destination[prop] = sourceValue;
  277. }
  278. }
  279. };
  280. Tools.IsEmpty = function (obj) {
  281. for (var i in obj) {
  282. return false;
  283. }
  284. return true;
  285. };
  286. Tools.RegisterTopRootEvents = function (events) {
  287. for (var index = 0; index < events.length; index++) {
  288. var event = events[index];
  289. window.addEventListener(event.name, event.handler, false);
  290. try {
  291. if (window.parent) {
  292. window.parent.addEventListener(event.name, event.handler, false);
  293. }
  294. } catch (e) {
  295. // Silently fails...
  296. }
  297. }
  298. };
  299. Tools.UnregisterTopRootEvents = function (events) {
  300. for (var index = 0; index < events.length; index++) {
  301. var event = events[index];
  302. window.removeEventListener(event.name, event.handler);
  303. try {
  304. if (window.parent) {
  305. window.parent.removeEventListener(event.name, event.handler);
  306. }
  307. } catch (e) {
  308. // Silently fails...
  309. }
  310. }
  311. };
  312. Tools.GetFps = function () {
  313. return fps;
  314. };
  315. Tools.GetDeltaTime = function () {
  316. return deltaTime;
  317. };
  318. Tools._MeasureFps = function () {
  319. previousFramesDuration.push((new Date).getTime());
  320. var length = previousFramesDuration.length;
  321. if (length >= 2) {
  322. deltaTime = previousFramesDuration[length - 1] - previousFramesDuration[length - 2];
  323. }
  324. if (length >= fpsRange) {
  325. if (length > fpsRange) {
  326. previousFramesDuration.splice(0, 1);
  327. length = previousFramesDuration.length;
  328. }
  329. var sum = 0;
  330. for (var id = 0; id < length - 1; id++) {
  331. sum += previousFramesDuration[id + 1] - previousFramesDuration[id];
  332. }
  333. fps = 1000.0 / (sum / (length - 1));
  334. }
  335. };
  336. Tools.CreateScreenshot = function (engine, camera, size) {
  337. var width;
  338. var height;
  339. var scene = camera.getScene();
  340. var previousCamera = null;
  341. if (scene.activeCamera !== camera) {
  342. previousCamera = scene.activeCamera;
  343. scene.activeCamera = camera;
  344. }
  345. //If a precision value is specified
  346. if (size.precision) {
  347. width = Math.round(engine.getRenderWidth() * size.precision);
  348. height = Math.round(width / engine.getAspectRatio(camera));
  349. size = { width: width, height: height };
  350. } else if (size.width && size.height) {
  351. width = size.width;
  352. height = size.height;
  353. } else if (size.width && !size.height) {
  354. width = size.width;
  355. height = Math.round(width / engine.getAspectRatio(camera));
  356. size = { width: width, height: height };
  357. } else if (size.height && !size.width) {
  358. height = size.height;
  359. width = Math.round(height * engine.getAspectRatio(camera));
  360. size = { width: width, height: height };
  361. } else if (!isNaN(size)) {
  362. height = size;
  363. width = size;
  364. } else {
  365. Tools.Error("Invalid 'size' parameter !");
  366. return;
  367. }
  368. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  369. var texture = new BABYLON.RenderTargetTexture("screenShot", size, engine.scenes[0], false, false);
  370. texture.renderList = engine.scenes[0].meshes;
  371. texture.onAfterRender = function () {
  372. // Read the contents of the framebuffer
  373. var numberOfChannelsByLine = width * 4;
  374. var halfHeight = height / 2;
  375. //Reading datas from WebGL
  376. var data = engine.readPixels(0, 0, width, height);
  377. for (var i = 0; i < halfHeight; i++) {
  378. for (var j = 0; j < numberOfChannelsByLine; j++) {
  379. var currentCell = j + i * numberOfChannelsByLine;
  380. var targetLine = height - i - 1;
  381. var targetCell = j + targetLine * numberOfChannelsByLine;
  382. var temp = data[currentCell];
  383. data[currentCell] = data[targetCell];
  384. data[targetCell] = temp;
  385. }
  386. }
  387. // Create a 2D canvas to store the result
  388. if (!screenshotCanvas) {
  389. screenshotCanvas = document.createElement('canvas');
  390. }
  391. screenshotCanvas.width = width;
  392. screenshotCanvas.height = height;
  393. var context = screenshotCanvas.getContext('2d');
  394. // Copy the pixels to a 2D canvas
  395. var imageData = context.createImageData(width, height);
  396. imageData.data.set(data);
  397. context.putImageData(imageData, 0, 0);
  398. var base64Image = screenshotCanvas.toDataURL();
  399. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  400. if (("download" in document.createElement("a"))) {
  401. var a = window.document.createElement("a");
  402. a.href = base64Image;
  403. var date = new Date();
  404. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  405. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  406. window.document.body.appendChild(a);
  407. a.addEventListener("click", function () {
  408. a.parentElement.removeChild(a);
  409. });
  410. a.click();
  411. //Or opening a new tab with the image if it is not possible to automatically start download.
  412. } else {
  413. var newWindow = window.open("");
  414. var img = newWindow.document.createElement("img");
  415. img.src = base64Image;
  416. newWindow.document.body.appendChild(img);
  417. }
  418. };
  419. texture.render(true);
  420. texture.dispose();
  421. if (previousCamera) {
  422. scene.activeCamera = previousCamera;
  423. }
  424. };
  425. // XHR response validator for local file scenario
  426. Tools.ValidateXHRData = function (xhr, dataType) {
  427. if (typeof dataType === "undefined") { dataType = 7; }
  428. try {
  429. if (dataType & 1) {
  430. if (xhr.responseText && xhr.responseText.length > 0) {
  431. return true;
  432. } else if (dataType === 1) {
  433. return false;
  434. }
  435. }
  436. if (dataType & 2) {
  437. // Check header width and height since there is no "TGA" magic number
  438. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  439. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  440. return true;
  441. } else if (dataType === 2) {
  442. return false;
  443. }
  444. }
  445. if (dataType & 4) {
  446. // Check for the "DDS" magic number
  447. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  448. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  449. return true;
  450. } else {
  451. return false;
  452. }
  453. }
  454. } catch (e) {
  455. // Global protection
  456. }
  457. return false;
  458. };
  459. Object.defineProperty(Tools, "NoneLogLevel", {
  460. get: function () {
  461. return Tools._NoneLogLevel;
  462. },
  463. enumerable: true,
  464. configurable: true
  465. });
  466. Object.defineProperty(Tools, "MessageLogLevel", {
  467. get: function () {
  468. return Tools._MessageLogLevel;
  469. },
  470. enumerable: true,
  471. configurable: true
  472. });
  473. Object.defineProperty(Tools, "WarningLogLevel", {
  474. get: function () {
  475. return Tools._WarningLogLevel;
  476. },
  477. enumerable: true,
  478. configurable: true
  479. });
  480. Object.defineProperty(Tools, "ErrorLogLevel", {
  481. get: function () {
  482. return Tools._ErrorLogLevel;
  483. },
  484. enumerable: true,
  485. configurable: true
  486. });
  487. Object.defineProperty(Tools, "AllLogLevel", {
  488. get: function () {
  489. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  490. },
  491. enumerable: true,
  492. configurable: true
  493. });
  494. Tools._FormatMessage = function (message) {
  495. var padStr = function (i) {
  496. return (i < 10) ? "0" + i : "" + i;
  497. };
  498. var date = new Date();
  499. return "BJS - [" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  500. };
  501. Tools._LogDisabled = function (message) {
  502. // nothing to do
  503. };
  504. Tools._LogEnabled = function (message) {
  505. console.log(Tools._FormatMessage(message));
  506. };
  507. Tools._WarnDisabled = function (message) {
  508. // nothing to do
  509. };
  510. Tools._WarnEnabled = function (message) {
  511. console.warn(Tools._FormatMessage(message));
  512. };
  513. Tools._ErrorDisabled = function (message) {
  514. // nothing to do
  515. };
  516. Tools._ErrorEnabled = function (message) {
  517. console.error(Tools._FormatMessage(message));
  518. };
  519. Object.defineProperty(Tools, "LogLevels", {
  520. set: function (level) {
  521. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  522. Tools.Log = Tools._LogEnabled;
  523. } else {
  524. Tools.Log = Tools._LogDisabled;
  525. }
  526. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  527. Tools.Warn = Tools._WarnEnabled;
  528. } else {
  529. Tools.Warn = Tools._WarnDisabled;
  530. }
  531. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  532. Tools.Error = Tools._ErrorEnabled;
  533. } else {
  534. Tools.Error = Tools._ErrorDisabled;
  535. }
  536. },
  537. enumerable: true,
  538. configurable: true
  539. });
  540. Tools.BaseUrl = "";
  541. Tools.GetExponantOfTwo = function (value, max) {
  542. var count = 1;
  543. do {
  544. count *= 2;
  545. } while(count < value);
  546. if (count > max)
  547. count = max;
  548. return count;
  549. };
  550. Tools._NoneLogLevel = 0;
  551. Tools._MessageLogLevel = 1;
  552. Tools._WarningLogLevel = 2;
  553. Tools._ErrorLogLevel = 4;
  554. Tools.Log = Tools._LogEnabled;
  555. Tools.Warn = Tools._WarnEnabled;
  556. Tools.Error = Tools._ErrorEnabled;
  557. return Tools;
  558. })();
  559. BABYLON.Tools = Tools;
  560. })(BABYLON || (BABYLON = {}));
  561. //# sourceMappingURL=babylon.tools.js.map