USDZExporter.js 12 KB

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