USDZExporter.js 11 KB

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