babylon.database.js 20 KB

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