CMPTLoaderBase.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // CMPT File Format
  2. // https://github.com/CesiumGS/3d-tiles/blob/master/specification/TileFormats/Composite/README.md
  3. export class CMPTLoaderBase {
  4. constructor() {
  5. this.fetchOptions = {};
  6. }
  7. load( url ) {
  8. return fetch( url, this.fetchOptions )
  9. .then( res => {
  10. if ( ! res.ok ) {
  11. throw new Error( `Failed to load file "${ url }" with status ${ res.status } : ${ res.statusText }` );
  12. }
  13. return res.arrayBuffer();
  14. } )
  15. .then( buffer => this.parse( buffer ) );
  16. }
  17. parse( buffer ) {
  18. const dataView = new DataView( buffer );
  19. // 16-byte header
  20. // 4 bytes
  21. const magic =
  22. String.fromCharCode( dataView.getUint8( 0 ) ) +
  23. String.fromCharCode( dataView.getUint8( 1 ) ) +
  24. String.fromCharCode( dataView.getUint8( 2 ) ) +
  25. String.fromCharCode( dataView.getUint8( 3 ) );
  26. console.assert( magic === 'cmpt' );
  27. // 4 bytes
  28. const version = dataView.getUint32( 4, true );
  29. console.assert( version === 1 );
  30. // 4 bytes
  31. const byteLength = dataView.getUint32( 8, true );
  32. console.assert( byteLength === buffer.byteLength );
  33. // 4 bytes
  34. const tilesLength = dataView.getUint32( 12, true );
  35. const tiles = [];
  36. let offset = 16;
  37. for ( let i = 0; i < tilesLength; i ++ ) {
  38. const tileView = new DataView( buffer, offset, 12 );
  39. const tileMagic =
  40. String.fromCharCode( tileView.getUint8( 0 ) ) +
  41. String.fromCharCode( tileView.getUint8( 1 ) ) +
  42. String.fromCharCode( tileView.getUint8( 2 ) ) +
  43. String.fromCharCode( tileView.getUint8( 3 ) );
  44. const tileVersion = tileView.getUint32( 4, true );
  45. const byteLength = tileView.getUint32( 8, true );
  46. const tileBuffer = new Uint8Array( buffer, offset, byteLength );
  47. tiles.push( {
  48. type: tileMagic,
  49. buffer: tileBuffer,
  50. version: tileVersion,
  51. } );
  52. offset += byteLength;
  53. }
  54. return {
  55. version,
  56. tiles,
  57. };
  58. }
  59. }