KMZLoader.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import {
  2. FileLoader,
  3. Group,
  4. Loader,
  5. LoadingManager
  6. } from '../../../build/three.module.js';
  7. import { ColladaLoader } from '../loaders/ColladaLoader.js';
  8. import * as fflate from '../libs/fflate.module.js';
  9. class KMZLoader extends Loader {
  10. constructor( manager ) {
  11. super( manager );
  12. }
  13. load( url, onLoad, onProgress, onError ) {
  14. const scope = this;
  15. const loader = new FileLoader( scope.manager );
  16. loader.setPath( scope.path );
  17. loader.setResponseType( 'arraybuffer' );
  18. loader.setRequestHeader( scope.requestHeader );
  19. loader.setWithCredentials( scope.withCredentials );
  20. loader.load( url, function ( text ) {
  21. try {
  22. onLoad( scope.parse( text ) );
  23. } catch ( e ) {
  24. if ( onError ) {
  25. onError( e );
  26. } else {
  27. console.error( e );
  28. }
  29. scope.manager.itemError( url );
  30. }
  31. }, onProgress, onError );
  32. }
  33. parse( data ) {
  34. function findFile( url ) {
  35. for ( const path in zip ) {
  36. if ( path.substr( - url.length ) === url ) {
  37. return zip[ path ];
  38. }
  39. }
  40. }
  41. const manager = new LoadingManager();
  42. manager.setURLModifier( function ( url ) {
  43. const image = findFile( url );
  44. if ( image ) {
  45. console.log( 'Loading', url );
  46. const blob = new Blob( [ image.buffer ], { type: 'application/octet-stream' } );
  47. return URL.createObjectURL( blob );
  48. }
  49. return url;
  50. } );
  51. //
  52. const zip = fflate.unzipSync( new Uint8Array( data ) ); // eslint-disable-line no-undef
  53. if ( zip[ 'doc.kml' ] ) {
  54. const xml = new DOMParser().parseFromString( fflate.strFromU8( zip[ 'doc.kml' ] ), 'application/xml' ); // eslint-disable-line no-undef
  55. const model = xml.querySelector( 'Placemark Model Link href' );
  56. if ( model ) {
  57. const loader = new ColladaLoader( manager );
  58. return loader.parse( fflate.strFromU8( zip[ model.textContent ] ) ); // eslint-disable-line no-undef
  59. }
  60. } else {
  61. console.warn( 'KMZLoader: Missing doc.kml file.' );
  62. for ( const path in zip ) {
  63. const extension = path.split( '.' ).pop().toLowerCase();
  64. if ( extension === 'dae' ) {
  65. const loader = new ColladaLoader( manager );
  66. return loader.parse( fflate.strFromU8( zip[ path ] ) ); // eslint-disable-line no-undef
  67. }
  68. }
  69. }
  70. console.error( 'KMZLoader: Couldn\'t find .dae file.' );
  71. return { scene: new Group() };
  72. }
  73. }
  74. export { KMZLoader };