USDZLoader.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. ClampToEdgeWrapping,
  5. FileLoader,
  6. Group,
  7. NoColorSpace,
  8. Loader,
  9. Mesh,
  10. MeshPhysicalMaterial,
  11. MirroredRepeatWrapping,
  12. RepeatWrapping,
  13. SRGBColorSpace,
  14. TextureLoader,
  15. Object3D,
  16. Vector2
  17. } from 'three';
  18. import * as fflate from '../libs/fflate.module.js';
  19. class USDAParser {
  20. parse( text ) {
  21. const data = {};
  22. const lines = text.split( '\n' );
  23. const length = lines.length;
  24. let current = 0;
  25. let string = null;
  26. let target = data;
  27. const stack = [ data ];
  28. // debugger;
  29. function parseNextLine() {
  30. const line = lines[ current ];
  31. // console.log( line );
  32. if ( line.includes( '=' ) ) {
  33. const assignment = line.split( '=' );
  34. const lhs = assignment[ 0 ].trim();
  35. const rhs = assignment[ 1 ].trim();
  36. if ( rhs.endsWith( '{' ) ) {
  37. const group = {};
  38. stack.push( group );
  39. target[ lhs ] = group;
  40. target = group;
  41. } else {
  42. target[ lhs ] = rhs;
  43. }
  44. } else if ( line.endsWith( '{' ) ) {
  45. const group = target[ string ] || {};
  46. stack.push( group );
  47. target[ string ] = group;
  48. target = group;
  49. } else if ( line.endsWith( '}' ) ) {
  50. stack.pop();
  51. if ( stack.length === 0 ) return;
  52. target = stack[ stack.length - 1 ];
  53. } else if ( line.endsWith( '(' ) ) {
  54. const meta = {};
  55. stack.push( meta );
  56. string = line.split( '(' )[ 0 ].trim() || string;
  57. target[ string ] = meta;
  58. target = meta;
  59. } else if ( line.endsWith( ')' ) ) {
  60. stack.pop();
  61. target = stack[ stack.length - 1 ];
  62. } else {
  63. string = line.trim();
  64. }
  65. current ++;
  66. if ( current < length ) {
  67. parseNextLine();
  68. }
  69. }
  70. parseNextLine();
  71. return data;
  72. }
  73. }
  74. class USDZLoader extends Loader {
  75. constructor( manager ) {
  76. super( manager );
  77. }
  78. load( url, onLoad, onProgress, onError ) {
  79. const scope = this;
  80. const loader = new FileLoader( scope.manager );
  81. loader.setPath( scope.path );
  82. loader.setResponseType( 'arraybuffer' );
  83. loader.setRequestHeader( scope.requestHeader );
  84. loader.setWithCredentials( scope.withCredentials );
  85. loader.load( url, function ( text ) {
  86. try {
  87. onLoad( scope.parse( text ) );
  88. } catch ( e ) {
  89. if ( onError ) {
  90. onError( e );
  91. } else {
  92. console.error( e );
  93. }
  94. scope.manager.itemError( url );
  95. }
  96. }, onProgress, onError );
  97. }
  98. parse( buffer ) {
  99. const parser = new USDAParser();
  100. function parseAssets( zip ) {
  101. const data = {};
  102. const loader = new FileLoader();
  103. loader.setResponseType( 'arraybuffer' );
  104. for ( const filename in zip ) {
  105. if ( filename.endsWith( 'png' ) ) {
  106. const blob = new Blob( [ zip[ filename ] ], { type: { type: 'image/png' } } );
  107. data[ filename ] = URL.createObjectURL( blob );
  108. }
  109. if ( filename.endsWith( 'usd' ) || filename.endsWith( 'usda' ) ) {
  110. if ( isCrateFile( zip[ filename ] ) ) {
  111. console.warn( 'THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.' );
  112. continue;
  113. }
  114. const text = fflate.strFromU8( zip[ filename ] );
  115. data[ filename ] = parser.parse( text );
  116. }
  117. }
  118. return data;
  119. }
  120. function isCrateFile( buffer ) {
  121. // Check if this a crate file. First 7 bytes of a crate file are "PXR-USDC".
  122. const fileHeader = buffer.slice( 0, 7 );
  123. const crateHeader = new Uint8Array( [ 0x50, 0x58, 0x52, 0x2D, 0x55, 0x53, 0x44, 0x43 ] );
  124. // If this is not a crate file, we assume it is a plain USDA file.
  125. return fileHeader.every( ( value, index ) => value === crateHeader[ index ] );
  126. }
  127. function findUSD( zip ) {
  128. if ( zip.length < 1 ) return undefined;
  129. const firstFileName = Object.keys( zip )[ 0 ];
  130. let isCrate = false;
  131. // As per the USD specification, the first entry in the zip archive is used as the main file ("UsdStage").
  132. // ASCII files can end in either .usda or .usd.
  133. // See https://openusd.org/release/spec_usdz.html#layout
  134. if ( firstFileName.endsWith( 'usda' ) ) return zip[ firstFileName ];
  135. if ( firstFileName.endsWith( 'usdc' ) ) {
  136. isCrate = true;
  137. } else if ( firstFileName.endsWith( 'usd' ) ) {
  138. // If this is not a crate file, we assume it is a plain USDA file.
  139. if ( ! isCrateFile( zip[ firstFileName ] ) ) {
  140. return zip[ firstFileName ];
  141. } else {
  142. isCrate = true;
  143. }
  144. }
  145. if ( isCrate ) {
  146. console.warn( 'THREE.USDZLoader: Crate files (.usdc or binary .usd) are not supported.' );
  147. }
  148. return undefined;
  149. }
  150. const zip = fflate.unzipSync( new Uint8Array( buffer ) );
  151. // console.log( zip );
  152. const assets = parseAssets( zip );
  153. // console.log( assets )
  154. const file = findUSD( zip );
  155. if ( file === undefined ) {
  156. console.warn( 'THREE.USDZLoader: No usda file found.' );
  157. return new Group();
  158. }
  159. // Parse file
  160. const text = fflate.strFromU8( file );
  161. const root = parser.parse( text );
  162. // Build scene
  163. function findMeshGeometry( data ) {
  164. if ( ! data ) return undefined;
  165. if ( 'prepend references' in data ) {
  166. const reference = data[ 'prepend references' ];
  167. const parts = reference.split( '@' );
  168. const path = parts[ 1 ].replace( /^.\//, '' );
  169. const id = parts[ 2 ].replace( /^<\//, '' ).replace( />$/, '' );
  170. return findGeometry( assets[ path ], id );
  171. }
  172. return findGeometry( data );
  173. }
  174. function findGeometry( data, id ) {
  175. if ( ! data ) return undefined;
  176. if ( id !== undefined ) {
  177. const def = `def Mesh "${id}"`;
  178. if ( def in data ) {
  179. return data[ def ];
  180. }
  181. }
  182. for ( const name in data ) {
  183. const object = data[ name ];
  184. if ( name.startsWith( 'def Mesh' ) ) {
  185. // Move points to Mesh
  186. if ( 'point3f[] points' in data ) {
  187. object[ 'point3f[] points' ] = data[ 'point3f[] points' ];
  188. }
  189. // Move st to Mesh
  190. if ( 'texCoord2f[] primvars:st' in data ) {
  191. object[ 'texCoord2f[] primvars:st' ] = data[ 'texCoord2f[] primvars:st' ];
  192. }
  193. // Move st indices to Mesh
  194. if ( 'int[] primvars:st:indices' in data ) {
  195. object[ 'int[] primvars:st:indices' ] = data[ 'int[] primvars:st:indices' ];
  196. }
  197. return object;
  198. }
  199. if ( typeof object === 'object' ) {
  200. const geometry = findGeometry( object );
  201. if ( geometry ) return geometry;
  202. }
  203. }
  204. }
  205. function buildGeometry( data ) {
  206. if ( ! data ) return undefined;
  207. let geometry = new BufferGeometry();
  208. if ( 'int[] faceVertexIndices' in data ) {
  209. const indices = JSON.parse( data[ 'int[] faceVertexIndices' ] );
  210. geometry.setIndex( indices );
  211. }
  212. if ( 'point3f[] points' in data ) {
  213. const positions = JSON.parse( data[ 'point3f[] points' ].replace( /[()]*/g, '' ) );
  214. const attribute = new BufferAttribute( new Float32Array( positions ), 3 );
  215. geometry.setAttribute( 'position', attribute );
  216. }
  217. if ( 'normal3f[] normals' in data ) {
  218. const normals = JSON.parse( data[ 'normal3f[] normals' ].replace( /[()]*/g, '' ) );
  219. const attribute = new BufferAttribute( new Float32Array( normals ), 3 );
  220. geometry.setAttribute( 'normal', attribute );
  221. } else {
  222. geometry.computeVertexNormals();
  223. }
  224. if ( 'float2[] primvars:st' in data ) {
  225. data[ 'texCoord2f[] primvars:st' ] = data[ 'float2[] primvars:st' ];
  226. }
  227. if ( 'texCoord2f[] primvars:st' in data ) {
  228. const uvs = JSON.parse( data[ 'texCoord2f[] primvars:st' ].replace( /[()]*/g, '' ) );
  229. const attribute = new BufferAttribute( new Float32Array( uvs ), 2 );
  230. if ( 'int[] primvars:st:indices' in data ) {
  231. geometry = geometry.toNonIndexed();
  232. const indices = JSON.parse( data[ 'int[] primvars:st:indices' ] );
  233. geometry.setAttribute( 'uv', toFlatBufferAttribute( attribute, indices ) );
  234. } else {
  235. geometry.setAttribute( 'uv', attribute );
  236. }
  237. }
  238. return geometry;
  239. }
  240. function toFlatBufferAttribute( attribute, indices ) {
  241. const array = attribute.array;
  242. const itemSize = attribute.itemSize;
  243. const array2 = new array.constructor( indices.length * itemSize );
  244. let index = 0, index2 = 0;
  245. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  246. index = indices[ i ] * itemSize;
  247. for ( let j = 0; j < itemSize; j ++ ) {
  248. array2[ index2 ++ ] = array[ index ++ ];
  249. }
  250. }
  251. return new BufferAttribute( array2, itemSize );
  252. }
  253. function findMeshMaterial( data ) {
  254. if ( ! data ) return undefined;
  255. if ( 'rel material:binding' in data ) {
  256. const reference = data[ 'rel material:binding' ];
  257. const id = reference.replace( /^<\//, '' ).replace( />$/, '' );
  258. const parts = id.split( '/' );
  259. return findMaterial( root, ` "${ parts[ 1 ] }"` );
  260. }
  261. return findMaterial( data );
  262. }
  263. function findMaterial( data, id = '' ) {
  264. for ( const name in data ) {
  265. const object = data[ name ];
  266. if ( name.startsWith( 'def Material' + id ) ) {
  267. return object;
  268. }
  269. if ( typeof object === 'object' ) {
  270. const material = findMaterial( object, id );
  271. if ( material ) return material;
  272. }
  273. }
  274. }
  275. function setTextureParams( map, data_value ) {
  276. // rotation, scale and translation
  277. if ( data_value[ 'float inputs:rotation' ] ) {
  278. map.rotation = parseFloat( data_value[ 'float inputs:rotation' ] );
  279. }
  280. if ( data_value[ 'float2 inputs:scale' ] ) {
  281. map.repeat = new Vector2().fromArray( JSON.parse( '[' + data_value[ 'float2 inputs:scale' ].replace( /[()]*/g, '' ) + ']' ) );
  282. }
  283. if ( data_value[ 'float2 inputs:translation' ] ) {
  284. map.offset = new Vector2().fromArray( JSON.parse( '[' + data_value[ 'float2 inputs:translation' ].replace( /[()]*/g, '' ) + ']' ) );
  285. }
  286. }
  287. function buildMaterial( data ) {
  288. const material = new MeshPhysicalMaterial();
  289. if ( data !== undefined ) {
  290. if ( 'def Shader "PreviewSurface"' in data ) {
  291. const surface = data[ 'def Shader "PreviewSurface"' ];
  292. if ( 'color3f inputs:diffuseColor.connect' in surface ) {
  293. const path = surface[ 'color3f inputs:diffuseColor.connect' ];
  294. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  295. material.map = buildTexture( sampler );
  296. material.map.colorSpace = SRGBColorSpace;
  297. if ( 'def Shader "Transform2d_diffuse"' in data ) {
  298. setTextureParams( material.map, data[ 'def Shader "Transform2d_diffuse"' ] );
  299. }
  300. } else if ( 'color3f inputs:diffuseColor' in surface ) {
  301. const color = surface[ 'color3f inputs:diffuseColor' ].replace( /[()]*/g, '' );
  302. material.color.fromArray( JSON.parse( '[' + color + ']' ) );
  303. }
  304. if ( 'color3f inputs:emissiveColor.connect' in surface ) {
  305. const path = surface[ 'color3f inputs:emissiveColor.connect' ];
  306. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  307. material.emissiveMap = buildTexture( sampler );
  308. material.emissiveMap.colorSpace = SRGBColorSpace;
  309. material.emissive.set( 0xffffff );
  310. if ( 'def Shader "Transform2d_emissive"' in data ) {
  311. setTextureParams( material.emissiveMap, data[ 'def Shader "Transform2d_emissive"' ] );
  312. }
  313. } else if ( 'color3f inputs:emissiveColor' in surface ) {
  314. const color = surface[ 'color3f inputs:emissiveColor' ].replace( /[()]*/g, '' );
  315. material.emissive.fromArray( JSON.parse( '[' + color + ']' ) );
  316. }
  317. if ( 'normal3f inputs:normal.connect' in surface ) {
  318. const path = surface[ 'normal3f inputs:normal.connect' ];
  319. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  320. material.normalMap = buildTexture( sampler );
  321. material.normalMap.colorSpace = NoColorSpace;
  322. if ( 'def Shader "Transform2d_normal"' in data ) {
  323. setTextureParams( material.normalMap, data[ 'def Shader "Transform2d_normal"' ] );
  324. }
  325. }
  326. if ( 'float inputs:roughness.connect' in surface ) {
  327. const path = surface[ 'float inputs:roughness.connect' ];
  328. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  329. material.roughness = 1.0;
  330. material.roughnessMap = buildTexture( sampler );
  331. material.roughnessMap.colorSpace = NoColorSpace;
  332. if ( 'def Shader "Transform2d_roughness"' in data ) {
  333. setTextureParams( material.roughnessMap, data[ 'def Shader "Transform2d_roughness"' ] );
  334. }
  335. } else if ( 'float inputs:roughness' in surface ) {
  336. material.roughness = parseFloat( surface[ 'float inputs:roughness' ] );
  337. }
  338. if ( 'float inputs:metallic.connect' in surface ) {
  339. const path = surface[ 'float inputs:metallic.connect' ];
  340. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  341. material.metalness = 1.0;
  342. material.metalnessMap = buildTexture( sampler );
  343. material.metalnessMap.colorSpace = NoColorSpace;
  344. if ( 'def Shader "Transform2d_metallic"' in data ) {
  345. setTextureParams( material.metalnessMap, data[ 'def Shader "Transform2d_metallic"' ] );
  346. }
  347. } else if ( 'float inputs:metallic' in surface ) {
  348. material.metalness = parseFloat( surface[ 'float inputs:metallic' ] );
  349. }
  350. if ( 'float inputs:clearcoat.connect' in surface ) {
  351. const path = surface[ 'float inputs:clearcoat.connect' ];
  352. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  353. material.clearcoat = 1.0;
  354. material.clearcoatMap = buildTexture( sampler );
  355. material.clearcoatMap.colorSpace = NoColorSpace;
  356. if ( 'def Shader "Transform2d_clearcoat"' in data ) {
  357. setTextureParams( material.clearcoatMap, data[ 'def Shader "Transform2d_clearcoat"' ] );
  358. }
  359. } else if ( 'float inputs:clearcoat' in surface ) {
  360. material.clearcoat = parseFloat( surface[ 'float inputs:clearcoat' ] );
  361. }
  362. if ( 'float inputs:clearcoatRoughness.connect' in surface ) {
  363. const path = surface[ 'float inputs:clearcoatRoughness.connect' ];
  364. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  365. material.clearcoatRoughness = 1.0;
  366. material.clearcoatRoughnessMap = buildTexture( sampler );
  367. material.clearcoatRoughnessMap.colorSpace = NoColorSpace;
  368. if ( 'def Shader "Transform2d_clearcoatRoughness"' in data ) {
  369. setTextureParams( material.clearcoatRoughnessMap, data[ 'def Shader "Transform2d_clearcoatRoughness"' ] );
  370. }
  371. } else if ( 'float inputs:clearcoatRoughness' in surface ) {
  372. material.clearcoatRoughness = parseFloat( surface[ 'float inputs:clearcoatRoughness' ] );
  373. }
  374. if ( 'float inputs:ior' in surface ) {
  375. material.ior = parseFloat( surface[ 'float inputs:ior' ] );
  376. }
  377. if ( 'float inputs:occlusion.connect' in surface ) {
  378. const path = surface[ 'float inputs:occlusion.connect' ];
  379. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  380. material.aoMap = buildTexture( sampler );
  381. material.aoMap.colorSpace = NoColorSpace;
  382. if ( 'def Shader "Transform2d_occlusion"' in data ) {
  383. setTextureParams( material.aoMap, data[ 'def Shader "Transform2d_occlusion"' ] );
  384. }
  385. }
  386. }
  387. if ( 'def Shader "diffuseColor_texture"' in data ) {
  388. const sampler = data[ 'def Shader "diffuseColor_texture"' ];
  389. material.map = buildTexture( sampler );
  390. material.map.colorSpace = SRGBColorSpace;
  391. }
  392. if ( 'def Shader "normal_texture"' in data ) {
  393. const sampler = data[ 'def Shader "normal_texture"' ];
  394. material.normalMap = buildTexture( sampler );
  395. material.normalMap.colorSpace = NoColorSpace;
  396. }
  397. }
  398. return material;
  399. }
  400. function findTexture( data, id ) {
  401. for ( const name in data ) {
  402. const object = data[ name ];
  403. if ( name.startsWith( `def Shader "${ id }"` ) ) {
  404. return object;
  405. }
  406. if ( typeof object === 'object' ) {
  407. const texture = findTexture( object, id );
  408. if ( texture ) return texture;
  409. }
  410. }
  411. }
  412. function buildTexture( data ) {
  413. if ( 'asset inputs:file' in data ) {
  414. const path = data[ 'asset inputs:file' ].replace( /@*/g, '' );
  415. const loader = new TextureLoader();
  416. const texture = loader.load( assets[ path ] );
  417. const map = {
  418. '"clamp"': ClampToEdgeWrapping,
  419. '"mirror"': MirroredRepeatWrapping,
  420. '"repeat"': RepeatWrapping
  421. };
  422. if ( 'token inputs:wrapS' in data ) {
  423. texture.wrapS = map[ data[ 'token inputs:wrapS' ] ];
  424. }
  425. if ( 'token inputs:wrapT' in data ) {
  426. texture.wrapT = map[ data[ 'token inputs:wrapT' ] ];
  427. }
  428. return texture;
  429. }
  430. return null;
  431. }
  432. function buildObject( data ) {
  433. const geometry = buildGeometry( findMeshGeometry( data ) );
  434. const material = buildMaterial( findMeshMaterial( data ) );
  435. const mesh = geometry ? new Mesh( geometry, material ) : new Object3D();
  436. if ( 'matrix4d xformOp:transform' in data ) {
  437. const array = JSON.parse( '[' + data[ 'matrix4d xformOp:transform' ].replace( /[()]*/g, '' ) + ']' );
  438. mesh.matrix.fromArray( array );
  439. mesh.matrix.decompose( mesh.position, mesh.quaternion, mesh.scale );
  440. }
  441. return mesh;
  442. }
  443. function buildHierarchy( data, group ) {
  444. for ( const name in data ) {
  445. if ( name.startsWith( 'def Scope' ) ) {
  446. buildHierarchy( data[ name ], group );
  447. } else if ( name.startsWith( 'def Xform' ) ) {
  448. const mesh = buildObject( data[ name ] );
  449. if ( /def Xform "(\w+)"/.test( name ) ) {
  450. mesh.name = /def Xform "(\w+)"/.exec( name )[ 1 ];
  451. }
  452. group.add( mesh );
  453. buildHierarchy( data[ name ], mesh );
  454. }
  455. }
  456. }
  457. const group = new Group();
  458. buildHierarchy( root, group );
  459. return group;
  460. }
  461. }
  462. export { USDZLoader };