USDZExporter.js 17 KB

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