TilesRendererBase.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. const basePath = url.replace( /\/[^\/]*\/?$/, '' );
  225. traverseSet(
  226. json.root,
  227. ( node, parent ) => this.preprocessNode( node, parent, basePath ),
  228. null,
  229. parent,
  230. parent ? parent.__depth : 0,
  231. );
  232. return json;
  233. } );
  234. }
  235. loadRootTileSet( url ) {
  236. const tileSets = this.tileSets;
  237. if ( ! ( url in tileSets ) ) {
  238. const pr = this
  239. .fetchTileSet( this.preprocessURL ? this.preprocessURL( url ) : url, this.fetchOptions )
  240. .then( json => {
  241. tileSets[ url ] = json;
  242. } );
  243. pr.catch( err => {
  244. console.error( err );
  245. tileSets[ url ] = err;
  246. } );
  247. tileSets[ url ] = pr;
  248. return pr;
  249. } else if ( tileSets[ url ] instanceof Error ) {
  250. return Promise.reject( tileSets[ url ] );
  251. } else {
  252. return Promise.resolve( tileSets[ url ] );
  253. }
  254. }
  255. requestTileContents( tile ) {
  256. // If the tile is already being loaded then don't
  257. // start it again.
  258. if ( tile.__loadingState !== UNLOADED ) {
  259. return;
  260. }
  261. const stats = this.stats;
  262. const lruCache = this.lruCache;
  263. const downloadQueue = this.downloadQueue;
  264. const parseQueue = this.parseQueue;
  265. const isExternalTileSet = tile.__externalTileSet;
  266. lruCache.add( tile, t => {
  267. // Stop the load if it's started
  268. if ( t.__loadingState === LOADING ) {
  269. t.__loadAbort.abort();
  270. t.__loadAbort = null;
  271. } else if ( isExternalTileSet ) {
  272. t.children.length = 0;
  273. } else {
  274. this.disposeTile( t );
  275. }
  276. // Decrement stats
  277. if ( t.__loadingState === LOADING ) {
  278. stats.downloading --;
  279. } else if ( t.__loadingState === PARSING ) {
  280. stats.parsing --;
  281. }
  282. t.__loadingState = UNLOADED;
  283. t.__loadIndex ++;
  284. parseQueue.remove( t );
  285. downloadQueue.remove( t );
  286. } );
  287. // Track a new load index so we avoid the condition where this load is stopped and
  288. // another begins soon after so we don't parse twice.
  289. tile.__loadIndex ++;
  290. const loadIndex = tile.__loadIndex;
  291. const controller = new AbortController();
  292. const signal = controller.signal;
  293. stats.downloading ++;
  294. tile.__loadAbort = controller;
  295. tile.__loadingState = LOADING;
  296. const errorCallback = e => {
  297. // if it has been unloaded then the tile has been disposed
  298. if ( tile.__loadIndex !== loadIndex ) {
  299. return;
  300. }
  301. if ( e.name !== 'AbortError' ) {
  302. parseQueue.remove( tile );
  303. downloadQueue.remove( tile );
  304. if ( tile.__loadingState === PARSING ) {
  305. stats.parsing --;
  306. } else if ( tile.__loadingState === LOADING ) {
  307. stats.downloading --;
  308. }
  309. stats.failed ++;
  310. console.error( `TilesRenderer : Failed to load tile at url "${ tile.content.uri }".` );
  311. console.error( e );
  312. tile.__loadingState = FAILED;
  313. } else {
  314. lruCache.remove( tile );
  315. }
  316. };
  317. if ( isExternalTileSet ) {
  318. downloadQueue.add( tile, tileCb => {
  319. // if it has been unloaded then the tile has been disposed
  320. if ( tileCb.__loadIndex !== loadIndex ) {
  321. return Promise.resolve();
  322. }
  323. const uri = this.preprocessURL ? this.preprocessURL( tileCb.content.uri ) : tileCb.content.uri;
  324. return this.fetchTileSet( uri, Object.assign( { signal }, this.fetchOptions ), tileCb );
  325. } )
  326. .then( json => {
  327. // if it has been unloaded then the tile has been disposed
  328. if ( tile.__loadIndex !== loadIndex ) {
  329. return;
  330. }
  331. stats.downloading --;
  332. tile.__loadAbort = null;
  333. tile.__loadingState = LOADED;
  334. tile.children.push( json.root );
  335. } )
  336. .catch( errorCallback );
  337. } else {
  338. downloadQueue.add( tile, downloadTile => {
  339. if ( downloadTile.__loadIndex !== loadIndex ) {
  340. return Promise.resolve();
  341. }
  342. const uri = this.preprocessURL ? this.preprocessURL( downloadTile.content.uri ) : downloadTile.content.uri;
  343. return fetch( uri, Object.assign( { signal }, this.fetchOptions ) );
  344. } )
  345. .then( res => {
  346. if ( tile.__loadIndex !== loadIndex ) {
  347. return;
  348. }
  349. if ( res.ok ) {
  350. return res.arrayBuffer();
  351. } else {
  352. throw new Error( `Failed to load model with error code ${res.status}` );
  353. }
  354. } )
  355. .then( buffer => {
  356. // if it has been unloaded then the tile has been disposed
  357. if ( tile.__loadIndex !== loadIndex ) {
  358. return;
  359. }
  360. stats.downloading --;
  361. stats.parsing ++;
  362. tile.__loadAbort = null;
  363. tile.__loadingState = PARSING;
  364. return parseQueue.add( tile, parseTile => {
  365. // if it has been unloaded then the tile has been disposed
  366. if ( parseTile.__loadIndex !== loadIndex ) {
  367. return Promise.resolve();
  368. }
  369. const uri = parseTile.content.uri;
  370. const extension = getUrlExtension( uri );
  371. return this.parseTile( buffer, parseTile, extension );
  372. } );
  373. } )
  374. .then( () => {
  375. // if it has been unloaded then the tile has been disposed
  376. if ( tile.__loadIndex !== loadIndex ) {
  377. return;
  378. }
  379. stats.parsing --;
  380. tile.__loadingState = LOADED;
  381. if ( tile.__wasSetVisible ) {
  382. this.setTileVisible( tile, true );
  383. }
  384. if ( tile.__wasSetActive ) {
  385. this.setTileActive( tile, true );
  386. }
  387. } )
  388. .catch( errorCallback );
  389. }
  390. }
  391. dispose() {
  392. const lruCache = this.lruCache;
  393. this.traverse( tile => {
  394. lruCache.remove( tile );
  395. } );
  396. }
  397. }