USDLoader.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import {
  2. FileLoader,
  3. Loader
  4. } from 'three';
  5. import { unzipSync } from '../libs/fflate.module.js';
  6. import { USDAParser } from './usd/USDAParser.js';
  7. import { USDCParser } from './usd/USDCParser.js';
  8. import { USDComposer } from './usd/USDComposer.js';
  9. /**
  10. * A loader for the USD format (USD, USDA, USDC, USDZ).
  11. *
  12. * Supports both ASCII (USDA) and binary (USDC) USD files, as well as
  13. * USDZ archives containing either format.
  14. *
  15. * ```js
  16. * const loader = new USDLoader();
  17. * const model = await loader.loadAsync( 'model.usdz' );
  18. * scene.add( model );
  19. * ```
  20. *
  21. * @augments Loader
  22. * @three_import import { USDLoader } from 'three/addons/loaders/USDLoader.js';
  23. */
  24. class USDLoader extends Loader {
  25. /**
  26. * Constructs a new USDZ loader.
  27. *
  28. * @param {LoadingManager} [manager] - The loading manager.
  29. */
  30. constructor( manager ) {
  31. super( manager );
  32. }
  33. /**
  34. * Starts loading from the given URL and passes the loaded USDZ asset
  35. * to the `onLoad()` callback.
  36. *
  37. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  38. * @param {function(Group)} onLoad - Executed when the loading process has been finished.
  39. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  40. * @param {onErrorCallback} onError - Executed when errors occur.
  41. */
  42. load( url, onLoad, onProgress, onError ) {
  43. const scope = this;
  44. const loader = new FileLoader( scope.manager );
  45. loader.setPath( scope.path );
  46. loader.setResponseType( 'arraybuffer' );
  47. loader.setRequestHeader( scope.requestHeader );
  48. loader.setWithCredentials( scope.withCredentials );
  49. loader.load( url, function ( text ) {
  50. try {
  51. onLoad( scope.parse( text ) );
  52. } catch ( e ) {
  53. if ( onError ) {
  54. onError( e );
  55. } else {
  56. console.error( e );
  57. }
  58. scope.manager.itemError( url );
  59. }
  60. }, onProgress, onError );
  61. }
  62. /**
  63. * Parses the given USDZ data and returns the resulting group.
  64. *
  65. * @param {ArrayBuffer|string} buffer - The raw USDZ data as an array buffer.
  66. * @return {Group} The parsed asset as a group.
  67. */
  68. parse( buffer ) {
  69. const usda = new USDAParser();
  70. const usdc = new USDCParser();
  71. const textDecoder = new TextDecoder();
  72. function toArrayBuffer( data ) {
  73. if ( data instanceof ArrayBuffer ) return data;
  74. if ( data.byteOffset === 0 && data.byteLength === data.buffer.byteLength ) {
  75. return data.buffer;
  76. }
  77. return data.buffer.slice( data.byteOffset, data.byteOffset + data.byteLength );
  78. }
  79. function getLowercaseExtension( filename ) {
  80. const lastDot = filename.lastIndexOf( '.' );
  81. if ( lastDot < 0 ) return '';
  82. const lastSlash = filename.lastIndexOf( '/' );
  83. if ( lastSlash > lastDot ) return '';
  84. return filename.slice( lastDot + 1 ).toLowerCase();
  85. }
  86. function parseAssets( zip ) {
  87. const data = {};
  88. for ( const filename in zip ) {
  89. const fileBytes = zip[ filename ];
  90. const ext = getLowercaseExtension( filename );
  91. if ( ext === 'png' || ext === 'jpg' || ext === 'jpeg' || ext === 'avif' ) {
  92. // Keep raw image bytes and create object URLs lazily in USDComposer.
  93. data[ filename ] = fileBytes;
  94. continue;
  95. }
  96. if ( ext !== 'usd' && ext !== 'usda' && ext !== 'usdc' ) continue;
  97. if ( isCrateFile( fileBytes ) ) {
  98. data[ filename ] = usdc.parseData( toArrayBuffer( fileBytes ) );
  99. } else {
  100. data[ filename ] = usda.parseData( textDecoder.decode( fileBytes ) );
  101. }
  102. }
  103. return data;
  104. }
  105. function isCrateFile( buffer ) {
  106. const crateHeader = new Uint8Array( [ 0x50, 0x58, 0x52, 0x2D, 0x55, 0x53, 0x44, 0x43 ] ); // PXR-USDC
  107. const view = buffer instanceof Uint8Array ? buffer : new Uint8Array( buffer );
  108. if ( view.byteLength < crateHeader.length ) return false;
  109. for ( let i = 0; i < crateHeader.length; i ++ ) {
  110. if ( view[ i ] !== crateHeader[ i ] ) return false;
  111. }
  112. return true;
  113. }
  114. function findUSD( zip ) {
  115. const fileNames = Object.keys( zip );
  116. if ( fileNames.length < 1 ) return { file: undefined, filename: '', basePath: '' };
  117. const firstFileName = fileNames[ 0 ];
  118. const ext = getLowercaseExtension( firstFileName );
  119. let isCrate = false;
  120. const lastSlash = firstFileName.lastIndexOf( '/' );
  121. const basePath = lastSlash >= 0 ? firstFileName.slice( 0, lastSlash ) : '';
  122. // Per AOUSD core spec v1.0.1 section 16.4.1.2, the first ZIP entry is the root layer.
  123. // ASCII files can end in either .usda or .usd.
  124. if ( ext === 'usda' ) return { file: zip[ firstFileName ], filename: firstFileName, basePath };
  125. if ( ext === 'usdc' ) {
  126. isCrate = true;
  127. } else if ( ext === 'usd' ) {
  128. // If this is not a crate file, we assume it is a plain USDA file.
  129. if ( ! isCrateFile( zip[ firstFileName ] ) ) {
  130. return { file: zip[ firstFileName ], filename: firstFileName, basePath };
  131. } else {
  132. isCrate = true;
  133. }
  134. }
  135. if ( isCrate ) {
  136. return { file: zip[ firstFileName ], filename: firstFileName, basePath };
  137. }
  138. return { file: undefined, filename: '', basePath: '' };
  139. }
  140. const scope = this;
  141. // USDA (standalone)
  142. if ( typeof buffer === 'string' ) {
  143. const composer = new USDComposer( scope.manager );
  144. const data = usda.parseData( buffer );
  145. return composer.compose( data, {} );
  146. }
  147. // USDC (standalone)
  148. if ( isCrateFile( buffer ) ) {
  149. const composer = new USDComposer( scope.manager );
  150. const data = usdc.parseData( toArrayBuffer( buffer ) );
  151. return composer.compose( data, {} );
  152. }
  153. const bytes = new Uint8Array( buffer );
  154. // USDZ
  155. if ( bytes[ 0 ] === 0x50 && bytes[ 1 ] === 0x4B ) {
  156. const zip = unzipSync( bytes );
  157. const assets = parseAssets( zip );
  158. const { file, filename, basePath } = findUSD( zip );
  159. if ( ! file ) {
  160. throw new Error( 'USDLoader: Invalid USDZ package. The first ZIP entry must be a USD layer (.usd/.usda/.usdc).' );
  161. }
  162. const composer = new USDComposer( scope.manager );
  163. const data = assets[ filename ];
  164. if ( ! data ) {
  165. throw new Error( 'USDLoader: Failed to parse root layer "' + filename + '".' );
  166. }
  167. return composer.compose( data, assets, {}, basePath );
  168. }
  169. // USDA (standalone, as ArrayBuffer)
  170. const composer = new USDComposer( scope.manager );
  171. const text = textDecoder.decode( bytes );
  172. const data = usda.parseData( text );
  173. return composer.compose( data, {} );
  174. }
  175. }
  176. export { USDLoader };
粤ICP备19079148号