USDZExporter.js 16 KB

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