babylon.database.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. BABYLON.Tools.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 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  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. BABYLON.Tools.Error("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. BABYLON.Tools.Error("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. BABYLON.Tools.Error("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. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  171. image.src = url;
  172. };
  173. }
  174. else {
  175. BABYLON.Tools.Error("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. };
  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. BABYLON.Tools.Error("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. BABYLON.Tools.Error("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. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  300. callback(-1);
  301. };
  302. }
  303. catch (ex) {
  304. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  305. callback(-1);
  306. }
  307. }
  308. else {
  309. BABYLON.Tools.Error("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. };
  339. addRequest.onerror = function (event) {
  340. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  341. };
  342. }
  343. catch (ex) {
  344. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  345. callback(-1);
  346. }
  347. }
  348. else {
  349. callback(-1);
  350. }
  351. };
  352. BABYLON.Database.prototype.loadSceneFromDB = function (url, sceneLoaded, progressCallBack, errorCallback) {
  353. var that = this;
  354. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  355. var saveAndLoadScene = function (event) {
  356. // the scene is not yet in the DB, let's try to save it
  357. that._saveSceneIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  358. };
  359. this._checkVersionFromDB(completeUrl, function (version) {
  360. if (version !== -1) {
  361. if (!that.mustUpdateRessources) {
  362. that._loadSceneFromDBAsync(completeUrl, sceneLoaded, saveAndLoadScene);
  363. }
  364. else {
  365. that._saveSceneIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  366. }
  367. }
  368. else {
  369. errorCallback();
  370. }
  371. });
  372. };
  373. BABYLON.Database.prototype._loadSceneFromDBAsync = function (url, callback, notInDBCallback) {
  374. if (this.isSupported) {
  375. var scene;
  376. var transaction = this.db.transaction(["scenes"]);
  377. transaction.oncomplete = function (event) {
  378. if (scene) {
  379. callback(scene.data);
  380. }
  381. // scene was not found in DB
  382. else {
  383. notInDBCallback();
  384. }
  385. };
  386. transaction.onabort = function (event) {
  387. notInDBCallback();
  388. };
  389. var getRequest = transaction.objectStore("scenes").get(url);
  390. getRequest.onsuccess = function (event) {
  391. scene = event.target.result;
  392. };
  393. getRequest.onerror = function (event) {
  394. BABYLON.Tools.Error("Error loading scene " + url + " from DB.");
  395. notInDBCallback();
  396. };
  397. }
  398. else {
  399. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  400. callback();
  401. }
  402. };
  403. BABYLON.Database.prototype._saveSceneIntoDBAsync = function (url, callback, progressCallback) {
  404. if (this.isSupported) {
  405. // Create XHR
  406. var xhr = new XMLHttpRequest(), sceneText;
  407. var that = this;
  408. var urlTimeStamped = url + (url.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  409. xhr.open("GET", urlTimeStamped, true);
  410. xhr.onprogress = progressCallback;
  411. xhr.addEventListener("load", function () {
  412. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  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. };
  440. addRequest.onerror = function (event) {
  441. BABYLON.Tools.Error("Error in DB add scene request in BABYLON.Database.");
  442. };
  443. }
  444. catch (ex) {
  445. callback(sceneText);
  446. }
  447. }
  448. else {
  449. callback(sceneText);
  450. }
  451. }
  452. else {
  453. callback();
  454. }
  455. }, false);
  456. xhr.addEventListener("error", function (event) {
  457. BABYLON.Tools.Error("error on XHR request.");
  458. callback();
  459. }, false);
  460. xhr.send();
  461. }
  462. else {
  463. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  464. callback();
  465. }
  466. };
  467. })();