USDZExporter.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import { zipSync, strToU8 } from '../libs/fflate.module.min.js';
  2. class USDZExporter {
  3. async parse( scene ) {
  4. let output = buildHeader();
  5. const materials = {};
  6. const textures = {};
  7. scene.traverse( ( object ) => {
  8. if ( object.isMesh ) {
  9. const geometry = object.geometry;
  10. const material = object.material;
  11. materials[ material.uuid ] = material;
  12. if ( material.map !== null ) textures[ material.map.uuid ] = material.map;
  13. if ( material.normalMap !== null ) textures[ material.normalMap.uuid ] = material.normalMap;
  14. if ( material.aoMap !== null ) textures[ material.aoMap.uuid ] = material.aoMap;
  15. if ( material.roughnessMap !== null ) textures[ material.roughnessMap.uuid ] = material.roughnessMap;
  16. if ( material.metalnessMap !== null ) textures[ material.metalnessMap.uuid ] = material.metalnessMap;
  17. if ( material.emissiveMap !== null ) textures[ material.emissiveMap.uuid ] = material.emissiveMap;
  18. output += buildXform( object, buildMesh( geometry, material ) );
  19. }
  20. } );
  21. output += buildMaterials( materials );
  22. output += buildTextures( textures );
  23. const files = { 'model.usda': strToU8( output ) };
  24. for ( const uuid in textures ) {
  25. const texture = textures[ uuid ];
  26. files[ 'textures/Texture_' + texture.id + '.jpg' ] = await imgToU8( texture.image );
  27. }
  28. // 64 byte alignment
  29. // https://github.com/101arrowz/fflate/issues/39#issuecomment-777263109
  30. let offset = 0;
  31. for ( const filename in files ) {
  32. const file = files[ filename ];
  33. const headerSize = 34 + filename.length;
  34. offset += headerSize;
  35. const offsetMod64 = offset & 63;
  36. if ( offsetMod64 !== 4 ) {
  37. const padLength = 64 - offsetMod64;
  38. const padding = new Uint8Array( padLength );
  39. files[ filename ] = [ file, { extra: { 12345: padding } } ];
  40. }
  41. offset = file.length;
  42. }
  43. return zipSync( files, { level: 0 } );
  44. }
  45. }
  46. async function imgToU8( image ) {
  47. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  48. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  49. ( typeof OffscreenCanvas !== 'undefined' && image instanceof OffscreenCanvas ) ||
  50. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  51. const scale = 1024 / Math.max( image.width, image.height );
  52. const canvas = document.createElement( 'canvas' );
  53. canvas.width = image.width * Math.min( 1, scale );
  54. canvas.height = image.height * Math.min( 1, scale );
  55. const context = canvas.getContext( '2d' );
  56. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  57. const blob = await new Promise( resolve => canvas.toBlob( resolve, 'image/jpeg', 1 ) );
  58. return new Uint8Array( await blob.arrayBuffer() );
  59. }
  60. }
  61. //
  62. const PRECISION = 7;
  63. function buildHeader() {
  64. return `#usda 1.0
  65. (
  66. customLayerData = {
  67. string creator = "Three.js USDZExporter"
  68. }
  69. metersPerUnit = 1
  70. upAxis = "Y"
  71. )
  72. `;
  73. }
  74. // Xform
  75. function buildXform( object, define ) {
  76. const name = 'Object_' + object.id;
  77. const transform = buildMatrix( object.matrixWorld );
  78. return `def Xform "${ name }"
  79. {
  80. matrix4d xformOp:transform = ${ transform }
  81. uniform token[] xformOpOrder = ["xformOp:transform"]
  82. ${ define }
  83. }
  84. `;
  85. }
  86. function buildMatrix( matrix ) {
  87. const array = matrix.elements;
  88. return `( ${ buildMatrixRow( array, 0 ) }, ${ buildMatrixRow( array, 4 ) }, ${ buildMatrixRow( array, 8 ) }, ${ buildMatrixRow( array, 12 ) } )`;
  89. }
  90. function buildMatrixRow( array, offset ) {
  91. return `(${ array[ offset + 0 ] }, ${ array[ offset + 1 ] }, ${ array[ offset + 2 ] }, ${ array[ offset + 3 ] })`;
  92. }
  93. // Mesh
  94. function buildMesh( geometry, material ) {
  95. const name = 'Geometry_' + geometry.id;
  96. const attributes = geometry.attributes;
  97. const count = attributes.position.count;
  98. if ( 'uv2' in attributes ) {
  99. console.warn( 'THREE.USDZExporter: uv2 not supported yet.' );
  100. }
  101. return `def Mesh "${ name }"
  102. {
  103. int[] faceVertexCounts = [${ buildMeshVertexCount( geometry ) }]
  104. int[] faceVertexIndices = [${ buildMeshVertexIndices( geometry ) }]
  105. rel material:binding = </Materials/Material_${ material.id }>
  106. normal3f[] normals = [${ buildVector3Array( attributes.normal, count )}] (
  107. interpolation = "vertex"
  108. )
  109. point3f[] points = [${ buildVector3Array( attributes.position, count )}]
  110. float2[] primvars:st = [${ buildVector2Array( attributes.uv, count )}] (
  111. interpolation = "vertex"
  112. )
  113. uniform token subdivisionScheme = "none"
  114. }
  115. `;
  116. }
  117. function buildMeshVertexCount( geometry ) {
  118. const count = geometry.index !== null ? geometry.index.array.length : geometry.attributes.position.count;
  119. return Array( count / 3 ).fill( 3 ).join( ', ' );
  120. }
  121. function buildMeshVertexIndices( geometry ) {
  122. if ( geometry.index !== null ) {
  123. return geometry.index.array.join( ', ' );
  124. }
  125. const array = [];
  126. const length = geometry.attributes.position.count;
  127. for ( let i = 0; i < length; i ++ ) {
  128. array.push( i );
  129. }
  130. return array.join( ', ' );
  131. }
  132. function buildVector3Array( attribute, count ) {
  133. if ( attribute === undefined ) {
  134. console.warn( 'USDZExporter: Normals missing.' );
  135. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  136. }
  137. const array = [];
  138. const data = attribute.array;
  139. for ( let i = 0; i < data.length; i += 3 ) {
  140. array.push( `(${ data[ i + 0 ].toPrecision( PRECISION ) }, ${ data[ i + 1 ].toPrecision( PRECISION ) }, ${ data[ i + 2 ].toPrecision( PRECISION ) })` );
  141. }
  142. return array.join( ', ' );
  143. }
  144. function buildVector2Array( attribute, count ) {
  145. if ( attribute === undefined ) {
  146. console.warn( 'USDZExporter: UVs missing.' );
  147. return Array( count ).fill( '(0, 0)' ).join( ', ' );
  148. }
  149. const array = [];
  150. const data = attribute.array;
  151. for ( let i = 0; i < data.length; i += 2 ) {
  152. array.push( `(${ data[ i + 0 ].toPrecision( PRECISION ) }, ${ 1 - data[ i + 1 ].toPrecision( PRECISION ) })` );
  153. }
  154. return array.join( ', ' );
  155. }
  156. // Materials
  157. function buildMaterials( materials ) {
  158. const array = [];
  159. for ( const uuid in materials ) {
  160. const material = materials[ uuid ];
  161. array.push( buildMaterial( material ) );
  162. }
  163. return `def "Materials"
  164. {
  165. ${ array.join( '' ) }
  166. }
  167. `;
  168. }
  169. function buildMaterial( material ) {
  170. // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
  171. const pad = ' ';
  172. const parameters = [];
  173. if ( material.map !== null ) {
  174. parameters.push( `${ pad }color3f inputs:diffuseColor.connect = </Textures/Texture_${ material.map.id }.outputs:rgb>` );
  175. } else {
  176. parameters.push( `${ pad }color3f inputs:diffuseColor = ${ buildColor( material.color ) }` );
  177. }
  178. if ( material.emissiveMap !== null ) {
  179. parameters.push( `${ pad }color3f inputs:emissiveColor.connect = </Textures/Texture_${ material.emissiveMap.id }.outputs:rgb>` );
  180. } else if ( material.emissive.getHex() > 0 ) {
  181. parameters.push( `${ pad }color3f inputs:emissiveColor = ${ buildColor( material.emissive ) }` );
  182. }
  183. if ( material.normalMap !== null ) {
  184. parameters.push( `${ pad }normal3f inputs:normal.connect = </Textures/Texture_${ material.normalMap.id }.outputs:rgb>` );
  185. }
  186. if ( material.aoMap !== null ) {
  187. parameters.push( `${ pad }float inputs:occlusion.connect = </Textures/Texture_${ material.aoMap.id }.outputs:r>` );
  188. }
  189. if ( material.roughnessMap !== null ) {
  190. parameters.push( `${ pad }float inputs:roughness.connect = </Textures/Texture_${ material.roughnessMap.id }.outputs:g>` );
  191. } else {
  192. parameters.push( `${ pad }float inputs:roughness = ${ material.roughness }` );
  193. }
  194. if ( material.metalnessMap !== null ) {
  195. parameters.push( `${ pad }float inputs:metallic.connect = </Textures/Texture_${ material.metalnessMap.id }.outputs:b>` );
  196. } else {
  197. parameters.push( `${ pad }float inputs:metallic = ${ material.metalness }` );
  198. }
  199. return `
  200. def Material "Material_${ material.id }"
  201. {
  202. token outputs:surface.connect = </Materials/Material_${ material.id }/PreviewSurface.outputs:surface>
  203. def Shader "PreviewSurface"
  204. {
  205. uniform token info:id = "UsdPreviewSurface"
  206. ${ parameters.join( '\n' ) }
  207. int inputs:useSpecularWorkflow = 0
  208. token outputs:surface
  209. }
  210. }
  211. `;
  212. }
  213. function buildTextures( textures ) {
  214. const array = [];
  215. for ( const uuid in textures ) {
  216. const texture = textures[ uuid ];
  217. array.push( buildTexture( texture ) );
  218. }
  219. return `def "Textures"
  220. {
  221. ${ array.join( '' ) }
  222. }
  223. `;
  224. }
  225. function buildTexture( texture ) {
  226. return `
  227. def Shader "Texture_${ texture.id }"
  228. {
  229. uniform token info:id = "UsdUVTexture"
  230. asset inputs:file = @textures/Texture_${ texture.id }.jpg@
  231. token inputs:wrapS = "repeat"
  232. token inputs:wrapT = "repeat"
  233. float outputs:r
  234. float outputs:g
  235. float outputs:b
  236. float3 outputs:rgb
  237. }
  238. `;
  239. }
  240. function buildColor( color ) {
  241. return `(${ color.r }, ${ color.g }, ${ color.b })`;
  242. }
  243. export { USDZExporter };