USDZExporter.js 16 KB

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