USDZExporter.js 12 KB

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