USDZExporter.js 9.8 KB
Newer Older
1
import * as fflate from '../libs/fflate.module.js';
M
Mr.doob 已提交
2 3 4

class USDZExporter {

M
Mr.doob 已提交
5
	async parse( scene ) {
M
Mr.doob 已提交
6

7 8 9 10
		const files = {};
		const modelFileName = 'model.usda';
		const geometryFileName = 'geometry.usd';

M
Mr.doob 已提交
11 12
		let output = buildHeader();

13
		const geometries = {};
M
Mr.doob 已提交
14
		const materials = {};
M
Mr.doob 已提交
15
		const textures = {};
M
Mr.doob 已提交
16 17 18 19 20

		scene.traverse( ( object ) => {

			if ( object.isMesh ) {

M
Mr.doob 已提交
21 22 23
				const geometry = object.geometry;
				const material = object.material;

24 25 26 27 28 29 30
				if ( ! ( geometry.uuid in geometries ) ) {

					geometries[ geometry.uuid ] = geometry;

				}

				if ( ! ( material.uuid in materials ) ) {
M
Mr.doob 已提交
31

32 33 34 35 36 37 38
					materials[ material.uuid ] = material;
					if ( material.map !== null ) textures[ material.map.uuid ] = material.map;
					if ( material.normalMap !== null ) textures[ material.normalMap.uuid ] = material.normalMap;
					if ( material.aoMap !== null ) textures[ material.aoMap.uuid ] = material.aoMap;
					if ( material.roughnessMap !== null ) textures[ material.roughnessMap.uuid ] = material.roughnessMap;
					if ( material.metalnessMap !== null ) textures[ material.metalnessMap.uuid ] = material.metalnessMap;
					if ( material.emissiveMap !== null ) textures[ material.emissiveMap.uuid ] = material.emissiveMap;
M
Mr.doob 已提交
39

40 41 42 43 44
				}

				const referencedMesh = `prepend references = @./${geometryFileName}@</Geometry_${ geometry.id }>`;
				const referencedMaterial = `rel material:binding = </Materials/Material_${ material.id }>`;
				output += buildXform( object, referencedMesh, referencedMaterial );
M
Mr.doob 已提交
45 46 47 48 49 50

			}

		} );

		output += buildMaterials( materials );
M
Mr.doob 已提交
51 52
		output += buildTextures( textures );

53 54 55 56
		files[ modelFileName ] = fflate.strToU8( output );
		output = null;

		files[ geometryFileName ] = fflate.strToU8( buildMeshFileString( geometries ) );
M
Mr.doob 已提交
57 58

		for ( const uuid in textures ) {
M
Mr.doob 已提交
59

M
Mr.doob 已提交
60
			const texture = textures[ uuid ];
61
			files[ 'textures/Texture_' + texture.id + '.jpg' ] = await imgToU8( texture.image );
M
Mr.doob 已提交
62 63 64

		}

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
		// 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;

		}

92
		return fflate.zipSync( files, { level: 0 } );
M
Mr.doob 已提交
93 94 95 96 97

	}

}

M
Mr.doob 已提交
98
async function imgToU8( image ) {
M
Mr.doob 已提交
99 100 101 102 103 104

	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 ) ) {

M
Mr.doob 已提交
105 106
		const scale = 1024 / Math.max( image.width, image.height );

M
Mr.doob 已提交
107
		const canvas = document.createElement( 'canvas' );
M
Mr.doob 已提交
108 109
		canvas.width = image.width * Math.min( 1, scale );
		canvas.height = image.height * Math.min( 1, scale );
M
Mr.doob 已提交
110 111 112 113

		const context = canvas.getContext( '2d' );
		context.drawImage( image, 0, 0, canvas.width, canvas.height );

114
		const blob = await new Promise( resolve => canvas.toBlob( resolve, 'image/jpeg', 1 ) );
M
Mr.doob 已提交
115
		return new Uint8Array( await blob.arrayBuffer() );
M
Mr.doob 已提交
116 117 118 119 120 121 122

	}

}

//

123 124
const PRECISION = 7;

M
Mr.doob 已提交
125 126 127 128
function buildHeader() {

	return `#usda 1.0
(
M
Mr.doob 已提交
129 130 131
    customLayerData = {
        string creator = "Three.js USDZExporter"
    }
M
Mr.doob 已提交
132 133 134 135 136 137 138 139 140 141
    metersPerUnit = 1
    upAxis = "Y"
)

`;

}

// Xform

142
function buildXform( object, referencedMesh, referencedMaterial ) {
M
Mr.doob 已提交
143

M
Mr.doob 已提交
144
	const name = 'Object_' + object.id;
M
Mr.doob 已提交
145 146 147
	const transform = buildMatrix( object.matrixWorld );

	return `def Xform "${ name }"
148 149 150
(
	${ referencedMesh }
)
M
Mr.doob 已提交
151 152 153 154
{
    matrix4d xformOp:transform = ${ transform }
    uniform token[] xformOpOrder = ["xformOp:transform"]

155
    ${ referencedMaterial }
M
Mr.doob 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
}

`;

}

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

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
function buildMeshFileString( geometries ) {

	let output = buildHeader();

	for ( const uuid in geometries ) {

		const geometry = geometries[ uuid ];
		output += buildMeshObject( geometry );

	}

	return output;

}

function buildMeshObject( geometry ) {

	const name = 'Geometry_' + geometry.id;
	const mesh = buildMesh( geometry );
	return `
def "${name}"
{
	${mesh}
}
`;

}

function buildMesh( geometry ) {
M
Mr.doob 已提交
207

M
Mr.doob 已提交
208
	const name = 'Geometry_' + geometry.id;
M
Mr.doob 已提交
209 210 211
	const attributes = geometry.attributes;
	const count = attributes.position.count;

M
Mr.doob 已提交
212 213 214 215 216 217
	if ( 'uv2' in attributes ) {

		console.warn( 'THREE.USDZExporter: uv2 not supported yet.' );

	}

218 219
	return `
	def Mesh "${ name }"
M
Mr.doob 已提交
220 221 222 223
    {
        int[] faceVertexCounts = [${ buildMeshVertexCount( geometry ) }]
        int[] faceVertexIndices = [${ buildMeshVertexIndices( geometry ) }]
        normal3f[] normals = [${ buildVector3Array( attributes.normal, count )}] (
M
Mr.doob 已提交
224
            interpolation = "vertex"
M
Mr.doob 已提交
225 226
        )
        point3f[] points = [${ buildVector3Array( attributes.position, count )}]
M
Mr.doob 已提交
227 228
        float2[] primvars:st = [${ buildVector2Array( attributes.uv, count )}] (
            interpolation = "vertex"
M
Mr.doob 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
        )
        uniform token subdivisionScheme = "none"
    }
`;

}

function buildMeshVertexCount( geometry ) {

	const count = geometry.index !== null ? geometry.index.array.length : geometry.attributes.position.count;

	return Array( count / 3 ).fill( 3 ).join( ', ' );

}

function buildMeshVertexIndices( geometry ) {

	if ( geometry.index !== null ) {

		return geometry.index.array.join( ', ' );

	}

	const array = [];
	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 = [];
	const data = attribute.array;

	for ( let i = 0; i < data.length; i += 3 ) {

279
		array.push( `(${ data[ i + 0 ].toPrecision( PRECISION ) }, ${ data[ i + 1 ].toPrecision( PRECISION ) }, ${ data[ i + 2 ].toPrecision( PRECISION ) })` );
M
Mr.doob 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300

	}

	return array.join( ', ' );

}

function buildVector2Array( attribute, count ) {

	if ( attribute === undefined ) {

		console.warn( 'USDZExporter: UVs missing.' );
		return Array( count ).fill( '(0, 0)' ).join( ', ' );

	}

	const array = [];
	const data = attribute.array;

	for ( let i = 0; i < data.length; i += 2 ) {

301
		array.push( `(${ data[ i + 0 ].toPrecision( PRECISION ) }, ${ 1 - data[ i + 1 ].toPrecision( PRECISION ) })` );
M
Mr.doob 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322

	}

	return array.join( ', ' );

}

// Materials

function buildMaterials( materials ) {

	const array = [];

	for ( const uuid in materials ) {

		const material = materials[ uuid ];

		array.push( buildMaterial( material ) );

	}

M
Mr.doob 已提交
323
	return `def "Materials"
M
Mr.doob 已提交
324 325 326 327 328 329 330 331 332 333
{
${ array.join( '' ) }
}

`;

}

function buildMaterial( material ) {

334 335
	// https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html

336 337
	const pad = '            ';
	const parameters = [];
M
Mr.doob 已提交
338 339 340

	if ( material.map !== null ) {

341
		parameters.push( `${ pad }color3f inputs:diffuseColor.connect = </Textures/Texture_${ material.map.id }.outputs:rgb>` );
342 343 344

	} else {

345
		parameters.push( `${ pad }color3f inputs:diffuseColor = ${ buildColor( material.color ) }` );
M
Mr.doob 已提交
346 347 348

	}

349 350
	if ( material.emissiveMap !== null ) {

351
		parameters.push( `${ pad }color3f inputs:emissiveColor.connect = </Textures/Texture_${ material.emissiveMap.id }.outputs:rgb>` );
352

353
	} else if ( material.emissive.getHex() > 0 ) {
354

355
		parameters.push( `${ pad }color3f inputs:emissiveColor = ${ buildColor( material.emissive ) }` );
356 357 358

	}

M
Mr.doob 已提交
359 360
	if ( material.normalMap !== null ) {

361
		parameters.push( `${ pad }normal3f inputs:normal.connect = </Textures/Texture_${ material.normalMap.id }.outputs:rgb>` );
M
Mr.doob 已提交
362 363 364 365 366

	}

	if ( material.aoMap !== null ) {

367
		parameters.push( `${ pad }float inputs:occlusion.connect = </Textures/Texture_${ material.aoMap.id }.outputs:r>` );
M
Mr.doob 已提交
368 369 370 371 372

	}

	if ( material.roughnessMap !== null ) {

373
		parameters.push( `${ pad }float inputs:roughness.connect = </Textures/Texture_${ material.roughnessMap.id }.outputs:g>` );
374 375 376 377

	} else {

		parameters.push( `${ pad }float inputs:roughness = ${ material.roughness }` );
M
Mr.doob 已提交
378 379 380 381 382

	}

	if ( material.metalnessMap !== null ) {

383
		parameters.push( `${ pad }float inputs:metallic.connect = </Textures/Texture_${ material.metalnessMap.id }.outputs:b>` );
384 385 386 387

	} else {

		parameters.push( `${ pad }float inputs:metallic = ${ material.metalness }` );
M
Mr.doob 已提交
388 389 390

	}

391 392
	parameters.push( `${ pad }float inputs:opacity = ${ material.opacity }` );

M
Mr.doob 已提交
393 394 395
	return `
    def Material "Material_${ material.id }"
    {
M
Mr.doob 已提交
396
        token outputs:surface.connect = </Materials/Material_${ material.id }/PreviewSurface.outputs:surface>
M
Mr.doob 已提交
397

M
Mr.doob 已提交
398
        def Shader "PreviewSurface"
M
Mr.doob 已提交
399 400
        {
            uniform token info:id = "UsdPreviewSurface"
401
${ parameters.join( '\n' ) }
M
Mr.doob 已提交
402
            int inputs:useSpecularWorkflow = 0
M
Mr.doob 已提交
403 404 405 406 407 408 409
            token outputs:surface
        }
    }
`;

}

M
Mr.doob 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
function buildTextures( textures ) {

	const array = [];

	for ( const uuid in textures ) {

		const texture = textures[ uuid ];

		array.push( buildTexture( texture ) );

	}

	return `def "Textures"
{
${ array.join( '' ) }
}

`;

}

function buildTexture( texture ) {

	return `
    def Shader "Texture_${ texture.id }"
    {
        uniform token info:id = "UsdUVTexture"
        asset inputs:file = @textures/Texture_${ texture.id }.jpg@
        token inputs:wrapS = "repeat"
        token inputs:wrapT = "repeat"
440 441 442
        float outputs:r
        float outputs:g
        float outputs:b
M
Mr.doob 已提交
443 444 445 446 447 448
        float3 outputs:rgb
    }
`;

}

M
Mr.doob 已提交
449 450 451 452 453 454 455
function buildColor( color ) {

	return `(${ color.r }, ${ color.g }, ${ color.b })`;

}

export { USDZExporter };