USDZExporter.js 13 KB

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