USDAParser.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  1. import {
  2. BufferAttribute,
  3. BufferGeometry,
  4. ClampToEdgeWrapping,
  5. Group,
  6. NoColorSpace,
  7. Mesh,
  8. MeshPhysicalMaterial,
  9. MirroredRepeatWrapping,
  10. RepeatWrapping,
  11. SRGBColorSpace,
  12. TextureLoader,
  13. Object3D,
  14. Vector2
  15. } from 'three';
  16. class USDAParser {
  17. parseText( text ) {
  18. const root = {};
  19. const lines = text.split( '\n' );
  20. let string = null;
  21. let target = root;
  22. const stack = [ root ];
  23. // Parse USDA file
  24. for ( const line of lines ) {
  25. // console.log( line );
  26. if ( line.includes( '=' ) ) {
  27. const assignment = line.split( '=' );
  28. const lhs = assignment[ 0 ].trim();
  29. const rhs = assignment[ 1 ].trim();
  30. if ( rhs.endsWith( '{' ) ) {
  31. const group = {};
  32. stack.push( group );
  33. target[ lhs ] = group;
  34. target = group;
  35. } else if ( rhs.endsWith( '(' ) ) {
  36. // see #28631
  37. const values = rhs.slice( 0, - 1 );
  38. target[ lhs ] = values;
  39. const meta = {};
  40. stack.push( meta );
  41. target = meta;
  42. } else {
  43. target[ lhs ] = rhs;
  44. }
  45. } else if ( line.endsWith( '{' ) ) {
  46. const group = target[ string ] || {};
  47. stack.push( group );
  48. target[ string ] = group;
  49. target = group;
  50. } else if ( line.endsWith( '}' ) ) {
  51. stack.pop();
  52. if ( stack.length === 0 ) continue;
  53. target = stack[ stack.length - 1 ];
  54. } else if ( line.endsWith( '(' ) ) {
  55. const meta = {};
  56. stack.push( meta );
  57. string = line.split( '(' )[ 0 ].trim() || string;
  58. target[ string ] = meta;
  59. target = meta;
  60. } else if ( line.endsWith( ')' ) ) {
  61. stack.pop();
  62. target = stack[ stack.length - 1 ];
  63. } else {
  64. string = line.trim();
  65. }
  66. }
  67. return root;
  68. }
  69. parse( text, assets ) {
  70. const root = this.parseText( text );
  71. // Build scene graph
  72. function findMeshGeometry( data ) {
  73. if ( ! data ) return undefined;
  74. if ( 'prepend references' in data ) {
  75. const reference = data[ 'prepend references' ];
  76. const parts = reference.split( '@' );
  77. const path = parts[ 1 ].replace( /^.\//, '' );
  78. const id = parts[ 2 ].replace( /^<\//, '' ).replace( />$/, '' );
  79. return findGeometry( assets[ path ], id );
  80. }
  81. return findGeometry( data );
  82. }
  83. function findGeometry( data, id ) {
  84. if ( ! data ) return undefined;
  85. if ( id !== undefined ) {
  86. const def = `def Mesh "${id}"`;
  87. if ( def in data ) {
  88. return data[ def ];
  89. }
  90. }
  91. for ( const name in data ) {
  92. const object = data[ name ];
  93. if ( name.startsWith( 'def Mesh' ) ) {
  94. return object;
  95. }
  96. if ( typeof object === 'object' ) {
  97. const geometry = findGeometry( object );
  98. if ( geometry ) return geometry;
  99. }
  100. }
  101. }
  102. function buildGeometry( data ) {
  103. if ( ! data ) return undefined;
  104. const geometry = new BufferGeometry();
  105. let indices = null;
  106. let counts = null;
  107. let uvs = null;
  108. let positionsLength = - 1;
  109. // index
  110. if ( 'int[] faceVertexIndices' in data ) {
  111. indices = JSON.parse( data[ 'int[] faceVertexIndices' ] );
  112. }
  113. // face count
  114. if ( 'int[] faceVertexCounts' in data ) {
  115. counts = JSON.parse( data[ 'int[] faceVertexCounts' ] );
  116. indices = toTriangleIndices( indices, counts );
  117. }
  118. // position
  119. if ( 'point3f[] points' in data ) {
  120. const positions = JSON.parse( data[ 'point3f[] points' ].replace( /[()]*/g, '' ) );
  121. positionsLength = positions.length;
  122. let attribute = new BufferAttribute( new Float32Array( positions ), 3 );
  123. if ( indices !== null ) attribute = toFlatBufferAttribute( attribute, indices );
  124. geometry.setAttribute( 'position', attribute );
  125. }
  126. // uv
  127. if ( 'float2[] primvars:st' in data ) {
  128. data[ 'texCoord2f[] primvars:st' ] = data[ 'float2[] primvars:st' ];
  129. }
  130. if ( 'texCoord2f[] primvars:st' in data ) {
  131. uvs = JSON.parse( data[ 'texCoord2f[] primvars:st' ].replace( /[()]*/g, '' ) );
  132. let attribute = new BufferAttribute( new Float32Array( uvs ), 2 );
  133. if ( indices !== null ) attribute = toFlatBufferAttribute( attribute, indices );
  134. geometry.setAttribute( 'uv', attribute );
  135. }
  136. if ( 'int[] primvars:st:indices' in data && uvs !== null ) {
  137. // custom uv index, overwrite uvs with new data
  138. const attribute = new BufferAttribute( new Float32Array( uvs ), 2 );
  139. let indices = JSON.parse( data[ 'int[] primvars:st:indices' ] );
  140. indices = toTriangleIndices( indices, counts );
  141. geometry.setAttribute( 'uv', toFlatBufferAttribute( attribute, indices ) );
  142. }
  143. // normal
  144. if ( 'normal3f[] normals' in data ) {
  145. const normals = JSON.parse( data[ 'normal3f[] normals' ].replace( /[()]*/g, '' ) );
  146. let attribute = new BufferAttribute( new Float32Array( normals ), 3 );
  147. // normals require a special treatment in USD
  148. if ( normals.length === positionsLength ) {
  149. // raw normal and position data have equal length (like produced by USDZExporter)
  150. if ( indices !== null ) attribute = toFlatBufferAttribute( attribute, indices );
  151. } else {
  152. // unequal length, normals are independent of faceVertexIndices
  153. let indices = Array.from( Array( normals.length / 3 ).keys() ); // [ 0, 1, 2, 3 ... ]
  154. indices = toTriangleIndices( indices, counts );
  155. attribute = toFlatBufferAttribute( attribute, indices );
  156. }
  157. geometry.setAttribute( 'normal', attribute );
  158. } else {
  159. // compute flat vertex normals
  160. geometry.computeVertexNormals();
  161. }
  162. return geometry;
  163. }
  164. function toTriangleIndices( rawIndices, counts ) {
  165. const indices = [];
  166. for ( let i = 0; i < counts.length; i ++ ) {
  167. const count = counts[ i ];
  168. const stride = i * count;
  169. if ( count === 3 ) {
  170. const a = rawIndices[ stride + 0 ];
  171. const b = rawIndices[ stride + 1 ];
  172. const c = rawIndices[ stride + 2 ];
  173. indices.push( a, b, c );
  174. } else if ( count === 4 ) {
  175. const a = rawIndices[ stride + 0 ];
  176. const b = rawIndices[ stride + 1 ];
  177. const c = rawIndices[ stride + 2 ];
  178. const d = rawIndices[ stride + 3 ];
  179. indices.push( a, b, c );
  180. indices.push( a, c, d );
  181. } else {
  182. console.warn( 'THREE.USDZLoader: Face vertex count of %s unsupported.', count );
  183. }
  184. }
  185. return indices;
  186. }
  187. function toFlatBufferAttribute( attribute, indices ) {
  188. const array = attribute.array;
  189. const itemSize = attribute.itemSize;
  190. const array2 = new array.constructor( indices.length * itemSize );
  191. let index = 0, index2 = 0;
  192. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  193. index = indices[ i ] * itemSize;
  194. for ( let j = 0; j < itemSize; j ++ ) {
  195. array2[ index2 ++ ] = array[ index ++ ];
  196. }
  197. }
  198. return new BufferAttribute( array2, itemSize );
  199. }
  200. function findMeshMaterial( data ) {
  201. if ( ! data ) return undefined;
  202. if ( 'rel material:binding' in data ) {
  203. const reference = data[ 'rel material:binding' ];
  204. const id = reference.replace( /^<\//, '' ).replace( />$/, '' );
  205. const parts = id.split( '/' );
  206. return findMaterial( root, ` "${ parts[ 1 ] }"` );
  207. }
  208. return findMaterial( data );
  209. }
  210. function findMaterial( data, id = '' ) {
  211. for ( const name in data ) {
  212. const object = data[ name ];
  213. if ( name.startsWith( 'def Material' + id ) ) {
  214. return object;
  215. }
  216. if ( typeof object === 'object' ) {
  217. const material = findMaterial( object, id );
  218. if ( material ) return material;
  219. }
  220. }
  221. }
  222. function setTextureParams( map, data_value ) {
  223. // rotation, scale and translation
  224. if ( data_value[ 'float inputs:rotation' ] ) {
  225. map.rotation = parseFloat( data_value[ 'float inputs:rotation' ] );
  226. }
  227. if ( data_value[ 'float2 inputs:scale' ] ) {
  228. map.repeat = new Vector2().fromArray( JSON.parse( '[' + data_value[ 'float2 inputs:scale' ].replace( /[()]*/g, '' ) + ']' ) );
  229. }
  230. if ( data_value[ 'float2 inputs:translation' ] ) {
  231. map.offset = new Vector2().fromArray( JSON.parse( '[' + data_value[ 'float2 inputs:translation' ].replace( /[()]*/g, '' ) + ']' ) );
  232. }
  233. }
  234. function buildMaterial( data ) {
  235. const material = new MeshPhysicalMaterial();
  236. if ( data !== undefined ) {
  237. let surface = undefined;
  238. const surfaceConnection = data[ 'token outputs:surface.connect' ];
  239. if ( surfaceConnection ) {
  240. const match = /(\w+)\.output/.exec( surfaceConnection );
  241. if ( match ) {
  242. const surfaceName = match[ 1 ];
  243. surface = data[ `def Shader "${surfaceName}"` ];
  244. }
  245. }
  246. if ( surface !== undefined ) {
  247. if ( 'color3f inputs:diffuseColor.connect' in surface ) {
  248. const path = surface[ 'color3f inputs:diffuseColor.connect' ];
  249. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  250. material.map = buildTexture( sampler );
  251. material.map.colorSpace = SRGBColorSpace;
  252. if ( 'def Shader "Transform2d_diffuse"' in data ) {
  253. setTextureParams( material.map, data[ 'def Shader "Transform2d_diffuse"' ] );
  254. }
  255. } else if ( 'color3f inputs:diffuseColor' in surface ) {
  256. const color = surface[ 'color3f inputs:diffuseColor' ].replace( /[()]*/g, '' );
  257. material.color.fromArray( JSON.parse( '[' + color + ']' ) );
  258. }
  259. if ( 'color3f inputs:emissiveColor.connect' in surface ) {
  260. const path = surface[ 'color3f inputs:emissiveColor.connect' ];
  261. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  262. material.emissiveMap = buildTexture( sampler );
  263. material.emissiveMap.colorSpace = SRGBColorSpace;
  264. material.emissive.set( 0xffffff );
  265. if ( 'def Shader "Transform2d_emissive"' in data ) {
  266. setTextureParams( material.emissiveMap, data[ 'def Shader "Transform2d_emissive"' ] );
  267. }
  268. } else if ( 'color3f inputs:emissiveColor' in surface ) {
  269. const color = surface[ 'color3f inputs:emissiveColor' ].replace( /[()]*/g, '' );
  270. material.emissive.fromArray( JSON.parse( '[' + color + ']' ) );
  271. }
  272. if ( 'normal3f inputs:normal.connect' in surface ) {
  273. const path = surface[ 'normal3f inputs:normal.connect' ];
  274. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  275. material.normalMap = buildTexture( sampler );
  276. material.normalMap.colorSpace = NoColorSpace;
  277. if ( 'def Shader "Transform2d_normal"' in data ) {
  278. setTextureParams( material.normalMap, data[ 'def Shader "Transform2d_normal"' ] );
  279. }
  280. }
  281. if ( 'float inputs:roughness.connect' in surface ) {
  282. const path = surface[ 'float inputs:roughness.connect' ];
  283. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  284. material.roughness = 1.0;
  285. material.roughnessMap = buildTexture( sampler );
  286. material.roughnessMap.colorSpace = NoColorSpace;
  287. if ( 'def Shader "Transform2d_roughness"' in data ) {
  288. setTextureParams( material.roughnessMap, data[ 'def Shader "Transform2d_roughness"' ] );
  289. }
  290. } else if ( 'float inputs:roughness' in surface ) {
  291. material.roughness = parseFloat( surface[ 'float inputs:roughness' ] );
  292. }
  293. if ( 'float inputs:metallic.connect' in surface ) {
  294. const path = surface[ 'float inputs:metallic.connect' ];
  295. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  296. material.metalness = 1.0;
  297. material.metalnessMap = buildTexture( sampler );
  298. material.metalnessMap.colorSpace = NoColorSpace;
  299. if ( 'def Shader "Transform2d_metallic"' in data ) {
  300. setTextureParams( material.metalnessMap, data[ 'def Shader "Transform2d_metallic"' ] );
  301. }
  302. } else if ( 'float inputs:metallic' in surface ) {
  303. material.metalness = parseFloat( surface[ 'float inputs:metallic' ] );
  304. }
  305. if ( 'float inputs:clearcoat.connect' in surface ) {
  306. const path = surface[ 'float inputs:clearcoat.connect' ];
  307. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  308. material.clearcoat = 1.0;
  309. material.clearcoatMap = buildTexture( sampler );
  310. material.clearcoatMap.colorSpace = NoColorSpace;
  311. if ( 'def Shader "Transform2d_clearcoat"' in data ) {
  312. setTextureParams( material.clearcoatMap, data[ 'def Shader "Transform2d_clearcoat"' ] );
  313. }
  314. } else if ( 'float inputs:clearcoat' in surface ) {
  315. material.clearcoat = parseFloat( surface[ 'float inputs:clearcoat' ] );
  316. }
  317. if ( 'float inputs:clearcoatRoughness.connect' in surface ) {
  318. const path = surface[ 'float inputs:clearcoatRoughness.connect' ];
  319. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  320. material.clearcoatRoughness = 1.0;
  321. material.clearcoatRoughnessMap = buildTexture( sampler );
  322. material.clearcoatRoughnessMap.colorSpace = NoColorSpace;
  323. if ( 'def Shader "Transform2d_clearcoatRoughness"' in data ) {
  324. setTextureParams( material.clearcoatRoughnessMap, data[ 'def Shader "Transform2d_clearcoatRoughness"' ] );
  325. }
  326. } else if ( 'float inputs:clearcoatRoughness' in surface ) {
  327. material.clearcoatRoughness = parseFloat( surface[ 'float inputs:clearcoatRoughness' ] );
  328. }
  329. if ( 'float inputs:ior' in surface ) {
  330. material.ior = parseFloat( surface[ 'float inputs:ior' ] );
  331. }
  332. if ( 'float inputs:occlusion.connect' in surface ) {
  333. const path = surface[ 'float inputs:occlusion.connect' ];
  334. const sampler = findTexture( root, /(\w+).output/.exec( path )[ 1 ] );
  335. material.aoMap = buildTexture( sampler );
  336. material.aoMap.colorSpace = NoColorSpace;
  337. if ( 'def Shader "Transform2d_occlusion"' in data ) {
  338. setTextureParams( material.aoMap, data[ 'def Shader "Transform2d_occlusion"' ] );
  339. }
  340. }
  341. }
  342. }
  343. return material;
  344. }
  345. function findTexture( data, id ) {
  346. for ( const name in data ) {
  347. const object = data[ name ];
  348. if ( name.startsWith( `def Shader "${ id }"` ) ) {
  349. return object;
  350. }
  351. if ( typeof object === 'object' ) {
  352. const texture = findTexture( object, id );
  353. if ( texture ) return texture;
  354. }
  355. }
  356. }
  357. function buildTexture( data ) {
  358. if ( 'asset inputs:file' in data ) {
  359. const path = data[ 'asset inputs:file' ].replace( /@*/g, '' ).trim();
  360. const loader = new TextureLoader();
  361. const texture = loader.load( assets[ path ] );
  362. const map = {
  363. '"clamp"': ClampToEdgeWrapping,
  364. '"mirror"': MirroredRepeatWrapping,
  365. '"repeat"': RepeatWrapping
  366. };
  367. if ( 'token inputs:wrapS' in data ) {
  368. texture.wrapS = map[ data[ 'token inputs:wrapS' ] ];
  369. }
  370. if ( 'token inputs:wrapT' in data ) {
  371. texture.wrapT = map[ data[ 'token inputs:wrapT' ] ];
  372. }
  373. return texture;
  374. }
  375. return null;
  376. }
  377. function buildObject( data ) {
  378. const geometry = buildGeometry( findMeshGeometry( data ) );
  379. const material = buildMaterial( findMeshMaterial( data ) );
  380. const mesh = geometry ? new Mesh( geometry, material ) : new Object3D();
  381. if ( 'matrix4d xformOp:transform' in data ) {
  382. const array = JSON.parse( '[' + data[ 'matrix4d xformOp:transform' ].replace( /[()]*/g, '' ) + ']' );
  383. mesh.matrix.fromArray( array );
  384. mesh.matrix.decompose( mesh.position, mesh.quaternion, mesh.scale );
  385. }
  386. return mesh;
  387. }
  388. function buildHierarchy( data, group ) {
  389. for ( const name in data ) {
  390. if ( name.startsWith( 'def Scope' ) ) {
  391. buildHierarchy( data[ name ], group );
  392. } else if ( name.startsWith( 'def Xform' ) ) {
  393. const mesh = buildObject( data[ name ] );
  394. if ( /def Xform "(\w+)"/.test( name ) ) {
  395. mesh.name = /def Xform "(\w+)"/.exec( name )[ 1 ];
  396. }
  397. group.add( mesh );
  398. buildHierarchy( data[ name ], mesh );
  399. }
  400. }
  401. }
  402. function buildGroup( data ) {
  403. const group = new Group();
  404. buildHierarchy( data, group );
  405. return group;
  406. }
  407. return buildGroup( root );
  408. }
  409. }
  410. export { USDAParser };
粤ICP备19079148号