babylon.database.js 20 KB

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