babylon.database.ts 23 KB

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