USDZExporter.js 17 KB

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