USDZLoader.js 19 KB

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