TilesRenderer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. import path from 'path';
  2. import { LRUCache } from './LRUCache.js';
  3. import { PriorityQueue } from './PriorityQueue.js';
  4. // TODO: find out why tiles are left dangling in the hierarchy
  5. // TODO: Address the issue of too many promises, garbage collection
  6. // TODO: remove more redundant computation
  7. // TODO: See if using classes improves performance
  8. // TODO: See if declaring function inline improves performance
  9. // TODO: Make sure active state works as expected
  10. const UNLOADED = 0;
  11. const LOADING = 1;
  12. const PARSING = 2;
  13. const LOADED = 3;
  14. const FAILED = 4;
  15. function traverseSet( tile, beforeCb = null, afterCb = null, parent = null, depth = 0 ) {
  16. if ( beforeCb && beforeCb( tile, parent, depth ) ) {
  17. if ( afterCb ) {
  18. afterCb( tile, parent, depth );
  19. }
  20. return;
  21. }
  22. const children = tile.children;
  23. for ( let i = 0, l = children.length; i < l; i ++ ) {
  24. traverseSet( children[ i ], beforeCb, afterCb, tile, depth + 1 );
  25. }
  26. if ( afterCb ) {
  27. afterCb( tile, parent, depth );
  28. }
  29. }
  30. function isUsedThisFrame( tile, frameCount ) {
  31. return tile.__lastFrameVisited === frameCount && tile.__used;
  32. }
  33. function resetFrameState( tile, frameCount ) {
  34. if ( tile.__lastFrameVisited !== frameCount ) {
  35. tile.__lastFrameVisited = frameCount;
  36. tile.__used = false;
  37. tile.__inFrustum = false;
  38. tile.__isLeaf = false;
  39. tile.__visible = false;
  40. tile.__active = false;
  41. tile.__error = 0;
  42. }
  43. }
  44. function recursivelyMarkUsed( tile, frameCount, lruCache ) {
  45. resetFrameState( tile, frameCount );
  46. tile.__used = true;
  47. lruCache.markUsed( tile );
  48. if ( tile.__contentEmpty ) {
  49. const children = tile.children;
  50. for ( let i = 0, l = children.length; i < l; i ++ ) {
  51. recursivelyMarkUsed( children[ i ], frameCount, lruCache );
  52. }
  53. }
  54. }
  55. // TODO: include frustum mask here?
  56. function determineFrustumSet( tile, renderer ) {
  57. const stats = renderer.stats;
  58. const frameCount = renderer.frameCount;
  59. const errorTarget = renderer.errorTarget;
  60. const maxDepth = renderer.maxDepth;
  61. const loadSiblings = renderer.loadSiblings;
  62. const lruCache = renderer.lruCache;
  63. resetFrameState( tile, frameCount );
  64. const inFrustum = renderer.tileInView( tile );
  65. if ( inFrustum === false ) {
  66. return false;
  67. }
  68. tile.__used = true;
  69. lruCache.markUsed( tile );
  70. tile.__inFrustum = true;
  71. stats.inFrustum ++;
  72. if ( ! tile.__contentEmpty ) {
  73. const error = renderer.calculateError( tile );
  74. tile.__error = error;
  75. if ( error <= errorTarget ) {
  76. return true;
  77. }
  78. }
  79. if ( renderer.maxDepth > 0 && tile.__depth + 1 >= maxDepth ) {
  80. return true;
  81. }
  82. let anyChildrenUsed = false;
  83. const children = tile.children;
  84. for ( let i = 0, l = children.length; i < l; i ++ ) {
  85. const c = children[ i ];
  86. const r = determineFrustumSet( c, renderer );
  87. anyChildrenUsed = anyChildrenUsed || r;
  88. }
  89. if ( anyChildrenUsed && loadSiblings ) {
  90. for ( let i = 0, l = children.length; i < l; i ++ ) {
  91. recursivelyMarkUsed( tile, frameCount, lruCache );
  92. }
  93. }
  94. return true;
  95. }
  96. function markUsedSetLeaves( tile, renderer ) {
  97. const stats = renderer.stats;
  98. const frameCount = renderer.frameCount;
  99. if ( ! isUsedThisFrame( tile, frameCount ) ) {
  100. return;
  101. }
  102. stats.used ++;
  103. const children = tile.children;
  104. let anyChildrenUsed = false;
  105. for ( let i = 0, l = children.length; i < l; i ++ ) {
  106. const c = children[ i ];
  107. anyChildrenUsed = anyChildrenUsed || isUsedThisFrame( c, frameCount );
  108. }
  109. if ( ! anyChildrenUsed ) {
  110. tile.__isLeaf = true;
  111. // TODO: stats
  112. } else {
  113. for ( let i = 0, l = children.length; i < l; i ++ ) {
  114. const c = children[ i ];
  115. markUsedSetLeaves( c, renderer );
  116. }
  117. }
  118. }
  119. function skipTraversal( tile, renderer ) {
  120. const stats = renderer.stats;
  121. const frameCount = renderer.frameCount;
  122. if ( ! isUsedThisFrame( tile, frameCount ) ) {
  123. return;
  124. }
  125. const lruCache = renderer.lruCache;
  126. if ( tile.__isLeaf ) {
  127. if ( tile.__loadingState === LOADED ) {
  128. if ( tile.__inFrustum ) {
  129. tile.__visible = true;
  130. stats.visible ++;
  131. }
  132. tile.__active = true;
  133. stats.active ++;
  134. } else if ( ! lruCache.isFull() ) {
  135. renderer.requestTileContents( tile );
  136. }
  137. return;
  138. }
  139. const errorRequirement = renderer.errorTarget * renderer.errorThreshold;
  140. const meetsSSE = tile.__error < errorRequirement;
  141. const hasContent = tile.__loadingState === LOADED && ! tile.__contentEmpty;
  142. const children = tile.children;
  143. let allChildrenHaveContent = true;
  144. for ( let i = 0, l = children.length; i < l; i ++ ) {
  145. const c = children[ i ];
  146. if ( isUsedThisFrame( c, frameCount ) ) {
  147. const childContent = c.__loadingState === LOADED || tile.__contentEmpty;
  148. allChildrenHaveContent = allChildrenHaveContent && childContent;
  149. }
  150. }
  151. if ( meetsSSE && ! hasContent && ! lruCache.isFull() ) {
  152. renderer.requestTileContents( tile );
  153. }
  154. if ( meetsSSE && hasContent && ! allChildrenHaveContent ) {
  155. if ( tile.__inFrustum ) {
  156. tile.__visible = true;
  157. stats.visible ++;
  158. }
  159. tile.__active = true;
  160. stats.active ++;
  161. for ( let i = 0, l = children.length; i < l; i ++ ) {
  162. const c = children[ i ];
  163. if ( isUsedThisFrame( c, frameCount ) && ! lruCache.isFull() ) {
  164. renderer.requestTileContents( c );
  165. }
  166. }
  167. return;
  168. }
  169. for ( let i = 0, l = children.length; i < l; i ++ ) {
  170. const c = children[ i ];
  171. if ( isUsedThisFrame( c, frameCount ) ) {
  172. skipTraversal( c, renderer );
  173. }
  174. }
  175. }
  176. function toggleTiles( tile, renderer ) {
  177. const frameCount = renderer.frameCount;
  178. const isUsed = isUsedThisFrame( tile, frameCount );
  179. if ( isUsed || tile.__usedLastFrame ) {
  180. if ( ! isUsed ) {
  181. if ( ! tile.__contentEmpty && tile.__loadingState === LOADED ) {
  182. renderer.setTileVisible( tile, false );
  183. renderer.setTileActive( tile, false );
  184. }
  185. tile.__usedLastFrame = false;
  186. } else {
  187. if ( ! tile.__contentEmpty && tile.__loadingState === LOADED ) {
  188. // enable visibility if active due to shadows
  189. renderer.setTileActive( tile, tile.__active );
  190. renderer.setTileVisible( tile, tile.__active || tile.__visible );
  191. }
  192. tile.__usedLastFrame = true;
  193. }
  194. const children = tile.children;
  195. for ( let i = 0, l = children.length; i < l; i ++ ) {
  196. const c = children[ i ];
  197. toggleTiles( c, renderer );
  198. }
  199. }
  200. }
  201. class TilesRenderer {
  202. get root() {
  203. const tileSet = this.tileSets[ this.rootSet ];
  204. if ( ! tileSet || tileSet instanceof Promise ) {
  205. return null;
  206. } else {
  207. return tileSet.root;
  208. }
  209. }
  210. constructor( url, cache = new LRUCache(), downloadQueue = new PriorityQueue( 6 ), parseQueue = new PriorityQueue( 2 ) ) {
  211. // state
  212. this.tileSets = {};
  213. this.rootSet = url;
  214. this.lruCache = cache;
  215. this.downloadQueue = downloadQueue;
  216. this.parseQueue = parseQueue;
  217. this.stats = {
  218. parsing: 0,
  219. downloading: 0,
  220. inFrustum: 0,
  221. used: 0,
  222. active: 0,
  223. visible: 0,
  224. };
  225. this.frameCount = 0;
  226. // options
  227. this.errorTarget = 6.0;
  228. this.errorThreshold = 6.0;
  229. this.loadSiblings = true;
  230. this.maxDepth = Infinity;
  231. this.loadSiblings = true;
  232. this.loadTileSet( url );
  233. }
  234. traverse( cb ) {
  235. const tileSets = this.tileSets;
  236. const rootTileSet = tileSets[ this.rootSet ];
  237. if ( ! rootTileSet || ! rootTileSet.root ) return;
  238. traverseSet( rootTileSet.root, cb );
  239. }
  240. // Public API
  241. update() {
  242. const stats = this.stats;
  243. const lruCache = this.lruCache;
  244. const tileSets = this.tileSets;
  245. const rootTileSet = tileSets[ this.rootSet ];
  246. if ( ! rootTileSet || ! rootTileSet.root ) return;
  247. const root = rootTileSet.root;
  248. stats.inFrustum = 0,
  249. stats.used = 0,
  250. stats.active = 0,
  251. stats.visible = 0,
  252. this.frameCount ++;
  253. determineFrustumSet( root, this );
  254. markUsedSetLeaves( root, this );
  255. skipTraversal( root, this );
  256. toggleTiles( root, this );
  257. // TODO: We may want to add this function in the requestTileContents function
  258. lruCache.scheduleUnload( null );
  259. }
  260. // Overrideable
  261. parseTile( buffer, tile ) {
  262. return null;
  263. }
  264. disposeTile( tile ) {
  265. }
  266. preprocessNode( tile, parentTile, tileSetDir ) {
  267. if ( tile.content ) {
  268. if ( ! ( 'uri' in tile.content ) && 'url' in tile.content ) {
  269. tile.content.uri = tile.content.url;
  270. delete tile.content.url;
  271. }
  272. if ( tile.content.uri ) {
  273. tile.content.uri = path.join( tileSetDir, tile.content.uri );
  274. }
  275. // TODO: fix for some cases where tilesets provide the bounding volume
  276. // but volumes are not present. See
  277. if (
  278. tile.content.boundingVolume &&
  279. ! (
  280. 'box' in tile.content.boundingVolume ||
  281. 'sphere' in tile.content.boundingVolume ||
  282. 'region' in tile.content.boundingVolume
  283. )
  284. ) {
  285. delete tile.content.boundingVolume;
  286. }
  287. }
  288. tile.parent = parentTile;
  289. tile.__contentEmpty = ! tile.content || ! tile.content.uri;
  290. tile.__error = 0.0;
  291. tile.__inFrustum = false;
  292. tile.__isLeaf = false;
  293. tile.__wasUsed = false;
  294. tile.__used = false;
  295. tile.__wasVisible = false;
  296. tile.__visible = false;
  297. tile.__wasActive = false;
  298. tile.__active = false;
  299. tile.__childrenActive = false;
  300. tile.__loadingState = UNLOADED;
  301. tile.__loadIndex = 0;
  302. tile.__loadAbort = null;
  303. if ( parentTile === null ) {
  304. tile.__depth = 0;
  305. } else {
  306. tile.__depth = parentTile.__depth + 1;
  307. }
  308. }
  309. setTileActive( tile, state ) {
  310. }
  311. setTileVisible( tile, state ) {
  312. }
  313. calculateError( tile ) {
  314. return 0;
  315. }
  316. tileInView( tile ) {
  317. return true;
  318. }
  319. // Private Functions
  320. loadTileSet( url ) {
  321. const tileSets = this.tileSets;
  322. if ( ! ( url in tileSets ) ) {
  323. const pr =
  324. fetch( url, { credentials: 'same-origin' } )
  325. .then( res => {
  326. if ( res.ok ) {
  327. return res.json();
  328. } else {
  329. throw new Error( `Status ${ res.status } (${ res.statusText })` );
  330. }
  331. } )
  332. .then( json => {
  333. // TODO: Add version query?
  334. const version = json.asset.version;
  335. console.assert( version === '1.0' || version === '0.0' );
  336. const basePath = path.dirname( url );
  337. traverseSet( json.root, ( node, parent ) => this.preprocessNode( node, parent, basePath ) );
  338. tileSets[ url ] = json;
  339. // TODO: schedule an update to avoid doing this too many times
  340. this.update();
  341. } );
  342. pr.catch( e => {
  343. console.error( `TilesLoader: Failed to load tile set json "${ url }"` );
  344. console.error( e );
  345. delete tileSets[ url ];
  346. } );
  347. tileSets[ url ] = pr;
  348. }
  349. return Promise.resolve( tileSets[ url ] );
  350. }
  351. requestTileContents( tile ) {
  352. // If the tile is already being loaded then don't
  353. // start it again.
  354. if ( tile.__loadingState !== UNLOADED ) {
  355. return;
  356. }
  357. // TODO: reuse the functions created here?
  358. const lruCache = this.lruCache;
  359. const downloadQueue = this.downloadQueue;
  360. const parseQueue = this.parseQueue;
  361. lruCache.add( tile, t => {
  362. if ( t.__loadingState === LOADING ) {
  363. t.__loadAbort.abort();
  364. t.__loadAbort = null;
  365. } else {
  366. this.disposeTile( t );
  367. }
  368. if ( t.__loadingState === LOADING ) {
  369. stats.downloading --;
  370. } else if ( t.__loadingState === PARSING ) {
  371. stats.parsing --;
  372. }
  373. t.__loadingState = UNLOADED;
  374. t.__loadIndex ++;
  375. // TODO: Removing from the queues here is slow
  376. // parseQueue.remove( t );
  377. // downloadQueue.remove( t );
  378. } );
  379. tile.__loadIndex ++;
  380. const loadIndex = tile.__loadIndex;
  381. const priority = 1 / ( tile.__depth + 1 );
  382. const stats = this.stats;
  383. const controller = new AbortController();
  384. const signal = controller.signal;
  385. stats.downloading ++;
  386. tile.__loadAbort = controller;
  387. tile.__loadingState = LOADING;
  388. downloadQueue.add( tile, priority, tile => {
  389. if ( tile.__loadIndex !== loadIndex ) {
  390. return Promise.resolve();
  391. }
  392. return fetch( tile.content.uri, { credentials: 'same-origin', signal } );
  393. } )
  394. .then( res => {
  395. if ( tile.__loadIndex !== loadIndex ) {
  396. return;
  397. }
  398. if ( res.ok ) {
  399. return res.arrayBuffer();
  400. } else {
  401. throw new Error( `Failed to load model with error code ${res.status}` );
  402. }
  403. } )
  404. .then( buffer => {
  405. if ( tile.__loadIndex !== loadIndex ) {
  406. return;
  407. }
  408. stats.downloading --;
  409. stats.parsing ++;
  410. tile.__loadAbort = null;
  411. tile.__loadingState = PARSING;
  412. return parseQueue.add( buffer, priority, buffer => {
  413. if ( tile.__loadIndex !== loadIndex ) {
  414. return Promise.resolve();
  415. }
  416. return this.parseTile( buffer, tile );
  417. } );
  418. } )
  419. .then( () => {
  420. if ( tile.__loadIndex !== loadIndex ) {
  421. return;
  422. }
  423. stats.parsing --;
  424. tile.__loadingState = LOADED;
  425. this.setTileActive( tile, tile.__active );
  426. this.setTileVisible( tile, tile.__visible );
  427. } )
  428. .catch( e => {
  429. // if it has been unloaded then the tile has been disposed
  430. if ( tile.__loadIndex !== loadIndex ) {
  431. return;
  432. }
  433. if ( e.name !== 'AbortError' ) {
  434. console.error( 'TilesRenderer : Failed to load tile.' );
  435. console.error( e );
  436. tile.__loadingState = FAILED;
  437. } else {
  438. lruCache.remove( tile );
  439. }
  440. } );
  441. }
  442. }
  443. export { TilesRenderer };