USDLoader.js 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 ( data ) {
  50. scope.parse( data, onLoad, onError );
  51. }, onProgress, onError );
  52. }
  53. /**
  54. * Parses the given USDZ data and passes the resulting group to the `onLoad()` callback.
  55. *
  56. * @param {ArrayBuffer|string} buffer - The raw USDZ data as an array buffer.
  57. * @param {function(Group)} onLoad - Executed when the parsing process has been finished.
  58. * @param {onErrorCallback} [onError] - Executed when errors occur.
  59. */
  60. parse( buffer, onLoad, onError ) {
  61. const usda = new USDAParser();
  62. const usdc = new USDCParser();
  63. async function parseAssets( zip ) {
  64. const data = {};
  65. const imagePromises = [];
  66. for ( const filename in zip ) {
  67. if ( filename.endsWith( 'png' ) || filename.endsWith( 'jpg' ) || filename.endsWith( 'jpeg' ) ) {
  68. // Create ImageBitmap from raw image data
  69. const blob = new Blob( [ zip[ filename ] ] );
  70. imagePromises.push(
  71. createImageBitmap( blob, { colorSpaceConversion: 'none', imageOrientation: 'flipY' } ).then( imageBitmap => {
  72. data[ filename ] = imageBitmap;
  73. } )
  74. );
  75. }
  76. }
  77. await Promise.all( imagePromises );
  78. for ( const filename in zip ) {
  79. if ( filename.endsWith( 'usd' ) || filename.endsWith( 'usda' ) || filename.endsWith( 'usdc' ) ) {
  80. if ( isCrateFile( zip[ filename ] ) ) {
  81. // Store parsed data (specsByPath) for on-demand composition
  82. const parsedData = usdc.parseData( zip[ filename ].buffer );
  83. data[ filename ] = parsedData;
  84. // Store raw buffer for re-parsing with variant selections
  85. data[ filename + ':buffer' ] = zip[ filename ].buffer;
  86. } else {
  87. const text = new TextDecoder().decode( zip[ filename ] );
  88. // Store parsed data (specsByPath) for on-demand composition
  89. data[ filename ] = usda.parseData( text );
  90. // Store raw text for re-parsing with variant selections
  91. data[ filename + ':text' ] = text;
  92. }
  93. }
  94. }
  95. return data;
  96. }
  97. function isCrateFile( buffer ) {
  98. const crateHeader = new Uint8Array( [ 0x50, 0x58, 0x52, 0x2D, 0x55, 0x53, 0x44, 0x43 ] ); // PXR-USDC
  99. if ( buffer.byteLength < crateHeader.length ) return false;
  100. const view = new Uint8Array( buffer, 0, crateHeader.length );
  101. for ( let i = 0; i < crateHeader.length; i ++ ) {
  102. if ( view[ i ] !== crateHeader[ i ] ) return false;
  103. }
  104. return true;
  105. }
  106. function findUSD( zip ) {
  107. if ( zip.length < 1 ) return { file: undefined, basePath: '' };
  108. const firstFileName = Object.keys( zip )[ 0 ];
  109. let isCrate = false;
  110. const lastSlash = firstFileName.lastIndexOf( '/' );
  111. const basePath = lastSlash >= 0 ? firstFileName.slice( 0, lastSlash ) : '';
  112. // As per the USD specification, the first entry in the zip archive is used as the main file ("UsdStage").
  113. // ASCII files can end in either .usda or .usd.
  114. // See https://openusd.org/release/spec_usdz.html#layout
  115. if ( firstFileName.endsWith( 'usda' ) ) return { file: zip[ firstFileName ], basePath };
  116. if ( firstFileName.endsWith( 'usdc' ) ) {
  117. isCrate = true;
  118. } else if ( firstFileName.endsWith( 'usd' ) ) {
  119. // If this is not a crate file, we assume it is a plain USDA file.
  120. if ( ! isCrateFile( zip[ firstFileName ] ) ) {
  121. return { file: zip[ firstFileName ], basePath };
  122. } else {
  123. isCrate = true;
  124. }
  125. }
  126. if ( isCrate ) {
  127. return { file: zip[ firstFileName ], basePath };
  128. }
  129. return { file: undefined, basePath: '' };
  130. }
  131. const scope = this;
  132. async function doParse() {
  133. // USDA (standalone)
  134. if ( typeof buffer === 'string' ) {
  135. const composer = new USDComposer( scope.manager );
  136. const data = usda.parseData( buffer );
  137. return composer.compose( data, {} );
  138. }
  139. // USDC (standalone)
  140. if ( isCrateFile( buffer ) ) {
  141. const composer = new USDComposer( scope.manager );
  142. const data = usdc.parseData( buffer );
  143. return composer.compose( data, {} );
  144. }
  145. const bytes = new Uint8Array( buffer );
  146. // USDZ
  147. if ( bytes[ 0 ] === 0x50 && bytes[ 1 ] === 0x4B ) {
  148. const zip = unzipSync( bytes );
  149. const assets = await parseAssets( zip );
  150. const { file, basePath } = findUSD( zip );
  151. const composer = new USDComposer( scope.manager );
  152. let data;
  153. if ( isCrateFile( file ) ) {
  154. data = usdc.parseData( file.buffer );
  155. } else {
  156. const text = new TextDecoder().decode( file );
  157. data = usda.parseData( text );
  158. }
  159. return composer.compose( data, assets, {}, basePath );
  160. }
  161. // USDA (standalone, as ArrayBuffer)
  162. const composer = new USDComposer( scope.manager );
  163. const text = new TextDecoder().decode( bytes );
  164. const data = usda.parseData( text );
  165. return composer.compose( data, {} );
  166. }
  167. doParse().then( onLoad ).catch( e => {
  168. if ( onError ) {
  169. onError( e );
  170. } else {
  171. console.error( e );
  172. }
  173. } );
  174. }
  175. /**
  176. * Async version of {@link USDLoader#parse}.
  177. *
  178. * @async
  179. * @param {ArrayBuffer|string} buffer - The raw USDZ data as an array buffer.
  180. * @return {Promise<Group>} A Promise that resolves with the parsed group when the parsing has been finished.
  181. */
  182. parseAsync( buffer ) {
  183. const scope = this;
  184. return new Promise( function ( resolve, reject ) {
  185. scope.parse( buffer, resolve, reject );
  186. } );
  187. }
  188. }
  189. export { USDLoader };
粤ICP备19079148号