babylon.database.js 23 KB

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