USDZExporter.js 12 KB

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