USDZExporter.js 21 KB

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