TilesRendererBase.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. import { getUrlExtension } from '../utilities/urlExtension.js';
  2. import { LRUCache } from '../utilities/LRUCache.js';
  3. import { PriorityQueue } from '../utilities/PriorityQueue.js';
  4. import { determineFrustumSet, toggleTiles, skipTraversal, markUsedSetLeaves, traverseSet } from './traverseFunctions.js';
  5. import { UNLOADED, LOADING, PARSING, LOADED, FAILED } from './constants.js';
  6. /**
  7. * Function for provided to sort all tiles for prioritizing loading/unloading.
  8. *
  9. * @param {Tile} a
  10. * @param {Tile} b
  11. * @returns number
  12. */
  13. const priorityCallback = ( a, b ) => {
  14. if ( a.__depth !== b.__depth ) {
  15. // load shallower tiles first
  16. return a.__depth > b.__depth ? - 1 : 1;
  17. } else if ( a.__inFrustum !== b.__inFrustum ) {
  18. // load tiles that are in the frustum at the current depth
  19. return a.__inFrustum ? 1 : - 1;
  20. } else if ( a.__used !== b.__used ) {
  21. // load tiles that have been used
  22. return a.__used ? 1 : - 1;
  23. } else if ( a.__error !== b.__error ) {
  24. // load the tile with the higher error
  25. return a.__error > b.__error ? 1 : - 1;
  26. } else if ( a.__distanceFromCamera !== b.__distanceFromCamera ) {
  27. // and finally visible tiles which have equal error (ex: if geometricError === 0)
  28. // should prioritize based on distance.
  29. return a.__distanceFromCamera > b.__distanceFromCamera ? - 1 : 1;
  30. }
  31. return 0;
  32. };
  33. /**
  34. * Function for sorting the evicted LRU items. We should evict the shallowest depth first.
  35. * @param {Tile} tile
  36. * @returns number
  37. */
  38. const lruPriorityCallback = ( tile ) => 1 / ( tile.__depthFromRenderedParent + 1 );
  39. export class TilesRendererBase {
  40. get rootTileSet() {
  41. const tileSet = this.tileSets[ this.rootURL ];
  42. if ( ! tileSet || tileSet instanceof Promise ) {
  43. return null;
  44. } else {
  45. return tileSet;
  46. }
  47. }
  48. get root() {
  49. const tileSet = this.rootTileSet;
  50. return tileSet ? tileSet.root : null;
  51. }
  52. constructor( url ) {
  53. // state
  54. this.tileSets = {};
  55. this.rootURL = url;
  56. this.fetchOptions = {};
  57. this.preprocessURL = null;
  58. const lruCache = new LRUCache();
  59. lruCache.unloadPriorityCallback = lruPriorityCallback;
  60. const downloadQueue = new PriorityQueue();
  61. downloadQueue.maxJobs = 4;
  62. downloadQueue.priorityCallback = priorityCallback;
  63. const parseQueue = new PriorityQueue();
  64. parseQueue.maxJobs = 1;
  65. parseQueue.priorityCallback = priorityCallback;
  66. this.lruCache = lruCache;
  67. this.downloadQueue = downloadQueue;
  68. this.parseQueue = parseQueue;
  69. this.stats = {
  70. parsing: 0,
  71. downloading: 0,
  72. failed: 0,
  73. inFrustum: 0,
  74. used: 0,
  75. active: 0,
  76. visible: 0,
  77. };
  78. this.frameCount = 0;
  79. // options
  80. this.errorTarget = 6.0;
  81. this.errorThreshold = Infinity;
  82. this.loadSiblings = true;
  83. this.displayActiveTiles = false;
  84. this.maxDepth = Infinity;
  85. this.stopAtEmptyTiles = true;
  86. }
  87. traverse( beforecb, aftercb ) {
  88. const tileSets = this.tileSets;
  89. const rootTileSet = tileSets[ this.rootURL ];
  90. if ( ! rootTileSet || ! rootTileSet.root ) return;
  91. traverseSet( rootTileSet.root, beforecb, aftercb );
  92. }
  93. // Public API
  94. update() {
  95. const stats = this.stats;
  96. const lruCache = this.lruCache;
  97. const tileSets = this.tileSets;
  98. const rootTileSet = tileSets[ this.rootURL ];
  99. if ( ! ( this.rootURL in tileSets ) ) {
  100. this.loadRootTileSet( this.rootURL );
  101. return;
  102. } else if ( ! rootTileSet || ! rootTileSet.root ) {
  103. return;
  104. }
  105. const root = rootTileSet.root;
  106. stats.inFrustum = 0,
  107. stats.used = 0,
  108. stats.active = 0,
  109. stats.visible = 0,
  110. this.frameCount ++;
  111. determineFrustumSet( root, this );
  112. markUsedSetLeaves( root, this );
  113. skipTraversal( root, this );
  114. toggleTiles( root, this );
  115. lruCache.scheduleUnload();
  116. }
  117. // Overrideable
  118. parseTile( buffer, tile, extension ) {
  119. return null;
  120. }
  121. disposeTile( tile ) {
  122. }
  123. preprocessNode( tile, parentTile, tileSetDir ) {
  124. if ( tile.content ) {
  125. // Fix old file formats
  126. if ( ! ( 'uri' in tile.content ) && 'url' in tile.content ) {
  127. tile.content.uri = tile.content.url;
  128. delete tile.content.url;
  129. }
  130. if ( tile.content.uri ) {
  131. // tile content uri has to be interpreted relative to the tileset.json
  132. tile.content.uri = new URL( tile.content.uri, tileSetDir + '/' ).toString();
  133. }
  134. // NOTE: fix for some cases where tilesets provide the bounding volume
  135. // but volumes are not present.
  136. if (
  137. tile.content.boundingVolume &&
  138. ! (
  139. 'box' in tile.content.boundingVolume ||
  140. 'sphere' in tile.content.boundingVolume ||
  141. 'region' in tile.content.boundingVolume
  142. )
  143. ) {
  144. delete tile.content.boundingVolume;
  145. }
  146. }
  147. tile.parent = parentTile;
  148. tile.children = tile.children || [];
  149. const uri = tile.content && tile.content.uri;
  150. if ( uri ) {
  151. // "content" should only indicate loadable meshes, not external tile sets
  152. const extension = getUrlExtension( tile.content.uri );
  153. const isExternalTileSet = Boolean( extension && extension.toLowerCase() === 'json' );
  154. tile.__externalTileSet = isExternalTileSet;
  155. tile.__contentEmpty = isExternalTileSet;
  156. } else {
  157. tile.__externalTileSet = false;
  158. tile.__contentEmpty = true;
  159. }
  160. // Expected to be set during calculateError()
  161. tile.__distanceFromCamera = Infinity;
  162. tile.__error = Infinity;
  163. tile.__inFrustum = false;
  164. tile.__isLeaf = false;
  165. tile.__usedLastFrame = false;
  166. tile.__used = false;
  167. tile.__wasSetVisible = false;
  168. tile.__visible = false;
  169. tile.__childrenWereVisible = false;
  170. tile.__allChildrenLoaded = false;
  171. tile.__wasSetActive = false;
  172. tile.__active = false;
  173. tile.__loadingState = UNLOADED;
  174. tile.__loadIndex = 0;
  175. tile.__loadAbort = null;
  176. tile.__depthFromRenderedParent = - 1;
  177. if ( parentTile === null ) {
  178. tile.__depth = 0;
  179. tile.refine = tile.refine || 'REPLACE';
  180. } else {
  181. tile.__depth = parentTile.__depth + 1;
  182. tile.refine = tile.refine || parentTile.refine;
  183. }
  184. }
  185. setTileActive( tile, state ) {
  186. }
  187. setTileVisible( tile, state ) {
  188. }
  189. calculateError( tile ) {
  190. return 0;
  191. }
  192. tileInView( tile ) {
  193. return true;
  194. }
  195. resetFailedTiles() {
  196. const stats = this.stats;
  197. if ( stats.failed === 0 ) {
  198. return;
  199. }
  200. this.traverse( tile => {
  201. if ( tile.__loadingState === FAILED ) {
  202. tile.__loadingState = UNLOADED;
  203. }
  204. } );
  205. stats.failed = 0;
  206. }
  207. // Private Functions
  208. fetchTileSet( url, fetchOptions, parent = null ) {
  209. return fetch( url, fetchOptions )
  210. .then( res => {
  211. if ( res.ok ) {
  212. return res.json();
  213. } else {
  214. throw new Error( `TilesRenderer: Failed to load tileset "${ url }" with status ${ res.status } : ${ res.statusText }` );
  215. }
  216. } )
  217. .then( json => {
  218. const version = json.asset.version;
  219. console.assert(
  220. version === '1.0' || version === '0.0',
  221. 'asset.version is expected to be a string of "1.0" or "0.0"'
  222. );
  223. // remove trailing slash and last path-segment from the URL
  224. let basePath = url.replace( /\/[^\/]*\/?$/, '' );
  225. basePath = new URL( basePath, window.location.href ).toString();
  226. traverseSet(
  227. json.root,
  228. ( node, parent ) => this.preprocessNode( node, parent, basePath ),
  229. null,
  230. parent,
  231. parent ? parent.__depth : 0,
  232. );
  233. return json;
  234. } );
  235. }
  236. loadRootTileSet( url ) {
  237. const tileSets = this.tileSets;
  238. if ( ! ( url in tileSets ) ) {
  239. const pr = this
  240. .fetchTileSet( this.preprocessURL ? this.preprocessURL( url ) : url, this.fetchOptions )
  241. .then( json => {
  242. tileSets[ url ] = json;
  243. } );
  244. pr.catch( err => {
  245. console.error( err );
  246. tileSets[ url ] = err;
  247. } );
  248. tileSets[ url ] = pr;
  249. return pr;
  250. } else if ( tileSets[ url ] instanceof Error ) {
  251. return Promise.reject( tileSets[ url ] );
  252. } else {
  253. return Promise.resolve( tileSets[ url ] );
  254. }
  255. }
  256. requestTileContents( tile ) {
  257. // If the tile is already being loaded then don't
  258. // start it again.
  259. if ( tile.__loadingState !== UNLOADED ) {
  260. return;
  261. }
  262. const stats = this.stats;
  263. const lruCache = this.lruCache;
  264. const downloadQueue = this.downloadQueue;
  265. const parseQueue = this.parseQueue;
  266. const isExternalTileSet = tile.__externalTileSet;
  267. lruCache.add( tile, t => {
  268. // Stop the load if it's started
  269. if ( t.__loadingState === LOADING ) {
  270. t.__loadAbort.abort();
  271. t.__loadAbort = null;
  272. } else if ( isExternalTileSet ) {
  273. t.children.length = 0;
  274. } else {
  275. this.disposeTile( t );
  276. }
  277. // Decrement stats
  278. if ( t.__loadingState === LOADING ) {
  279. stats.downloading --;
  280. } else if ( t.__loadingState === PARSING ) {
  281. stats.parsing --;
  282. }
  283. t.__loadingState = UNLOADED;
  284. t.__loadIndex ++;
  285. parseQueue.remove( t );
  286. downloadQueue.remove( t );
  287. } );
  288. // Track a new load index so we avoid the condition where this load is stopped and
  289. // another begins soon after so we don't parse twice.
  290. tile.__loadIndex ++;
  291. const loadIndex = tile.__loadIndex;
  292. const controller = new AbortController();
  293. const signal = controller.signal;
  294. stats.downloading ++;
  295. tile.__loadAbort = controller;
  296. tile.__loadingState = LOADING;
  297. const errorCallback = e => {
  298. // if it has been unloaded then the tile has been disposed
  299. if ( tile.__loadIndex !== loadIndex ) {
  300. return;
  301. }
  302. if ( e.name !== 'AbortError' ) {
  303. parseQueue.remove( tile );
  304. downloadQueue.remove( tile );
  305. if ( tile.__loadingState === PARSING ) {
  306. stats.parsing --;
  307. } else if ( tile.__loadingState === LOADING ) {
  308. stats.downloading --;
  309. }
  310. stats.failed ++;
  311. console.error( `TilesRenderer : Failed to load tile at url "${ tile.content.uri }".` );
  312. console.error( e );
  313. tile.__loadingState = FAILED;
  314. } else {
  315. lruCache.remove( tile );
  316. }
  317. };
  318. if ( isExternalTileSet ) {
  319. downloadQueue.add( tile, tileCb => {
  320. // if it has been unloaded then the tile has been disposed
  321. if ( tileCb.__loadIndex !== loadIndex ) {
  322. return Promise.resolve();
  323. }
  324. const uri = this.preprocessURL ? this.preprocessURL( tileCb.content.uri ) : tileCb.content.uri;
  325. return this.fetchTileSet( uri, Object.assign( { signal }, this.fetchOptions ), tileCb );
  326. } )
  327. .then( json => {
  328. // if it has been unloaded then the tile has been disposed
  329. if ( tile.__loadIndex !== loadIndex ) {
  330. return;
  331. }
  332. stats.downloading --;
  333. tile.__loadAbort = null;
  334. tile.__loadingState = LOADED;
  335. tile.children.push( json.root );
  336. } )
  337. .catch( errorCallback );
  338. } else {
  339. downloadQueue.add( tile, downloadTile => {
  340. if ( downloadTile.__loadIndex !== loadIndex ) {
  341. return Promise.resolve();
  342. }
  343. const uri = this.preprocessURL ? this.preprocessURL( downloadTile.content.uri ) : downloadTile.content.uri;
  344. return fetch( uri, Object.assign( { signal }, this.fetchOptions ) );
  345. } )
  346. .then( res => {
  347. if ( tile.__loadIndex !== loadIndex ) {
  348. return;
  349. }
  350. if ( res.ok ) {
  351. return res.arrayBuffer();
  352. } else {
  353. throw new Error( `Failed to load model with error code ${res.status}` );
  354. }
  355. } )
  356. .then( buffer => {
  357. // if it has been unloaded then the tile has been disposed
  358. if ( tile.__loadIndex !== loadIndex ) {
  359. return;
  360. }
  361. stats.downloading --;
  362. stats.parsing ++;
  363. tile.__loadAbort = null;
  364. tile.__loadingState = PARSING;
  365. return parseQueue.add( tile, parseTile => {
  366. // if it has been unloaded then the tile has been disposed
  367. if ( parseTile.__loadIndex !== loadIndex ) {
  368. return Promise.resolve();
  369. }
  370. const uri = parseTile.content.uri;
  371. const extension = getUrlExtension( uri );
  372. return this.parseTile( buffer, parseTile, extension );
  373. } );
  374. } )
  375. .then( () => {
  376. // if it has been unloaded then the tile has been disposed
  377. if ( tile.__loadIndex !== loadIndex ) {
  378. return;
  379. }
  380. stats.parsing --;
  381. tile.__loadingState = LOADED;
  382. if ( tile.__wasSetVisible ) {
  383. this.setTileVisible( tile, true );
  384. }
  385. if ( tile.__wasSetActive ) {
  386. this.setTileActive( tile, true );
  387. }
  388. } )
  389. .catch( errorCallback );
  390. }
  391. }
  392. dispose() {
  393. const lruCache = this.lruCache;
  394. this.traverse( tile => {
  395. lruCache.remove( tile );
  396. } );
  397. this.stats = {
  398. parsing: 0,
  399. downloading: 0,
  400. failed: 0,
  401. inFrustum: 0,
  402. used: 0,
  403. active: 0,
  404. visible: 0,
  405. };
  406. this.frameCount = 0;
  407. }
  408. }