babylon.database.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 = (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 = (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. var scenesStore = this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  122. var versionsStore = this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  123. var texturesStore = this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  124. }
  125. catch (ex) {
  126. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  127. handleError();
  128. }
  129. };
  130. }
  131. // DB has already been created and opened
  132. else {
  133. if (successCallback) successCallback();
  134. }
  135. }
  136. }
  137. public loadImageFromDB(url: string, image: HTMLImageElement) {
  138. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  139. var saveAndLoadImage = () => {
  140. if (!this.hasReachedQuota && this.db !== null) {
  141. // the texture is not yet in the DB, let's try to save it
  142. this._saveImageIntoDBAsync(completeURL, image);
  143. }
  144. // If the texture is not in the DB and we've reached the DB quota limit
  145. // let's load it directly from the web
  146. else {
  147. image.src = url;
  148. }
  149. };
  150. if (!this.mustUpdateRessources) {
  151. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  152. }
  153. // First time we're download the images or update requested in the manifest file by a version change
  154. else {
  155. saveAndLoadImage();
  156. }
  157. }
  158. private _loadImageFromDBAsync(url: string, image: HTMLImageElement, notInDBCallback: () => any) {
  159. if (this.isSupported && this.db !== null) {
  160. var texture;
  161. var transaction: IDBTransaction = this.db.transaction(["textures"]);
  162. transaction.onabort = event => {
  163. image.src = url;
  164. };
  165. transaction.oncomplete = event => {
  166. var blobTextureURL;
  167. if (texture) {
  168. var URL = window.URL || window.webkitURL;
  169. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  170. image.onerror = () => {
  171. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  172. image.src = url;
  173. };
  174. image.src = blobTextureURL;
  175. }
  176. else {
  177. notInDBCallback();
  178. }
  179. };
  180. var getRequest: IDBRequest = transaction.objectStore("textures").get(url);
  181. getRequest.onsuccess = event => {
  182. texture = (<any>(event.target)).result;
  183. };
  184. getRequest.onerror = event => {
  185. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  186. image.src = url;
  187. };
  188. }
  189. else {
  190. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  191. image.src = url;
  192. }
  193. }
  194. private _saveImageIntoDBAsync(url: string, image: HTMLImageElement) {
  195. if (this.isSupported) {
  196. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  197. var generateBlobUrl = () => {
  198. var blobTextureURL;
  199. if (blob) {
  200. var URL = window.URL || window.webkitURL;
  201. try {
  202. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  203. }
  204. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  205. catch (ex) {
  206. blobTextureURL = URL.createObjectURL(blob);
  207. }
  208. }
  209. image.src = blobTextureURL;
  210. };
  211. if (BABYLON.Database.isUASupportingBlobStorage) { // Create XHR
  212. var xhr = new XMLHttpRequest(),
  213. blob: Blob;
  214. xhr.open("GET", url, true);
  215. xhr.responseType = "blob";
  216. xhr.addEventListener("load", () => {
  217. if (xhr.status === 200) {
  218. // Blob as response (XHR2)
  219. blob = xhr.response;
  220. var transaction = this.db.transaction(["textures"], "readwrite");
  221. // the transaction could abort because of a QuotaExceededError error
  222. transaction.onabort = function (event) {
  223. try {
  224. if (event.srcElement.error.name === "QuotaExceededError") {
  225. this.hasReachedQuota = true;
  226. }
  227. }
  228. catch (ex) { }
  229. generateBlobUrl();
  230. };
  231. transaction.oncomplete = event => {
  232. generateBlobUrl();
  233. };
  234. var newTexture = { textureUrl: url, data: blob };
  235. try {
  236. // Put the blob into the dabase
  237. var addRequest = transaction.objectStore("textures").put(newTexture);
  238. addRequest.onsuccess = event => {
  239. };
  240. addRequest.onerror = event => {
  241. generateBlobUrl();
  242. };
  243. }
  244. catch (ex) {
  245. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  246. if (ex.code === 25) {
  247. BABYLON.Database.isUASupportingBlobStorage = false;
  248. }
  249. image.src = url;
  250. }
  251. }
  252. else {
  253. image.src = url;
  254. }
  255. }, false);
  256. xhr.addEventListener("error", event => {
  257. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  258. image.src = url;
  259. }, false);
  260. xhr.send();
  261. }
  262. else {
  263. image.src = url;
  264. }
  265. }
  266. else {
  267. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  268. image.src = url;
  269. }
  270. }
  271. private _checkVersionFromDB(url: string, versionLoaded) {
  272. var updateVersion = event => {
  273. // the version is not yet in the DB or we need to update it
  274. this._saveVersionIntoDBAsync(url, versionLoaded);
  275. };
  276. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  277. }
  278. private _loadVersionFromDBAsync(url: string, callback, updateInDBCallback) {
  279. if (this.isSupported) {
  280. var version;
  281. try {
  282. var transaction = this.db.transaction(["versions"]);
  283. transaction.oncomplete = event => {
  284. if (version) {
  285. // If the version in the JSON file is > than the version in DB
  286. if (this.manifestVersionFound > version.data) {
  287. this.mustUpdateRessources = true;
  288. updateInDBCallback();
  289. }
  290. else {
  291. callback(version.data);
  292. }
  293. }
  294. // version was not found in DB
  295. else {
  296. this.mustUpdateRessources = true;
  297. updateInDBCallback();
  298. }
  299. };
  300. transaction.onabort = event => {
  301. callback(-1);
  302. };
  303. var getRequest = transaction.objectStore("versions").get(url);
  304. getRequest.onsuccess = event => {
  305. version = (<any>(event.target)).result;
  306. };
  307. getRequest.onerror = event => {
  308. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  309. callback(-1);
  310. };
  311. }
  312. catch (ex) {
  313. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  314. callback(-1);
  315. }
  316. }
  317. else {
  318. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  319. callback(-1);
  320. }
  321. }
  322. private _saveVersionIntoDBAsync(url: string, callback) {
  323. if (this.isSupported && !this.hasReachedQuota) {
  324. try {
  325. // Open a transaction to the database
  326. var transaction = this.db.transaction(["versions"], "readwrite");
  327. // the transaction could abort because of a QuotaExceededError error
  328. transaction.onabort = event => {
  329. try {
  330. if (event.srcElement.error.name === "QuotaExceededError") {
  331. this.hasReachedQuota = true;
  332. }
  333. }
  334. catch (ex) { }
  335. callback(-1);
  336. };
  337. transaction.oncomplete = event => {
  338. callback(this.manifestVersionFound);
  339. };
  340. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  341. // Put the scene into the database
  342. var addRequest = transaction.objectStore("versions").put(newVersion);
  343. addRequest.onsuccess = event => {
  344. };
  345. addRequest.onerror = event => {
  346. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  347. };
  348. }
  349. catch (ex) {
  350. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  351. callback(-1);
  352. }
  353. }
  354. else {
  355. callback(-1);
  356. }
  357. }
  358. private loadFileFromDB(url: string, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer?: boolean) {
  359. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  360. var saveAndLoadFile = event => {
  361. // the scene is not yet in the DB, let's try to save it
  362. this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  363. };
  364. this._checkVersionFromDB(completeUrl, version => {
  365. if (version !== -1) {
  366. if (!this.mustUpdateRessources) {
  367. this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  368. }
  369. else {
  370. this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  371. }
  372. }
  373. else {
  374. errorCallback();
  375. }
  376. });
  377. }
  378. private _loadFileFromDBAsync(url, callback, notInDBCallback, useArrayBuffer?: boolean) {
  379. if (this.isSupported) {
  380. var targetStore: string;
  381. if (url.indexOf(".babylon") !== -1) {
  382. targetStore = "scenes";
  383. }
  384. else {
  385. targetStore = "textures";
  386. }
  387. var file;
  388. var transaction = this.db.transaction([targetStore]);
  389. transaction.oncomplete = event => {
  390. if (file) {
  391. callback(file.data);
  392. }
  393. // file was not found in DB
  394. else {
  395. notInDBCallback();
  396. }
  397. };
  398. transaction.onabort = event => {
  399. notInDBCallback();
  400. };
  401. var getRequest = transaction.objectStore(targetStore).get(url);
  402. getRequest.onsuccess = event => {
  403. file = (<any>(event.target)).result;
  404. };
  405. getRequest.onerror = event => {
  406. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  407. notInDBCallback();
  408. };
  409. }
  410. else {
  411. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  412. callback();
  413. }
  414. }
  415. private _saveFileIntoDBAsync(url: string, callback, progressCallback, useArrayBuffer?: boolean) {
  416. if (this.isSupported) {
  417. var targetStore: string;
  418. if (url.indexOf(".babylon") !== -1) {
  419. targetStore = "scenes";
  420. }
  421. else {
  422. targetStore = "textures";
  423. }
  424. // Create XHR
  425. var xhr = new XMLHttpRequest(), fileData;
  426. xhr.open("GET", url, true);
  427. if (useArrayBuffer) {
  428. xhr.responseType = "arraybuffer";
  429. }
  430. xhr.onprogress = progressCallback;
  431. xhr.addEventListener("load", () => {
  432. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  433. // Blob as response (XHR2)
  434. //fileData = xhr.responseText;
  435. fileData = !useArrayBuffer ? xhr.responseText : xhr.response
  436. if (!this.hasReachedQuota) {
  437. // Open a transaction to the database
  438. var transaction = this.db.transaction([targetStore], "readwrite");
  439. // the transaction could abort because of a QuotaExceededError error
  440. transaction.onabort = function (event) {
  441. try {
  442. if (event.srcElement.error.name === "QuotaExceededError") {
  443. this.hasReachedQuota = true;
  444. }
  445. }
  446. catch (ex) { }
  447. callback(fileData);
  448. };
  449. transaction.oncomplete = event => {
  450. callback(fileData);
  451. };
  452. var newFile;
  453. if (targetStore === "scenes") {
  454. newFile = { sceneUrl: url, data: fileData, version: this.manifestVersionFound };
  455. }
  456. else {
  457. newFile = { textureUrl: url, data: fileData };
  458. }
  459. try {
  460. // Put the scene into the database
  461. var addRequest = transaction.objectStore(targetStore).put(newFile);
  462. addRequest.onsuccess = event => {
  463. };
  464. addRequest.onerror = event => {
  465. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  466. };
  467. }
  468. catch (ex) {
  469. callback(fileData);
  470. }
  471. }
  472. else {
  473. callback(fileData);
  474. }
  475. }
  476. else {
  477. callback();
  478. }
  479. }, false);
  480. xhr.addEventListener("error", event => {
  481. BABYLON.Tools.Error("error on XHR request.");
  482. callback();
  483. }, false);
  484. xhr.send();
  485. }
  486. else {
  487. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  488. callback();
  489. }
  490. }
  491. }
  492. }