USDZExporter.js 9.9 KB

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