babylon.database.js 20 KB

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