USDZExporter.js 11 KB

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