| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254 |
- import {
- NoColorSpace,
- DoubleSide,
- Color,
- } from 'three';
- import {
- strToU8,
- zipSync,
- } from '../libs/fflate.module.js';
- class USDNode {
- constructor( name, type = '', metadata = [], properties = [] ) {
- this.name = name;
- this.type = type;
- this.metadata = metadata;
- this.properties = properties;
- this.children = [];
- }
- addMetadata( key, value ) {
- this.metadata.push( { key, value } );
- }
- addProperty( property, metadata = [] ) {
- this.properties.push( { property, metadata } );
- }
- addChild( child ) {
- this.children.push( child );
- }
- toString( indent = 0 ) {
- const pad = '\t'.repeat( indent );
- const formattedMetadata = this.metadata.map( ( item ) => {
- const key = item.key;
- const value = item.value;
- if ( Array.isArray( value ) ) {
- const lines = [];
- lines.push( `${key} = {` );
- value.forEach( ( line ) => {
- lines.push( `${pad}\t\t${line}` );
- } );
- lines.push( `${pad}\t}` );
- return lines.join( '\n' );
- } else {
- return `${key} = ${value}`;
- }
- } );
- const meta = formattedMetadata.length
- ? ` (\n${formattedMetadata
- .map( ( l ) => `${pad}\t${l}` )
- .join( '\n' )}\n${pad})`
- : '';
- const properties = this.properties.map( ( l ) => {
- const property = l.property;
- const metadata = l.metadata.length
- ? ` (\n${l.metadata.map( ( m ) => `${pad}\t\t${m}` ).join( '\n' )}\n${pad}\t)`
- : '';
- return `${pad}\t${property}${metadata}`;
- } );
- const children = this.children.map( ( c ) => c.toString( indent + 1 ) );
- const bodyLines = [];
- if ( properties.length > 0 ) {
- bodyLines.push( ...properties );
- }
- if ( children.length > 0 ) {
- if ( properties.length > 0 ) {
- bodyLines.push( '' );
- }
- for ( let i = 0; i < children.length; i ++ ) {
- bodyLines.push( children[ i ] );
- if ( i < children.length - 1 ) {
- bodyLines.push( '' );
- }
- }
- }
- const bodyContent = bodyLines.join( '\n' );
- const type = this.type ? this.type + ' ' : '';
- return `${pad}def ${type}"${this.name}"${meta}\n${pad}{\n${bodyContent}\n${pad}}`;
- }
- }
- /**
- * An exporter for USDZ.
- *
- * ```js
- * const exporter = new USDZExporter();
- * const arraybuffer = await exporter.parseAsync( scene );
- * ```
- *
- * @three_import import { USDZExporter } from 'three/addons/exporters/USDZExporter.js';
- */
- class USDZExporter {
- /**
- * Constructs a new USDZ exporter.
- */
- constructor() {
- /**
- * A reference to a texture utils module.
- *
- * @type {?(WebGLTextureUtils|WebGPUTextureUtils)}
- * @default null
- */
- this.textureUtils = null;
- }
- /**
- * Sets the texture utils for this exporter. Only relevant when compressed textures have to be exported.
- *
- * Depending on whether you use {@link WebGLRenderer} or {@link WebGPURenderer}, you must inject the
- * corresponding texture utils {@link WebGLTextureUtils} or {@link WebGPUTextureUtils}.
- *
- * @param {WebGLTextureUtils|WebGPUTextureUtils} utils - The texture utils.
- */
- setTextureUtils( utils ) {
- this.textureUtils = utils;
- }
- /**
- * Parse the given 3D object and generates the USDZ output.
- *
- * @param {Object3D} scene - The 3D object to export.
- * @param {USDZExporter~OnDone} onDone - A callback function that is executed when the export has finished.
- * @param {USDZExporter~OnError} onError - A callback function that is executed when an error happens.
- * @param {USDZExporter~Options} options - The export options.
- */
- parse( scene, onDone, onError, options ) {
- this.parseAsync( scene, options ).then( onDone ).catch( onError );
- }
- /**
- * Async version of {@link USDZExporter#parse}.
- *
- * @async
- * @param {Object3D} scene - The 3D object to export.
- * @param {USDZExporter~Options} options - The export options.
- * @return {Promise<ArrayBuffer>} A Promise that resolved with the exported USDZ data.
- */
- async parseAsync( scene, options = {} ) {
- options = Object.assign(
- {
- ar: {
- anchoring: { type: 'plane' },
- planeAnchoring: { alignment: 'horizontal' },
- },
- includeAnchoringProperties: true,
- onlyVisible: true,
- quickLookCompatible: false,
- maxTextureSize: 1024,
- },
- options
- );
- const usedNames = new Set();
- const files = {};
- const modelFileName = 'model.usda';
- // model file should be first in USDZ archive so we init it here
- files[ modelFileName ] = null;
- const root = new USDNode( 'Root', 'Xform' );
- const scenesNode = new USDNode( 'Scenes', 'Scope' );
- scenesNode.addMetadata( 'kind', '"sceneLibrary"' );
- root.addChild( scenesNode );
- const sceneName = 'Scene';
- const sceneNode = new USDNode( sceneName, 'Xform' );
- sceneNode.addMetadata( 'customData', [
- 'bool preliminary_collidesWithEnvironment = 0',
- `string sceneName = "${sceneName}"`,
- ] );
- sceneNode.addMetadata( 'sceneName', `"${sceneName}"` );
- if ( options.includeAnchoringProperties ) {
- sceneNode.addProperty(
- `token preliminary:anchoring:type = "${options.ar.anchoring.type}"`
- );
- sceneNode.addProperty(
- `token preliminary:planeAnchoring:alignment = "${options.ar.planeAnchoring.alignment}"`
- );
- }
- scenesNode.addChild( sceneNode );
- let output;
- const materials = {};
- const textures = {};
- buildHierarchy( scene, sceneNode, materials, usedNames, files, options );
- const materialsNode = buildMaterials(
- materials,
- textures,
- options.quickLookCompatible
- );
- output =
- buildHeader() +
- '\n' +
- root.toString() +
- '\n\n' +
- materialsNode.toString();
- files[ modelFileName ] = strToU8( output );
- output = null;
- for ( const id in textures ) {
- let texture = textures[ id ];
- if ( texture.isCompressedTexture === true ) {
- if ( this.textureUtils === null ) {
- throw new Error(
- 'THREE.USDZExporter: setTextureUtils() must be called to process compressed textures.'
- );
- } else {
- texture = await this.textureUtils.decompress( texture );
- }
- }
- const canvas = imageToCanvas(
- texture.image,
- texture.flipY,
- options.maxTextureSize
- );
- const blob = await new Promise( ( resolve ) =>
- canvas.toBlob( resolve, 'image/png', 1 )
- );
- files[ `textures/Texture_${id}.png` ] = new Uint8Array(
- await blob.arrayBuffer()
- );
- }
- // 64 byte alignment
- // https://github.com/101arrowz/fflate/issues/39#issuecomment-777263109
- let offset = 0;
- for ( const filename in files ) {
- const file = files[ filename ];
- const headerSize = 34 + filename.length;
- offset += headerSize;
- const offsetMod64 = offset & 63;
- if ( offsetMod64 !== 4 ) {
- const padLength = 64 - offsetMod64;
- const padding = new Uint8Array( padLength );
- files[ filename ] = [ file, { extra: { 12345: padding } } ];
- }
- offset = file.length;
- }
- return zipSync( files, { level: 0 } );
- }
- }
- function getName( object, namesSet ) {
- let name = object.name;
- name = name.replace( /[^A-Za-z0-9_]/g, '' );
- if ( /^[0-9]/.test( name ) ) {
- name = '_' + name;
- }
- if ( name === '' ) {
- if ( object.isCamera ) {
- name = 'Camera';
- } else {
- name = 'Object';
- }
- }
- if ( namesSet.has( name ) ) {
- name = name + '_' + object.id;
- }
- namesSet.add( name );
- return name;
- }
- function imageToCanvas( image, flipY, maxTextureSize ) {
- if (
- ( typeof HTMLImageElement !== 'undefined' &&
- image instanceof HTMLImageElement ) ||
- ( typeof HTMLCanvasElement !== 'undefined' &&
- image instanceof HTMLCanvasElement ) ||
- ( typeof OffscreenCanvas !== 'undefined' &&
- image instanceof OffscreenCanvas ) ||
- ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap )
- ) {
- const scale = maxTextureSize / Math.max( image.width, image.height );
- const canvas = document.createElement( 'canvas' );
- canvas.width = image.width * Math.min( 1, scale );
- canvas.height = image.height * Math.min( 1, scale );
- const context = canvas.getContext( '2d' );
- // TODO: We should be able to do this in the UsdTransform2d?
- if ( flipY === true ) {
- context.translate( 0, canvas.height );
- context.scale( 1, - 1 );
- }
- context.drawImage( image, 0, 0, canvas.width, canvas.height );
- return canvas;
- } else {
- throw new Error(
- 'THREE.USDZExporter: No valid image data found. Unable to process texture.'
- );
- }
- }
- //
- const PRECISION = 7;
- function buildHeader() {
- return `#usda 1.0
- (
- customLayerData = {
- string creator = "Three.js USDZExporter"
- }
- defaultPrim = "Root"
- metersPerUnit = 1
- upAxis = "Y"
- )
- `;
- }
- // Xform
- function buildHierarchy( object, parentNode, materials, usedNames, files, options ) {
- for ( let i = 0, l = object.children.length; i < l; i ++ ) {
- const child = object.children[ i ];
- if ( child.visible === false && options.onlyVisible === true ) continue;
- let childNode;
- if ( child.isMesh ) {
- const geometry = child.geometry;
- const material = child.material;
- if ( material.isMeshStandardMaterial ) {
- const geometryFileName = 'geometries/Geometry_' + geometry.id + '.usda';
- if ( ! ( geometryFileName in files ) ) {
- const meshObject = buildMeshObject( geometry );
- files[ geometryFileName ] = strToU8(
- buildHeader() + '\n' + meshObject.toString()
- );
- }
- if ( ! ( material.uuid in materials ) ) {
- materials[ material.uuid ] = material;
- }
- childNode = buildMesh(
- child,
- geometry,
- materials[ material.uuid ],
- usedNames
- );
- } else {
- console.warn(
- 'THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)',
- child
- );
- }
- } else if ( child.isCamera ) {
- childNode = buildCamera( child, usedNames );
- } else {
- childNode = buildXform( child, usedNames );
- }
- if ( childNode ) {
- parentNode.addChild( childNode );
- buildHierarchy( child, childNode, materials, usedNames, files, options );
- }
- }
- }
- function buildXform( object, usedNames ) {
- const name = getName( object, usedNames );
- if ( object.matrix.determinant() < 0 ) {
- console.warn(
- 'THREE.USDZExporter: USDZ does not support negative scales',
- object
- );
- }
- const node = new USDNode( name, 'Xform' );
- if ( object.pivot !== null ) {
- // Export with pivot using separate transform ops
- const p = object.position;
- const q = object.quaternion;
- const s = object.scale;
- const piv = object.pivot;
- node.addProperty( `float3 xformOp:translate = (${p.x.toPrecision( PRECISION )}, ${p.y.toPrecision( PRECISION )}, ${p.z.toPrecision( PRECISION )})` );
- node.addProperty( `float3 xformOp:translate:pivot = (${piv.x.toPrecision( PRECISION )}, ${piv.y.toPrecision( PRECISION )}, ${piv.z.toPrecision( PRECISION )})` );
- node.addProperty( `quatf xformOp:orient = (${q.w.toPrecision( PRECISION )}, ${q.x.toPrecision( PRECISION )}, ${q.y.toPrecision( PRECISION )}, ${q.z.toPrecision( PRECISION )})` );
- node.addProperty( `float3 xformOp:scale = (${s.x.toPrecision( PRECISION )}, ${s.y.toPrecision( PRECISION )}, ${s.z.toPrecision( PRECISION )})` );
- node.addProperty( 'uniform token[] xformOpOrder = ["xformOp:translate", "xformOp:translate:pivot", "xformOp:orient", "xformOp:scale", "!invert!xformOp:translate:pivot"]' );
- } else {
- // Export as single transform matrix
- const transform = buildMatrix( object.matrix );
- node.addProperty( `matrix4d xformOp:transform = ${transform}` );
- node.addProperty( 'uniform token[] xformOpOrder = ["xformOp:transform"]' );
- }
- return node;
- }
- function buildMesh( object, geometry, material, usedNames ) {
- const node = buildXform( object, usedNames );
- node.addMetadata(
- 'prepend references',
- `@./geometries/Geometry_${geometry.id}.usda@</Geometry>`
- );
- node.addMetadata( 'prepend apiSchemas', '["MaterialBindingAPI"]' );
- node.addProperty(
- `rel material:binding = </Materials/Material_${material.id}>`
- );
- return node;
- }
- function buildMatrix( matrix ) {
- const array = matrix.elements;
- return `( ${buildMatrixRow( array, 0 )}, ${buildMatrixRow(
- array,
- 4
- )}, ${buildMatrixRow( array, 8 )}, ${buildMatrixRow( array, 12 )} )`;
- }
- function buildMatrixRow( array, offset ) {
- return `(${array[ offset + 0 ]}, ${array[ offset + 1 ]}, ${array[ offset + 2 ]}, ${
- array[ offset + 3 ]
- })`;
- }
- // Mesh
- function buildMeshObject( geometry ) {
- const node = new USDNode( 'Geometry' );
- const meshNode = buildMeshNode( geometry );
- node.addChild( meshNode );
- return node;
- }
- function buildMeshNode( geometry ) {
- const name = 'Geometry';
- const attributes = geometry.attributes;
- const count = attributes.position.count;
- const node = new USDNode( name, 'Mesh' );
- node.addProperty(
- `int[] faceVertexCounts = [${buildMeshVertexCount( geometry )}]`
- );
- node.addProperty(
- `int[] faceVertexIndices = [${buildMeshVertexIndices( geometry )}]`
- );
- node.addProperty(
- `normal3f[] normals = [${buildVector3Array( attributes.normal, count )}]`,
- [ 'interpolation = "vertex"' ]
- );
- node.addProperty(
- `point3f[] points = [${buildVector3Array( attributes.position, count )}]`
- );
- for ( let i = 0; i < 4; i ++ ) {
- const id = i > 0 ? i : '';
- const attribute = attributes[ 'uv' + id ];
- if ( attribute !== undefined ) {
- node.addProperty(
- `texCoord2f[] primvars:st${id} = [${buildVector2Array( attribute )}]`,
- [ 'interpolation = "vertex"' ]
- );
- }
- }
- const colorAttribute = attributes.color;
- if ( colorAttribute !== undefined ) {
- node.addProperty(
- `color3f[] primvars:displayColor = [${buildVector3Array(
- colorAttribute,
- count
- )}]`,
- [ 'interpolation = "vertex"' ]
- );
- }
- node.addProperty( 'uniform token subdivisionScheme = "none"' );
- return node;
- }
- function buildMeshVertexCount( geometry ) {
- const count =
- geometry.index !== null
- ? geometry.index.count
- : geometry.attributes.position.count;
- return Array( count / 3 )
- .fill( 3 )
- .join( ', ' );
- }
- function buildMeshVertexIndices( geometry ) {
- const index = geometry.index;
- const array = [];
- if ( index !== null ) {
- for ( let i = 0; i < index.count; i ++ ) {
- array.push( index.getX( i ) );
- }
- } else {
- const length = geometry.attributes.position.count;
- for ( let i = 0; i < length; i ++ ) {
- array.push( i );
- }
- }
- return array.join( ', ' );
- }
- function buildVector3Array( attribute, count ) {
- if ( attribute === undefined ) {
- console.warn( 'USDZExporter: Normals missing.' );
- return Array( count ).fill( '(0, 0, 0)' ).join( ', ' );
- }
- const array = [];
- for ( let i = 0; i < attribute.count; i ++ ) {
- const x = attribute.getX( i );
- const y = attribute.getY( i );
- const z = attribute.getZ( i );
- array.push(
- `(${x.toPrecision( PRECISION )}, ${y.toPrecision(
- PRECISION
- )}, ${z.toPrecision( PRECISION )})`
- );
- }
- return array.join( ', ' );
- }
- function buildVector2Array( attribute ) {
- const array = [];
- for ( let i = 0; i < attribute.count; i ++ ) {
- const x = attribute.getX( i );
- const y = attribute.getY( i );
- array.push(
- `(${x.toPrecision( PRECISION )}, ${1 - y.toPrecision( PRECISION )})`
- );
- }
- return array.join( ', ' );
- }
- // Materials
- function buildMaterials( materials, textures, quickLookCompatible = false ) {
- const materialsNode = new USDNode( 'Materials' );
- for ( const uuid in materials ) {
- const material = materials[ uuid ];
- materialsNode.addChild(
- buildMaterial( material, textures, quickLookCompatible )
- );
- }
- return materialsNode;
- }
- function buildMaterial( material, textures, quickLookCompatible = false ) {
- // https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
- const materialNode = new USDNode( `Material_${material.id}`, 'Material' );
- function buildTextureNodes( texture, mapType, color ) {
- const id = texture.source.id + '_' + texture.flipY;
- textures[ id ] = texture;
- const uv = texture.channel > 0 ? 'st' + texture.channel : 'st';
- const WRAPPINGS = {
- 1000: 'repeat', // RepeatWrapping
- 1001: 'clamp', // ClampToEdgeWrapping
- 1002: 'mirror', // MirroredRepeatWrapping
- };
- const repeat = texture.repeat.clone();
- const offset = texture.offset.clone();
- const rotation = texture.rotation;
- // rotation is around the wrong point. after rotation we need to shift offset again so that we're rotating around the right spot
- const xRotationOffset = Math.sin( rotation );
- const yRotationOffset = Math.cos( rotation );
- // texture coordinates start in the opposite corner, need to correct
- offset.y = 1 - offset.y - repeat.y;
- // turns out QuickLook is buggy and interprets texture repeat inverted/applies operations in a different order.
- // Apple Feedback: FB10036297 and FB11442287
- if ( quickLookCompatible ) {
- // This is NOT correct yet in QuickLook, but comes close for a range of models.
- // It becomes more incorrect the bigger the offset is
- offset.x = offset.x / repeat.x;
- offset.y = offset.y / repeat.y;
- offset.x += xRotationOffset / repeat.x;
- offset.y += yRotationOffset - 1;
- } else {
- // results match glTF results exactly. verified correct in usdview.
- offset.x += xRotationOffset * repeat.x;
- offset.y += ( 1 - yRotationOffset ) * repeat.y;
- }
- const primvarReaderNode = new USDNode( `PrimvarReader_${mapType}`, 'Shader' );
- primvarReaderNode.addProperty(
- 'uniform token info:id = "UsdPrimvarReader_float2"'
- );
- primvarReaderNode.addProperty( 'float2 inputs:fallback = (0.0, 0.0)' );
- primvarReaderNode.addProperty( `string inputs:varname = "${uv}"` );
- primvarReaderNode.addProperty( 'float2 outputs:result' );
- const transform2dNode = new USDNode( `Transform2d_${mapType}`, 'Shader' );
- transform2dNode.addProperty( 'uniform token info:id = "UsdTransform2d"' );
- transform2dNode.addProperty(
- `float2 inputs:in.connect = </Materials/Material_${material.id}/PrimvarReader_${mapType}.outputs:result>`
- );
- transform2dNode.addProperty(
- `float inputs:rotation = ${( rotation * ( 180 / Math.PI ) ).toFixed(
- PRECISION
- )}`
- );
- transform2dNode.addProperty(
- `float2 inputs:scale = ${buildVector2( repeat )}`
- );
- transform2dNode.addProperty(
- `float2 inputs:translation = ${buildVector2( offset )}`
- );
- transform2dNode.addProperty( 'float2 outputs:result' );
- const textureNode = new USDNode(
- `Texture_${texture.id}_${mapType}`,
- 'Shader'
- );
- textureNode.addProperty( 'uniform token info:id = "UsdUVTexture"' );
- textureNode.addProperty( `asset inputs:file = @textures/Texture_${id}.png@` );
- textureNode.addProperty(
- `float2 inputs:st.connect = </Materials/Material_${material.id}/Transform2d_${mapType}.outputs:result>`
- );
- if ( color !== undefined ) {
- textureNode.addProperty( `float4 inputs:scale = ${buildColor4( color )}` );
- }
- if ( mapType === 'normal' ) {
- textureNode.addProperty( 'float4 inputs:scale = (2, 2, 2, 1)' );
- textureNode.addProperty( 'float4 inputs:bias = (-1, -1, -1, 0)' );
- }
- textureNode.addProperty(
- `token inputs:sourceColorSpace = "${
- texture.colorSpace === NoColorSpace ? 'raw' : 'sRGB'
- }"`
- );
- textureNode.addProperty(
- `token inputs:wrapS = "${WRAPPINGS[ texture.wrapS ]}"`
- );
- textureNode.addProperty(
- `token inputs:wrapT = "${WRAPPINGS[ texture.wrapT ]}"`
- );
- textureNode.addProperty( 'float outputs:r' );
- textureNode.addProperty( 'float outputs:g' );
- textureNode.addProperty( 'float outputs:b' );
- textureNode.addProperty( 'float3 outputs:rgb' );
- if ( material.transparent || material.alphaTest > 0.0 ) {
- textureNode.addProperty( 'float outputs:a' );
- }
- return [ primvarReaderNode, transform2dNode, textureNode ];
- }
- if ( material.side === DoubleSide ) {
- console.warn(
- 'THREE.USDZExporter: USDZ does not support double sided materials',
- material
- );
- }
- const previewSurfaceNode = new USDNode( 'PreviewSurface', 'Shader' );
- previewSurfaceNode.addProperty( 'uniform token info:id = "UsdPreviewSurface"' );
- if ( material.map !== null ) {
- previewSurfaceNode.addProperty(
- `color3f inputs:diffuseColor.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:rgb>`
- );
- if ( material.transparent ) {
- previewSurfaceNode.addProperty(
- `float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:a>`
- );
- } else if ( material.alphaTest > 0.0 ) {
- previewSurfaceNode.addProperty(
- `float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.map.id}_diffuse.outputs:a>`
- );
- previewSurfaceNode.addProperty(
- `float inputs:opacityThreshold = ${material.alphaTest}`
- );
- }
- const textureNodes = buildTextureNodes(
- material.map,
- 'diffuse',
- material.color
- );
- textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
- } else {
- previewSurfaceNode.addProperty(
- `color3f inputs:diffuseColor = ${buildColor( material.color )}`
- );
- }
- if ( material.emissiveMap !== null ) {
- previewSurfaceNode.addProperty(
- `color3f inputs:emissiveColor.connect = </Materials/Material_${material.id}/Texture_${material.emissiveMap.id}_emissive.outputs:rgb>`
- );
- const emissiveColor = new Color(
- material.emissive.r * material.emissiveIntensity,
- material.emissive.g * material.emissiveIntensity,
- material.emissive.b * material.emissiveIntensity
- );
- const textureNodes = buildTextureNodes(
- material.emissiveMap,
- 'emissive',
- emissiveColor
- );
- textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
- } else if ( material.emissive.getHex() > 0 ) {
- previewSurfaceNode.addProperty(
- `color3f inputs:emissiveColor = ${buildColor( material.emissive )}`
- );
- }
- if ( material.normalMap !== null ) {
- previewSurfaceNode.addProperty(
- `normal3f inputs:normal.connect = </Materials/Material_${material.id}/Texture_${material.normalMap.id}_normal.outputs:rgb>`
- );
- const textureNodes = buildTextureNodes( material.normalMap, 'normal' );
- textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
- }
- if ( material.aoMap !== null ) {
- previewSurfaceNode.addProperty(
- `float inputs:occlusion.connect = </Materials/Material_${material.id}/Texture_${material.aoMap.id}_occlusion.outputs:r>`
- );
- const aoColor = new Color(
- material.aoMapIntensity,
- material.aoMapIntensity,
- material.aoMapIntensity
- );
- const textureNodes = buildTextureNodes(
- material.aoMap,
- 'occlusion',
- aoColor
- );
- textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
- }
- if ( material.roughnessMap !== null ) {
- previewSurfaceNode.addProperty(
- `float inputs:roughness.connect = </Materials/Material_${material.id}/Texture_${material.roughnessMap.id}_roughness.outputs:g>`
- );
- const roughnessColor = new Color(
- material.roughness,
- material.roughness,
- material.roughness
- );
- const textureNodes = buildTextureNodes(
- material.roughnessMap,
- 'roughness',
- roughnessColor
- );
- textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
- } else {
- previewSurfaceNode.addProperty(
- `float inputs:roughness = ${material.roughness}`
- );
- }
- if ( material.metalnessMap !== null ) {
- previewSurfaceNode.addProperty(
- `float inputs:metallic.connect = </Materials/Material_${material.id}/Texture_${material.metalnessMap.id}_metallic.outputs:b>`
- );
- const metalnessColor = new Color(
- material.metalness,
- material.metalness,
- material.metalness
- );
- const textureNodes = buildTextureNodes(
- material.metalnessMap,
- 'metallic',
- metalnessColor
- );
- textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
- } else {
- previewSurfaceNode.addProperty(
- `float inputs:metallic = ${material.metalness}`
- );
- }
- if ( material.alphaMap !== null ) {
- previewSurfaceNode.addProperty(
- `float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.alphaMap.id}_opacity.outputs:r>`
- );
- previewSurfaceNode.addProperty( 'float inputs:opacityThreshold = 0.0001' );
- const textureNodes = buildTextureNodes( material.alphaMap, 'opacity' );
- textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
- } else {
- previewSurfaceNode.addProperty(
- `float inputs:opacity = ${material.opacity}`
- );
- }
- if ( material.isMeshPhysicalMaterial ) {
- if ( material.clearcoatMap !== null ) {
- previewSurfaceNode.addProperty(
- `float inputs:clearcoat.connect = </Materials/Material_${material.id}/Texture_${material.clearcoatMap.id}_clearcoat.outputs:r>`
- );
- const clearcoatColor = new Color(
- material.clearcoat,
- material.clearcoat,
- material.clearcoat
- );
- const textureNodes = buildTextureNodes(
- material.clearcoatMap,
- 'clearcoat',
- clearcoatColor
- );
- textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
- } else {
- previewSurfaceNode.addProperty(
- `float inputs:clearcoat = ${material.clearcoat}`
- );
- }
- if ( material.clearcoatRoughnessMap !== null ) {
- previewSurfaceNode.addProperty(
- `float inputs:clearcoatRoughness.connect = </Materials/Material_${material.id}/Texture_${material.clearcoatRoughnessMap.id}_clearcoatRoughness.outputs:g>`
- );
- const clearcoatRoughnessColor = new Color(
- material.clearcoatRoughness,
- material.clearcoatRoughness,
- material.clearcoatRoughness
- );
- const textureNodes = buildTextureNodes(
- material.clearcoatRoughnessMap,
- 'clearcoatRoughness',
- clearcoatRoughnessColor
- );
- textureNodes.forEach( ( node ) => materialNode.addChild( node ) );
- } else {
- previewSurfaceNode.addProperty(
- `float inputs:clearcoatRoughness = ${material.clearcoatRoughness}`
- );
- }
- previewSurfaceNode.addProperty( `float inputs:ior = ${material.ior}` );
- }
- previewSurfaceNode.addProperty( 'int inputs:useSpecularWorkflow = 0' );
- previewSurfaceNode.addProperty( 'token outputs:surface' );
- materialNode.addChild( previewSurfaceNode );
- materialNode.addProperty(
- `token outputs:surface.connect = </Materials/Material_${material.id}/PreviewSurface.outputs:surface>`
- );
- return materialNode;
- }
- function buildColor( color ) {
- return `(${color.r}, ${color.g}, ${color.b})`;
- }
- function buildColor4( color ) {
- return `(${color.r}, ${color.g}, ${color.b}, 1.0)`;
- }
- function buildVector2( vector ) {
- return `(${vector.x}, ${vector.y})`;
- }
- function buildCamera( camera, usedNames ) {
- const name = getName( camera, usedNames );
- const transform = buildMatrix( camera.matrix );
- if ( camera.matrix.determinant() < 0 ) {
- console.warn(
- 'THREE.USDZExporter: USDZ does not support negative scales',
- camera
- );
- }
- const node = new USDNode( name, 'Camera' );
- node.addProperty( `matrix4d xformOp:transform = ${transform}` );
- node.addProperty( 'uniform token[] xformOpOrder = ["xformOp:transform"]' );
- const projection = camera.isOrthographicCamera
- ? 'orthographic'
- : 'perspective';
- node.addProperty( `token projection = "${projection}"` );
- const clippingRange = `(${camera.near.toPrecision(
- PRECISION
- )}, ${camera.far.toPrecision( PRECISION )})`;
- node.addProperty( `float2 clippingRange = ${clippingRange}` );
- let horizontalAperture;
- if ( camera.isOrthographicCamera ) {
- horizontalAperture = (
- ( Math.abs( camera.left ) + Math.abs( camera.right ) ) *
- 10
- ).toPrecision( PRECISION );
- } else {
- horizontalAperture = camera.getFilmWidth().toPrecision( PRECISION );
- }
- node.addProperty( `float horizontalAperture = ${horizontalAperture}` );
- let verticalAperture;
- if ( camera.isOrthographicCamera ) {
- verticalAperture = (
- ( Math.abs( camera.top ) + Math.abs( camera.bottom ) ) *
- 10
- ).toPrecision( PRECISION );
- } else {
- verticalAperture = camera.getFilmHeight().toPrecision( PRECISION );
- }
- node.addProperty( `float verticalAperture = ${verticalAperture}` );
- if ( camera.isPerspectiveCamera ) {
- const focalLength = camera.getFocalLength().toPrecision( PRECISION );
- node.addProperty( `float focalLength = ${focalLength}` );
- const focusDistance = camera.focus.toPrecision( PRECISION );
- node.addProperty( `float focusDistance = ${focusDistance}` );
- }
- return node;
- }
- /**
- * Export options of `USDZExporter`.
- *
- * @typedef {Object} USDZExporter~Options
- * @property {number} [maxTextureSize=1024] - The maximum texture size that is going to be exported.
- * @property {boolean} [includeAnchoringProperties=true] - Whether to include anchoring properties or not.
- * @property {boolean} [onlyVisible=true] - Export only visible 3D objects.
- * @property {Object} [ar] - If `includeAnchoringProperties` is set to `true`, the anchoring type and alignment
- * can be configured via `ar.anchoring.type` and `ar.planeAnchoring.alignment`.
- * @property {boolean} [quickLookCompatible=false] - Whether to make the exported USDZ compatible to QuickLook
- * which means the asset is modified to accommodate the bugs FB10036297 and FB11442287 (Apple Feedback).
- **/
- /**
- * onDone callback of `USDZExporter`.
- *
- * @callback USDZExporter~OnDone
- * @param {ArrayBuffer} result - The generated USDZ.
- */
- /**
- * onError callback of `USDZExporter`.
- *
- * @callback USDZExporter~OnError
- * @param {Error} error - The error object.
- */
- export { USDZExporter };
|