USDZExporter.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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.traverse( object => {
  11. if ( object.isMesh ) {
  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. if ( material.map !== null ) textures[ material.map.uuid ] = material.map;
  22. if ( material.normalMap !== null ) textures[ material.normalMap.uuid ] = material.normalMap;
  23. if ( material.aoMap !== null ) textures[ material.aoMap.uuid ] = material.aoMap;
  24. if ( material.roughnessMap !== null ) textures[ material.roughnessMap.uuid ] = material.roughnessMap;
  25. if ( material.metalnessMap !== null ) textures[ material.metalnessMap.uuid ] = material.metalnessMap;
  26. if ( material.emissiveMap !== null ) textures[ material.emissiveMap.uuid ] = material.emissiveMap;
  27. }
  28. const referencedMesh = `prepend references = @./${geometryFileName}@</Geometry>`;
  29. const referencedMaterial = `rel material:binding = </Materials/Material_${material.id}>`;
  30. output += buildXform( object, referencedMesh, referencedMaterial );
  31. }
  32. } );
  33. output += buildMaterials( materials );
  34. output += buildTextures( textures );
  35. files[ modelFileName ] = fflate.strToU8( output );
  36. output = null;
  37. for ( const uuid in textures ) {
  38. const texture = textures[ uuid ];
  39. files[ 'textures/Texture_' + texture.id + '.jpg' ] = await imgToU8( texture.image );
  40. } // 64 byte alignment
  41. // https://github.com/101arrowz/fflate/issues/39#issuecomment-777263109
  42. let offset = 0;
  43. for ( const filename in files ) {
  44. const file = files[ filename ];
  45. const headerSize = 34 + filename.length;
  46. offset += headerSize;
  47. const offsetMod64 = offset & 63;
  48. if ( offsetMod64 !== 4 ) {
  49. const padLength = 64 - offsetMod64;
  50. const padding = new Uint8Array( padLength );
  51. files[ filename ] = [ file, {
  52. extra: {
  53. 12345: padding
  54. }
  55. } ];
  56. }
  57. offset = file.length;
  58. }
  59. return fflate.zipSync( files, {
  60. level: 0
  61. } );
  62. }
  63. }
  64. async function imgToU8( image ) {
  65. 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 ) {
  66. const scale = 1024 / Math.max( image.width, image.height );
  67. const canvas = document.createElement( 'canvas' );
  68. canvas.width = image.width * Math.min( 1, scale );
  69. canvas.height = image.height * Math.min( 1, scale );
  70. const context = canvas.getContext( '2d' );
  71. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  72. const blob = await new Promise( resolve => canvas.toBlob( resolve, 'image/jpeg', 1 ) );
  73. return new Uint8Array( await blob.arrayBuffer() );
  74. }
  75. } //
  76. const PRECISION = 7;
  77. function buildHeader() {
  78. return `#usda 1.0
  79. (
  80. customLayerData = {
  81. string creator = "Three.js USDZExporter"
  82. }
  83. metersPerUnit = 1
  84. upAxis = "Y"
  85. )
  86. `;
  87. }
  88. function buildUSDFileAsString( dataToInsert ) {
  89. let output = buildHeader();
  90. output += dataToInsert;
  91. return fflate.strToU8( output );
  92. } // Xform
  93. function buildXform( object, referencedMesh, referencedMaterial ) {
  94. const name = 'Object_' + object.id;
  95. const transform = buildMatrix( object.matrixWorld );
  96. return `def Xform "${name}"
  97. (
  98. ${referencedMesh}
  99. )
  100. {
  101. matrix4d xformOp:transform = ${transform}
  102. uniform token[] xformOpOrder = ["xformOp:transform"]
  103. ${referencedMaterial}
  104. }
  105. `;
  106. }
  107. function buildMatrix( matrix ) {
  108. const array = matrix.elements;
  109. return `( ${buildMatrixRow( array, 0 )}, ${buildMatrixRow( array, 4 )}, ${buildMatrixRow( array, 8 )}, ${buildMatrixRow( array, 12 )} )`;
  110. }
  111. function buildMatrixRow( array, offset ) {
  112. return `(${array[ offset + 0 ]}, ${array[ offset + 1 ]}, ${array[ offset + 2 ]}, ${array[ offset + 3 ]})`;
  113. } // Mesh
  114. function buildMeshObject( geometry ) {
  115. const mesh = buildMesh( geometry );
  116. return `
  117. def "Geometry"
  118. {
  119. ${mesh}
  120. }
  121. `;
  122. }
  123. function buildMesh( geometry ) {
  124. const name = 'Geometry';
  125. const attributes = geometry.attributes;
  126. const count = attributes.position.count;
  127. if ( 'uv2' in attributes ) {
  128. console.warn( 'THREE.USDZExporter: uv2 not supported yet.' );
  129. }
  130. return `
  131. def Mesh "${name}"
  132. {
  133. int[] faceVertexCounts = [${buildMeshVertexCount( geometry )}]
  134. int[] faceVertexIndices = [${buildMeshVertexIndices( geometry )}]
  135. normal3f[] normals = [${buildVector3Array( attributes.normal, count )}] (
  136. interpolation = "vertex"
  137. )
  138. point3f[] points = [${buildVector3Array( attributes.position, count )}]
  139. float2[] primvars:st = [${buildVector2Array( attributes.uv, count )}] (
  140. interpolation = "vertex"
  141. )
  142. uniform token subdivisionScheme = "none"
  143. }
  144. `;
  145. }
  146. function buildMeshVertexCount( geometry ) {
  147. const count = geometry.index !== null ? geometry.index.array.length : geometry.attributes.position.count;
  148. return Array( count / 3 ).fill( 3 ).join( ', ' );
  149. }
  150. function buildMeshVertexIndices( geometry ) {
  151. if ( geometry.index !== null ) {
  152. return geometry.index.array.join( ', ' );
  153. }
  154. const array = [];
  155. const length = geometry.attributes.position.count;
  156. for ( let i = 0; i < length; i ++ ) {
  157. array.push( i );
  158. }
  159. return array.join( ', ' );
  160. }
  161. function buildVector3Array( attribute, count ) {
  162. if ( attribute === undefined ) {
  163. console.warn( 'USDZExporter: Normals missing.' );
  164. return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
  165. }
  166. const array = [];
  167. const data = attribute.array;
  168. for ( let i = 0; i < data.length; i += 3 ) {
  169. array.push( `(${data[ i + 0 ].toPrecision( PRECISION )}, ${data[ i + 1 ].toPrecision( PRECISION )}, ${data[ i + 2 ].toPrecision( PRECISION )})` );
  170. }
  171. return array.join( ', ' );
  172. }
  173. function buildVector2Array( attribute, count ) {
  174. if ( attribute === undefined ) {
  175. console.warn( 'USDZExporter: UVs missing.' );
  176. return Array( count ).fill( '(0, 0)' ).join( ', ' );
  177. }
  178. const array = [];
  179. const data = attribute.array;
  180. for ( let i = 0; i < data.length; i += 2 ) {
  181. array.push( `(${data[ i + 0 ].toPrecision( PRECISION )}, ${1 - data[ i + 1 ].toPrecision( PRECISION )})` );
  182. }
  183. return array.join( ', ' );
  184. } // Materials
  185. function buildMaterials( materials ) {
  186. const array = [];
  187. for ( const uuid in materials ) {
  188. const material = materials[ uuid ];
  189. array.push( buildMaterial( material ) );
  190. }
  191. return `def "Materials"
  192. {
  193. ${array.join( '' )}
  194. }
  195. `;
  196. }
  197. function buildMaterial( material ) {
  198. // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
  199. const pad = ' ';
  200. const parameters = [];
  201. if ( material.map !== null ) {
  202. parameters.push( `${pad}color3f inputs:diffuseColor.connect = </Textures/Texture_${material.map.id}.outputs:rgb>` );
  203. } else {
  204. parameters.push( `${pad}color3f inputs:diffuseColor = ${buildColor( material.color )}` );
  205. }
  206. if ( material.emissiveMap !== null ) {
  207. parameters.push( `${pad}color3f inputs:emissiveColor.connect = </Textures/Texture_${material.emissiveMap.id}.outputs:rgb>` );
  208. } else if ( material.emissive.getHex() > 0 ) {
  209. parameters.push( `${pad}color3f inputs:emissiveColor = ${buildColor( material.emissive )}` );
  210. }
  211. if ( material.normalMap !== null ) {
  212. parameters.push( `${pad}normal3f inputs:normal.connect = </Textures/Texture_${material.normalMap.id}.outputs:rgb>` );
  213. }
  214. if ( material.aoMap !== null ) {
  215. parameters.push( `${pad}float inputs:occlusion.connect = </Textures/Texture_${material.aoMap.id}.outputs:r>` );
  216. }
  217. if ( material.roughnessMap !== null ) {
  218. parameters.push( `${pad}float inputs:roughness.connect = </Textures/Texture_${material.roughnessMap.id}.outputs:g>` );
  219. } else {
  220. parameters.push( `${pad}float inputs:roughness = ${material.roughness}` );
  221. }
  222. if ( material.metalnessMap !== null ) {
  223. parameters.push( `${pad}float inputs:metallic.connect = </Textures/Texture_${material.metalnessMap.id}.outputs:b>` );
  224. } else {
  225. parameters.push( `${pad}float inputs:metallic = ${material.metalness}` );
  226. }
  227. parameters.push( `${pad}float inputs:opacity = ${material.opacity}` );
  228. return `
  229. def Material "Material_${material.id}"
  230. {
  231. token outputs:surface.connect = </Materials/Material_${material.id}/PreviewSurface.outputs:surface>
  232. def Shader "PreviewSurface"
  233. {
  234. uniform token info:id = "UsdPreviewSurface"
  235. ${parameters.join( '\n' )}
  236. int inputs:useSpecularWorkflow = 0
  237. token outputs:surface
  238. }
  239. }
  240. `;
  241. }
  242. function buildTextures( textures ) {
  243. const array = [];
  244. for ( const uuid in textures ) {
  245. const texture = textures[ uuid ];
  246. array.push( buildTexture( texture ) );
  247. }
  248. return `def "Textures"
  249. {
  250. ${array.join( '' )}
  251. }
  252. `;
  253. }
  254. function buildTexture( texture ) {
  255. return `
  256. def Shader "Texture_${texture.id}"
  257. {
  258. uniform token info:id = "UsdUVTexture"
  259. asset inputs:file = @textures/Texture_${texture.id}.jpg@
  260. token inputs:wrapS = "repeat"
  261. token inputs:wrapT = "repeat"
  262. float outputs:r
  263. float outputs:g
  264. float outputs:b
  265. float3 outputs:rgb
  266. }
  267. `;
  268. }
  269. function buildColor( color ) {
  270. return `(${color.r}, ${color.g}, ${color.b})`;
  271. }
  272. THREE.USDZExporter = USDZExporter;
  273. } )();