USDZExporter.js 17 KB

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