babylon.database.js 19 KB

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