babylon.database.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. var BABYLON;
  2. (function (BABYLON) {
  3. var Database = (function () {
  4. function Database(urlToScene, callbackManifestChecked) {
  5. // Handling various flavors of prefixed version of IndexedDB
  6. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  7. this.callbackManifestChecked = callbackManifestChecked;
  8. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  9. this.db = null;
  10. this.enableSceneOffline = false;
  11. this.enableTexturesOffline = false;
  12. this.manifestVersionFound = 0;
  13. this.mustUpdateRessources = false;
  14. this.hasReachedQuota = false;
  15. this.checkManifestFile();
  16. }
  17. Database.prototype.checkManifestFile = function () {
  18. var _this = this;
  19. function noManifestFile() {
  20. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  21. that.enableSceneOffline = false;
  22. that.enableTexturesOffline = false;
  23. that.callbackManifestChecked(false);
  24. }
  25. var that = this;
  26. var manifestURL = this.currentSceneUrl + ".manifest";
  27. var xhr = new XMLHttpRequest();
  28. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  29. xhr.open("GET", manifestURLTimeStamped, true);
  30. xhr.addEventListener("load", function () {
  31. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  32. try {
  33. var manifestFile = JSON.parse(xhr.response);
  34. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  35. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  36. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  37. _this.manifestVersionFound = manifestFile.version;
  38. }
  39. if (_this.callbackManifestChecked) {
  40. _this.callbackManifestChecked(true);
  41. }
  42. }
  43. catch (ex) {
  44. noManifestFile();
  45. }
  46. }
  47. else {
  48. noManifestFile();
  49. }
  50. }, false);
  51. xhr.addEventListener("error", function (event) {
  52. noManifestFile();
  53. }, false);
  54. try {
  55. xhr.send();
  56. }
  57. catch (ex) {
  58. BABYLON.Tools.Error("Error on XHR send request.");
  59. that.callbackManifestChecked(false);
  60. }
  61. };
  62. Database.prototype.openAsync = function (successCallback, errorCallback) {
  63. var _this = this;
  64. function handleError() {
  65. that.isSupported = false;
  66. if (errorCallback)
  67. errorCallback();
  68. }
  69. var that = this;
  70. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  71. // Your browser doesn't support IndexedDB
  72. this.isSupported = false;
  73. if (errorCallback)
  74. errorCallback();
  75. }
  76. else {
  77. // If the DB hasn't been opened or created yet
  78. if (!this.db) {
  79. this.hasReachedQuota = false;
  80. this.isSupported = true;
  81. var request = this.idbFactory.open("babylonjs", 1);
  82. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  83. request.onerror = function (event) {
  84. handleError();
  85. };
  86. // executes when a version change transaction cannot complete due to other active transactions
  87. request.onblocked = function (event) {
  88. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  89. handleError();
  90. };
  91. // DB has been opened successfully
  92. request.onsuccess = function (event) {
  93. _this.db = request.result;
  94. successCallback();
  95. };
  96. // Initialization of the DB. Creating Scenes & Textures stores
  97. request.onupgradeneeded = function (event) {
  98. _this.db = (event.target).result;
  99. try {
  100. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  101. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  102. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  103. }
  104. catch (ex) {
  105. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  106. handleError();
  107. }
  108. };
  109. }
  110. else {
  111. if (successCallback)
  112. successCallback();
  113. }
  114. }
  115. };
  116. Database.prototype.loadImageFromDB = function (url, image) {
  117. var _this = this;
  118. var completeURL = Database.ReturnFullUrlLocation(url);
  119. var saveAndLoadImage = function () {
  120. if (!_this.hasReachedQuota && _this.db !== null) {
  121. // the texture is not yet in the DB, let's try to save it
  122. _this._saveImageIntoDBAsync(completeURL, image);
  123. }
  124. else {
  125. image.src = url;
  126. }
  127. };
  128. if (!this.mustUpdateRessources) {
  129. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  130. }
  131. else {
  132. saveAndLoadImage();
  133. }
  134. };
  135. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  136. if (this.isSupported && this.db !== null) {
  137. var texture;
  138. var transaction = this.db.transaction(["textures"]);
  139. transaction.onabort = function (event) {
  140. image.src = url;
  141. };
  142. transaction.oncomplete = function (event) {
  143. var blobTextureURL;
  144. if (texture) {
  145. var URL = window.URL || window.webkitURL;
  146. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  147. image.onerror = function () {
  148. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  149. image.src = url;
  150. };
  151. image.src = blobTextureURL;
  152. }
  153. else {
  154. notInDBCallback();
  155. }
  156. };
  157. var getRequest = transaction.objectStore("textures").get(url);
  158. getRequest.onsuccess = function (event) {
  159. texture = (event.target).result;
  160. };
  161. getRequest.onerror = function (event) {
  162. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  163. image.src = url;
  164. };
  165. }
  166. else {
  167. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  168. image.src = url;
  169. }
  170. };
  171. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  172. var _this = this;
  173. if (this.isSupported) {
  174. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  175. var generateBlobUrl = function () {
  176. var blobTextureURL;
  177. if (blob) {
  178. var URL = window.URL || window.webkitURL;
  179. try {
  180. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  181. }
  182. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  183. catch (ex) {
  184. blobTextureURL = URL.createObjectURL(blob);
  185. }
  186. }
  187. image.src = blobTextureURL;
  188. };
  189. if (Database.isUASupportingBlobStorage) {
  190. var xhr = new XMLHttpRequest(), blob;
  191. xhr.open("GET", url, true);
  192. xhr.responseType = "blob";
  193. xhr.addEventListener("load", function () {
  194. if (xhr.status === 200) {
  195. // Blob as response (XHR2)
  196. blob = xhr.response;
  197. var transaction = _this.db.transaction(["textures"], "readwrite");
  198. // the transaction could abort because of a QuotaExceededError error
  199. transaction.onabort = function (event) {
  200. try {
  201. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  202. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  203. this.hasReachedQuota = true;
  204. }
  205. }
  206. catch (ex) { }
  207. generateBlobUrl();
  208. };
  209. transaction.oncomplete = function (event) {
  210. generateBlobUrl();
  211. };
  212. var newTexture = { textureUrl: url, data: blob };
  213. try {
  214. // Put the blob into the dabase
  215. var addRequest = transaction.objectStore("textures").put(newTexture);
  216. addRequest.onsuccess = function (event) {
  217. };
  218. addRequest.onerror = function (event) {
  219. generateBlobUrl();
  220. };
  221. }
  222. catch (ex) {
  223. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  224. if (ex.code === 25) {
  225. Database.isUASupportingBlobStorage = false;
  226. }
  227. image.src = url;
  228. }
  229. }
  230. else {
  231. image.src = url;
  232. }
  233. }, false);
  234. xhr.addEventListener("error", function (event) {
  235. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  236. image.src = url;
  237. }, false);
  238. xhr.send();
  239. }
  240. else {
  241. image.src = url;
  242. }
  243. }
  244. else {
  245. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  246. image.src = url;
  247. }
  248. };
  249. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  250. var _this = this;
  251. var updateVersion = function (event) {
  252. // the version is not yet in the DB or we need to update it
  253. _this._saveVersionIntoDBAsync(url, versionLoaded);
  254. };
  255. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  256. };
  257. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  258. var _this = this;
  259. if (this.isSupported) {
  260. var version;
  261. try {
  262. var transaction = this.db.transaction(["versions"]);
  263. transaction.oncomplete = function (event) {
  264. if (version) {
  265. // If the version in the JSON file is > than the version in DB
  266. if (_this.manifestVersionFound > version.data) {
  267. _this.mustUpdateRessources = true;
  268. updateInDBCallback();
  269. }
  270. else {
  271. callback(version.data);
  272. }
  273. }
  274. else {
  275. _this.mustUpdateRessources = true;
  276. updateInDBCallback();
  277. }
  278. };
  279. transaction.onabort = function (event) {
  280. callback(-1);
  281. };
  282. var getRequest = transaction.objectStore("versions").get(url);
  283. getRequest.onsuccess = function (event) {
  284. version = (event.target).result;
  285. };
  286. getRequest.onerror = function (event) {
  287. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  288. callback(-1);
  289. };
  290. }
  291. catch (ex) {
  292. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  293. callback(-1);
  294. }
  295. }
  296. else {
  297. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  298. callback(-1);
  299. }
  300. };
  301. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  302. var _this = this;
  303. if (this.isSupported && !this.hasReachedQuota) {
  304. try {
  305. // Open a transaction to the database
  306. var transaction = this.db.transaction(["versions"], "readwrite");
  307. // the transaction could abort because of a QuotaExceededError error
  308. transaction.onabort = function (event) {
  309. try {
  310. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  311. _this.hasReachedQuota = true;
  312. }
  313. }
  314. catch (ex) { }
  315. callback(-1);
  316. };
  317. transaction.oncomplete = function (event) {
  318. callback(_this.manifestVersionFound);
  319. };
  320. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  321. // Put the scene into the database
  322. var addRequest = transaction.objectStore("versions").put(newVersion);
  323. addRequest.onsuccess = function (event) {
  324. };
  325. addRequest.onerror = function (event) {
  326. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  327. };
  328. }
  329. catch (ex) {
  330. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  331. callback(-1);
  332. }
  333. }
  334. else {
  335. callback(-1);
  336. }
  337. };
  338. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  339. var _this = this;
  340. var completeUrl = Database.ReturnFullUrlLocation(url);
  341. var saveAndLoadFile = function (event) {
  342. // the scene is not yet in the DB, let's try to save it
  343. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  344. };
  345. this._checkVersionFromDB(completeUrl, function (version) {
  346. if (version !== -1) {
  347. if (!_this.mustUpdateRessources) {
  348. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  349. }
  350. else {
  351. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  352. }
  353. }
  354. else {
  355. errorCallback();
  356. }
  357. });
  358. };
  359. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  360. if (this.isSupported) {
  361. var targetStore;
  362. if (url.indexOf(".babylon") !== -1) {
  363. targetStore = "scenes";
  364. }
  365. else {
  366. targetStore = "textures";
  367. }
  368. var file;
  369. var transaction = this.db.transaction([targetStore]);
  370. transaction.oncomplete = function (event) {
  371. if (file) {
  372. callback(file.data);
  373. }
  374. else {
  375. notInDBCallback();
  376. }
  377. };
  378. transaction.onabort = function (event) {
  379. notInDBCallback();
  380. };
  381. var getRequest = transaction.objectStore(targetStore).get(url);
  382. getRequest.onsuccess = function (event) {
  383. file = (event.target).result;
  384. };
  385. getRequest.onerror = function (event) {
  386. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  387. notInDBCallback();
  388. };
  389. }
  390. else {
  391. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  392. callback();
  393. }
  394. };
  395. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  396. var _this = this;
  397. if (this.isSupported) {
  398. var targetStore;
  399. if (url.indexOf(".babylon") !== -1) {
  400. targetStore = "scenes";
  401. }
  402. else {
  403. targetStore = "textures";
  404. }
  405. // Create XHR
  406. var xhr = new XMLHttpRequest(), fileData;
  407. xhr.open("GET", url, true);
  408. if (useArrayBuffer) {
  409. xhr.responseType = "arraybuffer";
  410. }
  411. xhr.onprogress = progressCallback;
  412. xhr.addEventListener("load", function () {
  413. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  414. // Blob as response (XHR2)
  415. //fileData = xhr.responseText;
  416. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  417. if (!_this.hasReachedQuota) {
  418. // Open a transaction to the database
  419. var transaction = _this.db.transaction([targetStore], "readwrite");
  420. // the transaction could abort because of a QuotaExceededError error
  421. transaction.onabort = function (event) {
  422. try {
  423. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  424. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  425. this.hasReachedQuota = true;
  426. }
  427. }
  428. catch (ex) { }
  429. callback(fileData);
  430. };
  431. transaction.oncomplete = function (event) {
  432. callback(fileData);
  433. };
  434. var newFile;
  435. if (targetStore === "scenes") {
  436. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  437. }
  438. else {
  439. newFile = { textureUrl: url, data: fileData };
  440. }
  441. try {
  442. // Put the scene into the database
  443. var addRequest = transaction.objectStore(targetStore).put(newFile);
  444. addRequest.onsuccess = function (event) {
  445. };
  446. addRequest.onerror = function (event) {
  447. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  448. };
  449. }
  450. catch (ex) {
  451. callback(fileData);
  452. }
  453. }
  454. else {
  455. callback(fileData);
  456. }
  457. }
  458. else {
  459. callback();
  460. }
  461. }, false);
  462. xhr.addEventListener("error", function (event) {
  463. BABYLON.Tools.Error("error on XHR request.");
  464. callback();
  465. }, false);
  466. xhr.send();
  467. }
  468. else {
  469. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  470. callback();
  471. }
  472. };
  473. Database.isUASupportingBlobStorage = true;
  474. Database.parseURL = function (url) {
  475. var a = document.createElement('a');
  476. a.href = url;
  477. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  478. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  479. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  480. return absLocation;
  481. };
  482. Database.ReturnFullUrlLocation = function (url) {
  483. if (url.indexOf("http:/") === -1) {
  484. return (BABYLON.Database.parseURL(window.location.href) + url);
  485. }
  486. else {
  487. return url;
  488. }
  489. };
  490. return Database;
  491. })();
  492. BABYLON.Database = Database;
  493. })(BABYLON || (BABYLON = {}));
  494. //# sourceMappingURL=babylon.database.js.map