USDZExporter.js 14 KB

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