Archived
Private
Public Access
1
0

Initial commit

This commit is contained in:
2022-09-04 12:45:01 +02:00
commit f4a01d6a69
11601 changed files with 4206660 additions and 0 deletions

View File

@@ -0,0 +1,722 @@
import {
Color,
DoubleSide,
Matrix4,
MeshBasicMaterial
} from 'three';
/**
* https://github.com/gkjohnson/collada-exporter-js
*
* Usage:
* const exporter = new ColladaExporter();
*
* const data = exporter.parse(mesh);
*
* Format Definition:
* https://www.khronos.org/collada/
*/
class ColladaExporter {
parse( object, onDone, options = {} ) {
options = Object.assign( {
version: '1.4.1',
author: null,
textureDirectory: '',
upAxis: 'Y_UP',
unitName: null,
unitMeter: null,
}, options );
if ( options.upAxis.match( /^[XYZ]_UP$/ ) === null ) {
console.error( 'ColladaExporter: Invalid upAxis: valid values are X_UP, Y_UP or Z_UP.' );
return null;
}
if ( options.unitName !== null && options.unitMeter === null ) {
console.error( 'ColladaExporter: unitMeter needs to be specified if unitName is specified.' );
return null;
}
if ( options.unitMeter !== null && options.unitName === null ) {
console.error( 'ColladaExporter: unitName needs to be specified if unitMeter is specified.' );
return null;
}
if ( options.textureDirectory !== '' ) {
options.textureDirectory = `${ options.textureDirectory }/`
.replace( /\\/g, '/' )
.replace( /\/+/g, '/' );
}
const version = options.version;
if ( version !== '1.4.1' && version !== '1.5.0' ) {
console.warn( `ColladaExporter : Version ${ version } not supported for export. Only 1.4.1 and 1.5.0.` );
return null;
}
// Convert the urdf xml into a well-formatted, indented format
function format( urdf ) {
const IS_END_TAG = /^<\//;
const IS_SELF_CLOSING = /(\?>$)|(\/>$)/;
const HAS_TEXT = /<[^>]+>[^<]*<\/[^<]+>/;
const pad = ( ch, num ) => ( num > 0 ? ch + pad( ch, num - 1 ) : '' );
let tagnum = 0;
return urdf
.match( /(<[^>]+>[^<]+<\/[^<]+>)|(<[^>]+>)/g )
.map( tag => {
if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && IS_END_TAG.test( tag ) ) {
tagnum --;
}
const res = `${ pad( ' ', tagnum ) }${ tag }`;
if ( ! HAS_TEXT.test( tag ) && ! IS_SELF_CLOSING.test( tag ) && ! IS_END_TAG.test( tag ) ) {
tagnum ++;
}
return res;
} )
.join( '\n' );
}
// Convert an image into a png format for saving
function base64ToBuffer( str ) {
const b = atob( str );
const buf = new Uint8Array( b.length );
for ( let i = 0, l = buf.length; i < l; i ++ ) {
buf[ i ] = b.charCodeAt( i );
}
return buf;
}
let canvas, ctx;
function imageToData( image, ext ) {
canvas = canvas || document.createElement( 'canvas' );
ctx = ctx || canvas.getContext( '2d' );
canvas.width = image.width;
canvas.height = image.height;
ctx.drawImage( image, 0, 0 );
// Get the base64 encoded data
const base64data = canvas
.toDataURL( `image/${ ext }`, 1 )
.replace( /^data:image\/(png|jpg);base64,/, '' );
// Convert to a uint8 array
return base64ToBuffer( base64data );
}
// gets the attribute array. Generate a new array if the attribute is interleaved
const getFuncs = [ 'getX', 'getY', 'getZ', 'getW' ];
const tempColor = new Color();
function attrBufferToArray( attr, isColor = false ) {
if ( isColor ) {
// convert the colors to srgb before export
// colors are always written as floats
const arr = new Float32Array( attr.count * 3 );
for ( let i = 0, l = attr.count; i < l; i ++ ) {
tempColor
.fromBufferAttribute( attr, i )
.convertLinearToSRGB();
arr[ 3 * i + 0 ] = tempColor.r;
arr[ 3 * i + 1 ] = tempColor.g;
arr[ 3 * i + 2 ] = tempColor.b;
}
return arr;
} else if ( attr.isInterleavedBufferAttribute ) {
// use the typed array constructor to save on memory
const arr = new attr.array.constructor( attr.count * attr.itemSize );
const size = attr.itemSize;
for ( let i = 0, l = attr.count; i < l; i ++ ) {
for ( let j = 0; j < size; j ++ ) {
arr[ i * size + j ] = attr[ getFuncs[ j ] ]( i );
}
}
return arr;
} else {
return attr.array;
}
}
// Returns an array of the same type starting at the `st` index,
// and `ct` length
function subArray( arr, st, ct ) {
if ( Array.isArray( arr ) ) return arr.slice( st, st + ct );
else return new arr.constructor( arr.buffer, st * arr.BYTES_PER_ELEMENT, ct );
}
// Returns the string for a geometry's attribute
function getAttribute( attr, name, params, type, isColor = false ) {
const array = attrBufferToArray( attr, isColor );
const res =
`<source id="${ name }">` +
`<float_array id="${ name }-array" count="${ array.length }">` +
array.join( ' ' ) +
'</float_array>' +
'<technique_common>' +
`<accessor source="#${ name }-array" count="${ Math.floor( array.length / attr.itemSize ) }" stride="${ attr.itemSize }">` +
params.map( n => `<param name="${ n }" type="${ type }" />` ).join( '' ) +
'</accessor>' +
'</technique_common>' +
'</source>';
return res;
}
// Returns the string for a node's transform information
let transMat;
function getTransform( o ) {
// ensure the object's matrix is up to date
// before saving the transform
o.updateMatrix();
transMat = transMat || new Matrix4();
transMat.copy( o.matrix );
transMat.transpose();
return `<matrix>${ transMat.toArray().join( ' ' ) }</matrix>`;
}
// Process the given piece of geometry into the geometry library
// Returns the mesh id
function processGeometry( g ) {
let info = geometryInfo.get( g );
if ( ! info ) {
// convert the geometry to bufferGeometry if it isn't already
const bufferGeometry = g;
if ( bufferGeometry.isBufferGeometry !== true ) {
throw new Error( 'THREE.ColladaExporter: Geometry is not of type THREE.BufferGeometry.' );
}
const meshid = `Mesh${ libraryGeometries.length + 1 }`;
const indexCount =
bufferGeometry.index ?
bufferGeometry.index.count * bufferGeometry.index.itemSize :
bufferGeometry.attributes.position.count;
const groups =
bufferGeometry.groups != null && bufferGeometry.groups.length !== 0 ?
bufferGeometry.groups :
[ { start: 0, count: indexCount, materialIndex: 0 } ];
const gname = g.name ? ` name="${ g.name }"` : '';
let gnode = `<geometry id="${ meshid }"${ gname }><mesh>`;
// define the geometry node and the vertices for the geometry
const posName = `${ meshid }-position`;
const vertName = `${ meshid }-vertices`;
gnode += getAttribute( bufferGeometry.attributes.position, posName, [ 'X', 'Y', 'Z' ], 'float' );
gnode += `<vertices id="${ vertName }"><input semantic="POSITION" source="#${ posName }" /></vertices>`;
// NOTE: We're not optimizing the attribute arrays here, so they're all the same length and
// can therefore share the same triangle indices. However, MeshLab seems to have trouble opening
// models with attributes that share an offset.
// MeshLab Bug#424: https://sourceforge.net/p/meshlab/bugs/424/
// serialize normals
let triangleInputs = `<input semantic="VERTEX" source="#${ vertName }" offset="0" />`;
if ( 'normal' in bufferGeometry.attributes ) {
const normName = `${ meshid }-normal`;
gnode += getAttribute( bufferGeometry.attributes.normal, normName, [ 'X', 'Y', 'Z' ], 'float' );
triangleInputs += `<input semantic="NORMAL" source="#${ normName }" offset="0" />`;
}
// serialize uvs
if ( 'uv' in bufferGeometry.attributes ) {
const uvName = `${ meshid }-texcoord`;
gnode += getAttribute( bufferGeometry.attributes.uv, uvName, [ 'S', 'T' ], 'float' );
triangleInputs += `<input semantic="TEXCOORD" source="#${ uvName }" offset="0" set="0" />`;
}
// serialize lightmap uvs
if ( 'uv2' in bufferGeometry.attributes ) {
const uvName = `${ meshid }-texcoord2`;
gnode += getAttribute( bufferGeometry.attributes.uv2, uvName, [ 'S', 'T' ], 'float' );
triangleInputs += `<input semantic="TEXCOORD" source="#${ uvName }" offset="0" set="1" />`;
}
// serialize colors
if ( 'color' in bufferGeometry.attributes ) {
// colors are always written as floats
const colName = `${ meshid }-color`;
gnode += getAttribute( bufferGeometry.attributes.color, colName, [ 'R', 'G', 'B' ], 'float', true );
triangleInputs += `<input semantic="COLOR" source="#${ colName }" offset="0" />`;
}
let indexArray = null;
if ( bufferGeometry.index ) {
indexArray = attrBufferToArray( bufferGeometry.index );
} else {
indexArray = new Array( indexCount );
for ( let i = 0, l = indexArray.length; i < l; i ++ ) indexArray[ i ] = i;
}
for ( let i = 0, l = groups.length; i < l; i ++ ) {
const group = groups[ i ];
const subarr = subArray( indexArray, group.start, group.count );
const polycount = subarr.length / 3;
gnode += `<triangles material="MESH_MATERIAL_${ group.materialIndex }" count="${ polycount }">`;
gnode += triangleInputs;
gnode += `<p>${ subarr.join( ' ' ) }</p>`;
gnode += '</triangles>';
}
gnode += '</mesh></geometry>';
libraryGeometries.push( gnode );
info = { meshid: meshid, bufferGeometry: bufferGeometry };
geometryInfo.set( g, info );
}
return info;
}
// Process the given texture into the image library
// Returns the image library
function processTexture( tex ) {
let texid = imageMap.get( tex );
if ( texid == null ) {
texid = `image-${ libraryImages.length + 1 }`;
const ext = 'png';
const name = tex.name || texid;
let imageNode = `<image id="${ texid }" name="${ name }">`;
if ( version === '1.5.0' ) {
imageNode += `<init_from><ref>${ options.textureDirectory }${ name }.${ ext }</ref></init_from>`;
} else {
// version image node 1.4.1
imageNode += `<init_from>${ options.textureDirectory }${ name }.${ ext }</init_from>`;
}
imageNode += '</image>';
libraryImages.push( imageNode );
imageMap.set( tex, texid );
textures.push( {
directory: options.textureDirectory,
name,
ext,
data: imageToData( tex.image, ext ),
original: tex
} );
}
return texid;
}
// Process the given material into the material and effect libraries
// Returns the material id
function processMaterial( m ) {
let matid = materialMap.get( m );
if ( matid == null ) {
matid = `Mat${ libraryEffects.length + 1 }`;
let type = 'phong';
if ( m.isMeshLambertMaterial === true ) {
type = 'lambert';
} else if ( m.isMeshBasicMaterial === true ) {
type = 'constant';
if ( m.map !== null ) {
// The Collada spec does not support diffuse texture maps with the
// constant shader type.
// mrdoob/three.js#15469
console.warn( 'ColladaExporter: Texture maps not supported with MeshBasicMaterial.' );
}
}
const emissive = m.emissive ? m.emissive : new Color( 0, 0, 0 );
const diffuse = m.color ? m.color : new Color( 0, 0, 0 );
const specular = m.specular ? m.specular : new Color( 1, 1, 1 );
const shininess = m.shininess || 0;
const reflectivity = m.reflectivity || 0;
emissive.convertLinearToSRGB();
specular.convertLinearToSRGB();
diffuse.convertLinearToSRGB();
// Do not export and alpha map for the reasons mentioned in issue (#13792)
// in three.js alpha maps are black and white, but collada expects the alpha
// channel to specify the transparency
let transparencyNode = '';
if ( m.transparent === true ) {
transparencyNode +=
'<transparent>' +
(
m.map ?
'<texture texture="diffuse-sampler"></texture>' :
'<float>1</float>'
) +
'</transparent>';
if ( m.opacity < 1 ) {
transparencyNode += `<transparency><float>${ m.opacity }</float></transparency>`;
}
}
const techniqueNode = `<technique sid="common"><${ type }>` +
'<emission>' +
(
m.emissiveMap ?
'<texture texture="emissive-sampler" texcoord="TEXCOORD" />' :
`<color sid="emission">${ emissive.r } ${ emissive.g } ${ emissive.b } 1</color>`
) +
'</emission>' +
(
type !== 'constant' ?
'<diffuse>' +
(
m.map ?
'<texture texture="diffuse-sampler" texcoord="TEXCOORD" />' :
`<color sid="diffuse">${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color>`
) +
'</diffuse>'
: ''
) +
(
type !== 'constant' ?
'<bump>' +
(
m.normalMap ? '<texture texture="bump-sampler" texcoord="TEXCOORD" />' : ''
) +
'</bump>'
: ''
) +
(
type === 'phong' ?
`<specular><color sid="specular">${ specular.r } ${ specular.g } ${ specular.b } 1</color></specular>` +
'<shininess>' +
(
m.specularMap ?
'<texture texture="specular-sampler" texcoord="TEXCOORD" />' :
`<float sid="shininess">${ shininess }</float>`
) +
'</shininess>'
: ''
) +
`<reflective><color>${ diffuse.r } ${ diffuse.g } ${ diffuse.b } 1</color></reflective>` +
`<reflectivity><float>${ reflectivity }</float></reflectivity>` +
transparencyNode +
`</${ type }></technique>`;
const effectnode =
`<effect id="${ matid }-effect">` +
'<profile_COMMON>' +
(
m.map ?
'<newparam sid="diffuse-surface"><surface type="2D">' +
`<init_from>${ processTexture( m.map ) }</init_from>` +
'</surface></newparam>' +
'<newparam sid="diffuse-sampler"><sampler2D><source>diffuse-surface</source></sampler2D></newparam>' :
''
) +
(
m.specularMap ?
'<newparam sid="specular-surface"><surface type="2D">' +
`<init_from>${ processTexture( m.specularMap ) }</init_from>` +
'</surface></newparam>' +
'<newparam sid="specular-sampler"><sampler2D><source>specular-surface</source></sampler2D></newparam>' :
''
) +
(
m.emissiveMap ?
'<newparam sid="emissive-surface"><surface type="2D">' +
`<init_from>${ processTexture( m.emissiveMap ) }</init_from>` +
'</surface></newparam>' +
'<newparam sid="emissive-sampler"><sampler2D><source>emissive-surface</source></sampler2D></newparam>' :
''
) +
(
m.normalMap ?
'<newparam sid="bump-surface"><surface type="2D">' +
`<init_from>${ processTexture( m.normalMap ) }</init_from>` +
'</surface></newparam>' +
'<newparam sid="bump-sampler"><sampler2D><source>bump-surface</source></sampler2D></newparam>' :
''
) +
techniqueNode +
(
m.side === DoubleSide ?
'<extra><technique profile="THREEJS"><double_sided sid="double_sided" type="int">1</double_sided></technique></extra>' :
''
) +
'</profile_COMMON>' +
'</effect>';
const materialName = m.name ? ` name="${ m.name }"` : '';
const materialNode = `<material id="${ matid }"${ materialName }><instance_effect url="#${ matid }-effect" /></material>`;
libraryMaterials.push( materialNode );
libraryEffects.push( effectnode );
materialMap.set( m, matid );
}
return matid;
}
// Recursively process the object into a scene
function processObject( o ) {
let node = `<node name="${ o.name }">`;
node += getTransform( o );
if ( o.isMesh === true && o.geometry !== null ) {
// function returns the id associated with the mesh and a "BufferGeometry" version
// of the geometry in case it's not a geometry.
const geomInfo = processGeometry( o.geometry );
const meshid = geomInfo.meshid;
const geometry = geomInfo.bufferGeometry;
// ids of the materials to bind to the geometry
let matids = null;
let matidsArray;
// get a list of materials to bind to the sub groups of the geometry.
// If the amount of subgroups is greater than the materials, than reuse
// the materials.
const mat = o.material || new MeshBasicMaterial();
const materials = Array.isArray( mat ) ? mat : [ mat ];
if ( geometry.groups.length > materials.length ) {
matidsArray = new Array( geometry.groups.length );
} else {
matidsArray = new Array( materials.length );
}
matids = matidsArray.fill().map( ( v, i ) => processMaterial( materials[ i % materials.length ] ) );
node +=
`<instance_geometry url="#${ meshid }">` +
(
matids.length > 0 ?
'<bind_material><technique_common>' +
matids.map( ( id, i ) =>
`<instance_material symbol="MESH_MATERIAL_${ i }" target="#${ id }" >` +
'<bind_vertex_input semantic="TEXCOORD" input_semantic="TEXCOORD" input_set="0" />' +
'</instance_material>'
).join( '' ) +
'</technique_common></bind_material>' :
''
) +
'</instance_geometry>';
}
o.children.forEach( c => node += processObject( c ) );
node += '</node>';
return node;
}
const geometryInfo = new WeakMap();
const materialMap = new WeakMap();
const imageMap = new WeakMap();
const textures = [];
const libraryImages = [];
const libraryGeometries = [];
const libraryEffects = [];
const libraryMaterials = [];
const libraryVisualScenes = processObject( object );
const specLink = version === '1.4.1' ? 'http://www.collada.org/2005/11/COLLADASchema' : 'https://www.khronos.org/collada/';
let dae =
'<?xml version="1.0" encoding="UTF-8" standalone="no" ?>' +
`<COLLADA xmlns="${ specLink }" version="${ version }">` +
'<asset>' +
(
'<contributor>' +
'<authoring_tool>three.js Collada Exporter</authoring_tool>' +
( options.author !== null ? `<author>${ options.author }</author>` : '' ) +
'</contributor>' +
`<created>${ ( new Date() ).toISOString() }</created>` +
`<modified>${ ( new Date() ).toISOString() }</modified>` +
( options.unitName !== null ? `<unit name="${ options.unitName }" meter="${ options.unitMeter }" />` : '' ) +
`<up_axis>${ options.upAxis }</up_axis>`
) +
'</asset>';
dae += `<library_images>${ libraryImages.join( '' ) }</library_images>`;
dae += `<library_effects>${ libraryEffects.join( '' ) }</library_effects>`;
dae += `<library_materials>${ libraryMaterials.join( '' ) }</library_materials>`;
dae += `<library_geometries>${ libraryGeometries.join( '' ) }</library_geometries>`;
dae += `<library_visual_scenes><visual_scene id="Scene" name="scene">${ libraryVisualScenes }</visual_scene></library_visual_scenes>`;
dae += '<scene><instance_visual_scene url="#Scene"/></scene>';
dae += '</COLLADA>';
const res = {
data: format( dae ),
textures
};
if ( typeof onDone === 'function' ) {
requestAnimationFrame( () => onDone( res ) );
}
return res;
}
}
export { ColladaExporter };

View File

@@ -0,0 +1,238 @@
/**
* Export draco compressed files from threejs geometry objects.
*
* Draco files are compressed and usually are smaller than conventional 3D file formats.
*
* The exporter receives a options object containing
* - decodeSpeed, indicates how to tune the encoder regarding decode speed (0 gives better speed but worst quality)
* - encodeSpeed, indicates how to tune the encoder parameters (0 gives better speed but worst quality)
* - encoderMethod
* - quantization, indicates the presision of each type of data stored in the draco file in the order (POSITION, NORMAL, COLOR, TEX_COORD, GENERIC)
* - exportUvs
* - exportNormals
*/
/* global DracoEncoderModule */
class DRACOExporter {
parse( object, options = {
decodeSpeed: 5,
encodeSpeed: 5,
encoderMethod: DRACOExporter.MESH_EDGEBREAKER_ENCODING,
quantization: [ 16, 8, 8, 8, 8 ],
exportUvs: true,
exportNormals: true,
exportColor: false,
} ) {
if ( object.isBufferGeometry === true ) {
throw new Error( 'DRACOExporter: The first parameter of parse() is now an instance of Mesh or Points.' );
}
if ( DracoEncoderModule === undefined ) {
throw new Error( 'THREE.DRACOExporter: required the draco_encoder to work.' );
}
const geometry = object.geometry;
const dracoEncoder = DracoEncoderModule();
const encoder = new dracoEncoder.Encoder();
let builder;
let dracoObject;
if ( geometry.isBufferGeometry !== true ) {
throw new Error( 'THREE.DRACOExporter.parse(geometry, options): geometry is not a THREE.BufferGeometry instance.' );
}
if ( object.isMesh === true ) {
builder = new dracoEncoder.MeshBuilder();
dracoObject = new dracoEncoder.Mesh();
const vertices = geometry.getAttribute( 'position' );
builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array );
const faces = geometry.getIndex();
if ( faces !== null ) {
builder.AddFacesToMesh( dracoObject, faces.count / 3, faces.array );
} else {
const faces = new ( vertices.count > 65535 ? Uint32Array : Uint16Array )( vertices.count );
for ( let i = 0; i < faces.length; i ++ ) {
faces[ i ] = i;
}
builder.AddFacesToMesh( dracoObject, vertices.count, faces );
}
if ( options.exportNormals === true ) {
const normals = geometry.getAttribute( 'normal' );
if ( normals !== undefined ) {
builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.NORMAL, normals.count, normals.itemSize, normals.array );
}
}
if ( options.exportUvs === true ) {
const uvs = geometry.getAttribute( 'uv' );
if ( uvs !== undefined ) {
builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.TEX_COORD, uvs.count, uvs.itemSize, uvs.array );
}
}
if ( options.exportColor === true ) {
const colors = geometry.getAttribute( 'color' );
if ( colors !== undefined ) {
builder.AddFloatAttributeToMesh( dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array );
}
}
} else if ( object.isPoints === true ) {
builder = new dracoEncoder.PointCloudBuilder();
dracoObject = new dracoEncoder.PointCloud();
const vertices = geometry.getAttribute( 'position' );
builder.AddFloatAttribute( dracoObject, dracoEncoder.POSITION, vertices.count, vertices.itemSize, vertices.array );
if ( options.exportColor === true ) {
const colors = geometry.getAttribute( 'color' );
if ( colors !== undefined ) {
builder.AddFloatAttribute( dracoObject, dracoEncoder.COLOR, colors.count, colors.itemSize, colors.array );
}
}
} else {
throw new Error( 'DRACOExporter: Unsupported object type.' );
}
//Compress using draco encoder
const encodedData = new dracoEncoder.DracoInt8Array();
//Sets the desired encoding and decoding speed for the given options from 0 (slowest speed, but the best compression) to 10 (fastest, but the worst compression).
const encodeSpeed = ( options.encodeSpeed !== undefined ) ? options.encodeSpeed : 5;
const decodeSpeed = ( options.decodeSpeed !== undefined ) ? options.decodeSpeed : 5;
encoder.SetSpeedOptions( encodeSpeed, decodeSpeed );
// Sets the desired encoding method for a given geometry.
if ( options.encoderMethod !== undefined ) {
encoder.SetEncodingMethod( options.encoderMethod );
}
// Sets the quantization (number of bits used to represent) compression options for a named attribute.
// The attribute values will be quantized in a box defined by the maximum extent of the attribute values.
if ( options.quantization !== undefined ) {
for ( let i = 0; i < 5; i ++ ) {
if ( options.quantization[ i ] !== undefined ) {
encoder.SetAttributeQuantization( i, options.quantization[ i ] );
}
}
}
let length;
if ( object.isMesh === true ) {
length = encoder.EncodeMeshToDracoBuffer( dracoObject, encodedData );
} else {
length = encoder.EncodePointCloudToDracoBuffer( dracoObject, true, encodedData );
}
dracoEncoder.destroy( dracoObject );
if ( length === 0 ) {
throw new Error( 'THREE.DRACOExporter: Draco encoding failed.' );
}
//Copy encoded data to buffer.
const outputData = new Int8Array( new ArrayBuffer( length ) );
for ( let i = 0; i < length; i ++ ) {
outputData[ i ] = encodedData.GetValue( i );
}
dracoEncoder.destroy( encodedData );
dracoEncoder.destroy( encoder );
dracoEncoder.destroy( builder );
return outputData;
}
}
// Encoder methods
DRACOExporter.MESH_EDGEBREAKER_ENCODING = 1;
DRACOExporter.MESH_SEQUENTIAL_ENCODING = 0;
// Geometry type
DRACOExporter.POINT_CLOUD = 0;
DRACOExporter.TRIANGULAR_MESH = 1;
// Attribute type
DRACOExporter.INVALID = - 1;
DRACOExporter.POSITION = 0;
DRACOExporter.NORMAL = 1;
DRACOExporter.COLOR = 2;
DRACOExporter.TEX_COORD = 3;
DRACOExporter.GENERIC = 4;
export { DRACOExporter };

View File

@@ -0,0 +1,507 @@
/**
* @author sciecode / https://github.com/sciecode
*
* EXR format references:
* https://www.openexr.com/documentation/openexrfilelayout.pdf
*/
import {
FloatType,
HalfFloatType,
RGBAFormat,
DataUtils,
} from 'three';
import * as fflate from '../libs/fflate.module.js';
const textEncoder = new TextEncoder();
const NO_COMPRESSION = 0;
const ZIPS_COMPRESSION = 2;
const ZIP_COMPRESSION = 3;
class EXRExporter {
parse( renderer, renderTarget, options ) {
if ( ! supported( renderer, renderTarget ) ) return undefined;
const info = buildInfo( renderTarget, options ),
dataBuffer = getPixelData( renderer, renderTarget, info ),
rawContentBuffer = reorganizeDataBuffer( dataBuffer, info ),
chunks = compressData( rawContentBuffer, info );
return fillData( chunks, info );
}
}
function supported( renderer, renderTarget ) {
if ( ! renderer || ! renderer.isWebGLRenderer ) {
console.error( 'EXRExporter.parse: Unsupported first parameter, expected instance of WebGLRenderer.' );
return false;
}
if ( ! renderTarget || ! renderTarget.isWebGLRenderTarget ) {
console.error( 'EXRExporter.parse: Unsupported second parameter, expected instance of WebGLRenderTarget.' );
return false;
}
if ( renderTarget.texture.type !== FloatType && renderTarget.texture.type !== HalfFloatType ) {
console.error( 'EXRExporter.parse: Unsupported WebGLRenderTarget texture type.' );
return false;
}
if ( renderTarget.texture.format !== RGBAFormat ) {
console.error( 'EXRExporter.parse: Unsupported WebGLRenderTarget texture format, expected RGBAFormat.' );
return false;
}
return true;
}
function buildInfo( renderTarget, options = {} ) {
const compressionSizes = {
0: 1,
2: 1,
3: 16
};
const WIDTH = renderTarget.width,
HEIGHT = renderTarget.height,
TYPE = renderTarget.texture.type,
FORMAT = renderTarget.texture.format,
ENCODING = renderTarget.texture.encoding,
COMPRESSION = ( options.compression !== undefined ) ? options.compression : ZIP_COMPRESSION,
EXPORTER_TYPE = ( options.type !== undefined ) ? options.type : HalfFloatType,
OUT_TYPE = ( EXPORTER_TYPE === FloatType ) ? 2 : 1,
COMPRESSION_SIZE = compressionSizes[ COMPRESSION ],
NUM_CHANNELS = 4;
return {
width: WIDTH,
height: HEIGHT,
type: TYPE,
format: FORMAT,
encoding: ENCODING,
compression: COMPRESSION,
blockLines: COMPRESSION_SIZE,
dataType: OUT_TYPE,
dataSize: 2 * OUT_TYPE,
numBlocks: Math.ceil( HEIGHT / COMPRESSION_SIZE ),
numInputChannels: 4,
numOutputChannels: NUM_CHANNELS,
};
}
function getPixelData( renderer, rtt, info ) {
let dataBuffer;
if ( info.type === FloatType ) {
dataBuffer = new Float32Array( info.width * info.height * info.numInputChannels );
} else {
dataBuffer = new Uint16Array( info.width * info.height * info.numInputChannels );
}
renderer.readRenderTargetPixels( rtt, 0, 0, info.width, info.height, dataBuffer );
return dataBuffer;
}
function reorganizeDataBuffer( inBuffer, info ) {
const w = info.width,
h = info.height,
dec = { r: 0, g: 0, b: 0, a: 0 },
offset = { value: 0 },
cOffset = ( info.numOutputChannels == 4 ) ? 1 : 0,
getValue = ( info.type == FloatType ) ? getFloat32 : getFloat16,
setValue = ( info.dataType == 1 ) ? setFloat16 : setFloat32,
outBuffer = new Uint8Array( info.width * info.height * info.numOutputChannels * info.dataSize ),
dv = new DataView( outBuffer.buffer );
for ( let y = 0; y < h; ++ y ) {
for ( let x = 0; x < w; ++ x ) {
const i = y * w * 4 + x * 4;
const r = getValue( inBuffer, i );
const g = getValue( inBuffer, i + 1 );
const b = getValue( inBuffer, i + 2 );
const a = getValue( inBuffer, i + 3 );
const line = ( h - y - 1 ) * w * ( 3 + cOffset ) * info.dataSize;
decodeLinear( dec, r, g, b, a );
offset.value = line + x * info.dataSize;
setValue( dv, dec.a, offset );
offset.value = line + ( cOffset ) * w * info.dataSize + x * info.dataSize;
setValue( dv, dec.b, offset );
offset.value = line + ( 1 + cOffset ) * w * info.dataSize + x * info.dataSize;
setValue( dv, dec.g, offset );
offset.value = line + ( 2 + cOffset ) * w * info.dataSize + x * info.dataSize;
setValue( dv, dec.r, offset );
}
}
return outBuffer;
}
function compressData( inBuffer, info ) {
let compress,
tmpBuffer,
sum = 0;
const chunks = { data: new Array(), totalSize: 0 },
size = info.width * info.numOutputChannels * info.blockLines * info.dataSize;
switch ( info.compression ) {
case 0:
compress = compressNONE;
break;
case 2:
case 3:
compress = compressZIP;
break;
}
if ( info.compression !== 0 ) {
tmpBuffer = new Uint8Array( size );
}
for ( let i = 0; i < info.numBlocks; ++ i ) {
const arr = inBuffer.subarray( size * i, size * ( i + 1 ) );
const block = compress( arr, tmpBuffer );
sum += block.length;
chunks.data.push( { dataChunk: block, size: block.length } );
}
chunks.totalSize = sum;
return chunks;
}
function compressNONE( data ) {
return data;
}
function compressZIP( data, tmpBuffer ) {
//
// Reorder the pixel data.
//
let t1 = 0,
t2 = Math.floor( ( data.length + 1 ) / 2 ),
s = 0;
const stop = data.length - 1;
while ( true ) {
if ( s > stop ) break;
tmpBuffer[ t1 ++ ] = data[ s ++ ];
if ( s > stop ) break;
tmpBuffer[ t2 ++ ] = data[ s ++ ];
}
//
// Predictor.
//
let p = tmpBuffer[ 0 ];
for ( let t = 1; t < tmpBuffer.length; t ++ ) {
const d = tmpBuffer[ t ] - p + ( 128 + 256 );
p = tmpBuffer[ t ];
tmpBuffer[ t ] = d;
}
if ( typeof fflate === 'undefined' ) {
console.error( 'THREE.EXRLoader: External \`fflate.module.js\` required' );
}
const deflate = fflate.zlibSync( tmpBuffer ); // eslint-disable-line no-undef
return deflate;
}
function fillHeader( outBuffer, chunks, info ) {
const offset = { value: 0 };
const dv = new DataView( outBuffer.buffer );
setUint32( dv, 20000630, offset ); // magic
setUint32( dv, 2, offset ); // mask
// = HEADER =
setString( dv, 'compression', offset );
setString( dv, 'compression', offset );
setUint32( dv, 1, offset );
setUint8( dv, info.compression, offset );
setString( dv, 'screenWindowCenter', offset );
setString( dv, 'v2f', offset );
setUint32( dv, 8, offset );
setUint32( dv, 0, offset );
setUint32( dv, 0, offset );
setString( dv, 'screenWindowWidth', offset );
setString( dv, 'float', offset );
setUint32( dv, 4, offset );
setFloat32( dv, 1.0, offset );
setString( dv, 'pixelAspectRatio', offset );
setString( dv, 'float', offset );
setUint32( dv, 4, offset );
setFloat32( dv, 1.0, offset );
setString( dv, 'lineOrder', offset );
setString( dv, 'lineOrder', offset );
setUint32( dv, 1, offset );
setUint8( dv, 0, offset );
setString( dv, 'dataWindow', offset );
setString( dv, 'box2i', offset );
setUint32( dv, 16, offset );
setUint32( dv, 0, offset );
setUint32( dv, 0, offset );
setUint32( dv, info.width - 1, offset );
setUint32( dv, info.height - 1, offset );
setString( dv, 'displayWindow', offset );
setString( dv, 'box2i', offset );
setUint32( dv, 16, offset );
setUint32( dv, 0, offset );
setUint32( dv, 0, offset );
setUint32( dv, info.width - 1, offset );
setUint32( dv, info.height - 1, offset );
setString( dv, 'channels', offset );
setString( dv, 'chlist', offset );
setUint32( dv, info.numOutputChannels * 18 + 1, offset );
setString( dv, 'A', offset );
setUint32( dv, info.dataType, offset );
offset.value += 4;
setUint32( dv, 1, offset );
setUint32( dv, 1, offset );
setString( dv, 'B', offset );
setUint32( dv, info.dataType, offset );
offset.value += 4;
setUint32( dv, 1, offset );
setUint32( dv, 1, offset );
setString( dv, 'G', offset );
setUint32( dv, info.dataType, offset );
offset.value += 4;
setUint32( dv, 1, offset );
setUint32( dv, 1, offset );
setString( dv, 'R', offset );
setUint32( dv, info.dataType, offset );
offset.value += 4;
setUint32( dv, 1, offset );
setUint32( dv, 1, offset );
setUint8( dv, 0, offset );
// null-byte
setUint8( dv, 0, offset );
// = OFFSET TABLE =
let sum = offset.value + info.numBlocks * 8;
for ( let i = 0; i < chunks.data.length; ++ i ) {
setUint64( dv, sum, offset );
sum += chunks.data[ i ].size + 8;
}
}
function fillData( chunks, info ) {
const TableSize = info.numBlocks * 8,
HeaderSize = 259 + ( 18 * info.numOutputChannels ), // 259 + 18 * chlist
offset = { value: HeaderSize + TableSize },
outBuffer = new Uint8Array( HeaderSize + TableSize + chunks.totalSize + info.numBlocks * 8 ),
dv = new DataView( outBuffer.buffer );
fillHeader( outBuffer, chunks, info );
for ( let i = 0; i < chunks.data.length; ++ i ) {
const data = chunks.data[ i ].dataChunk;
const size = chunks.data[ i ].size;
setUint32( dv, i * info.blockLines, offset );
setUint32( dv, size, offset );
outBuffer.set( data, offset.value );
offset.value += size;
}
return outBuffer;
}
function decodeLinear( dec, r, g, b, a ) {
dec.r = r;
dec.g = g;
dec.b = b;
dec.a = a;
}
// function decodeSRGB( dec, r, g, b, a ) {
// dec.r = r > 0.04045 ? Math.pow( r * 0.9478672986 + 0.0521327014, 2.4 ) : r * 0.0773993808;
// dec.g = g > 0.04045 ? Math.pow( g * 0.9478672986 + 0.0521327014, 2.4 ) : g * 0.0773993808;
// dec.b = b > 0.04045 ? Math.pow( b * 0.9478672986 + 0.0521327014, 2.4 ) : b * 0.0773993808;
// dec.a = a;
// }
function setUint8( dv, value, offset ) {
dv.setUint8( offset.value, value );
offset.value += 1;
}
function setUint32( dv, value, offset ) {
dv.setUint32( offset.value, value, true );
offset.value += 4;
}
function setFloat16( dv, value, offset ) {
dv.setUint16( offset.value, DataUtils.toHalfFloat( value ), true );
offset.value += 2;
}
function setFloat32( dv, value, offset ) {
dv.setFloat32( offset.value, value, true );
offset.value += 4;
}
function setUint64( dv, value, offset ) {
dv.setBigUint64( offset.value, BigInt( value ), true );
offset.value += 8;
}
function setString( dv, string, offset ) {
const tmp = textEncoder.encode( string + '\0' );
for ( let i = 0; i < tmp.length; ++ i ) {
setUint8( dv, tmp[ i ], offset );
}
}
function decodeFloat16( binary ) {
const exponent = ( binary & 0x7C00 ) >> 10,
fraction = binary & 0x03FF;
return ( binary >> 15 ? - 1 : 1 ) * (
exponent ?
(
exponent === 0x1F ?
fraction ? NaN : Infinity :
Math.pow( 2, exponent - 15 ) * ( 1 + fraction / 0x400 )
) :
6.103515625e-5 * ( fraction / 0x400 )
);
}
function getFloat16( arr, i ) {
return decodeFloat16( arr[ i ] );
}
function getFloat32( arr, i ) {
return arr[ i ];
}
export { EXRExporter, NO_COMPRESSION, ZIP_COMPRESSION, ZIPS_COMPRESSION };

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,217 @@
import {
Matrix4,
Quaternion,
Vector3
} from 'three';
import { MMDParser } from '../libs/mmdparser.module.js';
/**
* Dependencies
* - mmd-parser https://github.com/takahirox/mmd-parser
*/
class MMDExporter {
/* TODO: implement
// mesh -> pmd
this.parsePmd = function ( object ) {
};
*/
/* TODO: implement
// mesh -> pmx
this.parsePmx = function ( object ) {
};
*/
/* TODO: implement
// animation + skeleton -> vmd
this.parseVmd = function ( object ) {
};
*/
/*
* skeleton -> vpd
* Returns Shift_JIS encoded Uint8Array. Otherwise return strings.
*/
parseVpd( skin, outputShiftJis, useOriginalBones ) {
if ( skin.isSkinnedMesh !== true ) {
console.warn( 'THREE.MMDExporter: parseVpd() requires SkinnedMesh instance.' );
return null;
}
function toStringsFromNumber( num ) {
if ( Math.abs( num ) < 1e-6 ) num = 0;
let a = num.toString();
if ( a.indexOf( '.' ) === - 1 ) {
a += '.';
}
a += '000000';
const index = a.indexOf( '.' );
const d = a.slice( 0, index );
const p = a.slice( index + 1, index + 7 );
return d + '.' + p;
}
function toStringsFromArray( array ) {
const a = [];
for ( let i = 0, il = array.length; i < il; i ++ ) {
a.push( toStringsFromNumber( array[ i ] ) );
}
return a.join( ',' );
}
skin.updateMatrixWorld( true );
const bones = skin.skeleton.bones;
const bones2 = getBindBones( skin );
const position = new Vector3();
const quaternion = new Quaternion();
const quaternion2 = new Quaternion();
const matrix = new Matrix4();
const array = [];
array.push( 'Vocaloid Pose Data file' );
array.push( '' );
array.push( ( skin.name !== '' ? skin.name.replace( /\s/g, '_' ) : 'skin' ) + '.osm;' );
array.push( bones.length + ';' );
array.push( '' );
for ( let i = 0, il = bones.length; i < il; i ++ ) {
const bone = bones[ i ];
const bone2 = bones2[ i ];
/*
* use the bone matrix saved before solving IK.
* see CCDIKSolver for the detail.
*/
if ( useOriginalBones === true &&
bone.userData.ik !== undefined &&
bone.userData.ik.originalMatrix !== undefined ) {
matrix.fromArray( bone.userData.ik.originalMatrix );
} else {
matrix.copy( bone.matrix );
}
position.setFromMatrixPosition( matrix );
quaternion.setFromRotationMatrix( matrix );
const pArray = position.sub( bone2.position ).toArray();
const qArray = quaternion2.copy( bone2.quaternion ).conjugate().multiply( quaternion ).toArray();
// right to left
pArray[ 2 ] = - pArray[ 2 ];
qArray[ 0 ] = - qArray[ 0 ];
qArray[ 1 ] = - qArray[ 1 ];
array.push( 'Bone' + i + '{' + bone.name );
array.push( ' ' + toStringsFromArray( pArray ) + ';' );
array.push( ' ' + toStringsFromArray( qArray ) + ';' );
array.push( '}' );
array.push( '' );
}
array.push( '' );
const lines = array.join( '\n' );
return ( outputShiftJis === true ) ? unicodeToShiftjis( lines ) : lines;
}
}
// Unicode to Shift_JIS table
let u2sTable;
function unicodeToShiftjis( str ) {
if ( u2sTable === undefined ) {
const encoder = new MMDParser.CharsetEncoder(); // eslint-disable-line no-undef
const table = encoder.s2uTable;
u2sTable = {};
const keys = Object.keys( table );
for ( let i = 0, il = keys.length; i < il; i ++ ) {
let key = keys[ i ];
const value = table[ key ];
key = parseInt( key );
u2sTable[ value ] = key;
}
}
const array = [];
for ( let i = 0, il = str.length; i < il; i ++ ) {
const code = str.charCodeAt( i );
const value = u2sTable[ code ];
if ( value === undefined ) {
throw new Error( 'cannot convert charcode 0x' + code.toString( 16 ) );
} else if ( value > 0xff ) {
array.push( ( value >> 8 ) & 0xff );
array.push( value & 0xff );
} else {
array.push( value & 0xff );
}
}
return new Uint8Array( array );
}
function getBindBones( skin ) {
// any more efficient ways?
const poseSkin = skin.clone();
poseSkin.pose();
return poseSkin.skeleton.bones;
}
export { MMDExporter };

View File

@@ -0,0 +1,309 @@
import {
Color,
Matrix3,
Vector2,
Vector3
} from 'three';
class OBJExporter {
parse( object ) {
let output = '';
let indexVertex = 0;
let indexVertexUvs = 0;
let indexNormals = 0;
const vertex = new Vector3();
const color = new Color();
const normal = new Vector3();
const uv = new Vector2();
const face = [];
function parseMesh( mesh ) {
let nbVertex = 0;
let nbNormals = 0;
let nbVertexUvs = 0;
const geometry = mesh.geometry;
const normalMatrixWorld = new Matrix3();
if ( geometry.isBufferGeometry !== true ) {
throw new Error( 'THREE.OBJExporter: Geometry is not of type THREE.BufferGeometry.' );
}
// shortcuts
const vertices = geometry.getAttribute( 'position' );
const normals = geometry.getAttribute( 'normal' );
const uvs = geometry.getAttribute( 'uv' );
const indices = geometry.getIndex();
// name of the mesh object
output += 'o ' + mesh.name + '\n';
// name of the mesh material
if ( mesh.material && mesh.material.name ) {
output += 'usemtl ' + mesh.material.name + '\n';
}
// vertices
if ( vertices !== undefined ) {
for ( let i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) {
vertex.x = vertices.getX( i );
vertex.y = vertices.getY( i );
vertex.z = vertices.getZ( i );
// transform the vertex to world space
vertex.applyMatrix4( mesh.matrixWorld );
// transform the vertex to export format
output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n';
}
}
// uvs
if ( uvs !== undefined ) {
for ( let i = 0, l = uvs.count; i < l; i ++, nbVertexUvs ++ ) {
uv.x = uvs.getX( i );
uv.y = uvs.getY( i );
// transform the uv to export format
output += 'vt ' + uv.x + ' ' + uv.y + '\n';
}
}
// normals
if ( normals !== undefined ) {
normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
for ( let i = 0, l = normals.count; i < l; i ++, nbNormals ++ ) {
normal.x = normals.getX( i );
normal.y = normals.getY( i );
normal.z = normals.getZ( i );
// transform the normal to world space
normal.applyMatrix3( normalMatrixWorld ).normalize();
// transform the normal to export format
output += 'vn ' + normal.x + ' ' + normal.y + ' ' + normal.z + '\n';
}
}
// faces
if ( indices !== null ) {
for ( let i = 0, l = indices.count; i < l; i += 3 ) {
for ( let m = 0; m < 3; m ++ ) {
const j = indices.getX( i + m ) + 1;
face[ m ] = ( indexVertex + j ) + ( normals || uvs ? '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + ( normals ? '/' + ( indexNormals + j ) : '' ) : '' );
}
// transform the face to export format
output += 'f ' + face.join( ' ' ) + '\n';
}
} else {
for ( let i = 0, l = vertices.count; i < l; i += 3 ) {
for ( let m = 0; m < 3; m ++ ) {
const j = i + m + 1;
face[ m ] = ( indexVertex + j ) + ( normals || uvs ? '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + ( normals ? '/' + ( indexNormals + j ) : '' ) : '' );
}
// transform the face to export format
output += 'f ' + face.join( ' ' ) + '\n';
}
}
// update index
indexVertex += nbVertex;
indexVertexUvs += nbVertexUvs;
indexNormals += nbNormals;
}
function parseLine( line ) {
let nbVertex = 0;
const geometry = line.geometry;
const type = line.type;
if ( geometry.isBufferGeometry !== true ) {
throw new Error( 'THREE.OBJExporter: Geometry is not of type THREE.BufferGeometry.' );
}
// shortcuts
const vertices = geometry.getAttribute( 'position' );
// name of the line object
output += 'o ' + line.name + '\n';
if ( vertices !== undefined ) {
for ( let i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) {
vertex.x = vertices.getX( i );
vertex.y = vertices.getY( i );
vertex.z = vertices.getZ( i );
// transform the vertex to world space
vertex.applyMatrix4( line.matrixWorld );
// transform the vertex to export format
output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n';
}
}
if ( type === 'Line' ) {
output += 'l ';
for ( let j = 1, l = vertices.count; j <= l; j ++ ) {
output += ( indexVertex + j ) + ' ';
}
output += '\n';
}
if ( type === 'LineSegments' ) {
for ( let j = 1, k = j + 1, l = vertices.count; j < l; j += 2, k = j + 1 ) {
output += 'l ' + ( indexVertex + j ) + ' ' + ( indexVertex + k ) + '\n';
}
}
// update index
indexVertex += nbVertex;
}
function parsePoints( points ) {
let nbVertex = 0;
const geometry = points.geometry;
if ( geometry.isBufferGeometry !== true ) {
throw new Error( 'THREE.OBJExporter: Geometry is not of type THREE.BufferGeometry.' );
}
const vertices = geometry.getAttribute( 'position' );
const colors = geometry.getAttribute( 'color' );
output += 'o ' + points.name + '\n';
if ( vertices !== undefined ) {
for ( let i = 0, l = vertices.count; i < l; i ++, nbVertex ++ ) {
vertex.fromBufferAttribute( vertices, i );
vertex.applyMatrix4( points.matrixWorld );
output += 'v ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z;
if ( colors !== undefined ) {
color.fromBufferAttribute( colors, i ).convertLinearToSRGB();
output += ' ' + color.r + ' ' + color.g + ' ' + color.b;
}
output += '\n';
}
output += 'p ';
for ( let j = 1, l = vertices.count; j <= l; j ++ ) {
output += ( indexVertex + j ) + ' ';
}
output += '\n';
}
// update index
indexVertex += nbVertex;
}
object.traverse( function ( child ) {
if ( child.isMesh === true ) {
parseMesh( child );
}
if ( child.isLine === true ) {
parseLine( child );
}
if ( child.isPoints === true ) {
parsePoints( child );
}
} );
return output;
}
}
export { OBJExporter };

View File

@@ -0,0 +1,537 @@
import {
Matrix3,
Vector3,
Color
} from 'three';
/**
* https://github.com/gkjohnson/ply-exporter-js
*
* Usage:
* const exporter = new PLYExporter();
*
* // second argument is a list of options
* exporter.parse(mesh, data => console.log(data), { binary: true, excludeAttributes: [ 'color' ], littleEndian: true });
*
* Format Definition:
* http://paulbourke.net/dataformats/ply/
*/
class PLYExporter {
parse( object, onDone, options ) {
if ( onDone && typeof onDone === 'object' ) {
console.warn( 'THREE.PLYExporter: The options parameter is now the third argument to the "parse" function. See the documentation for the new API.' );
options = onDone;
onDone = undefined;
}
// Iterate over the valid meshes in the object
function traverseMeshes( cb ) {
object.traverse( function ( child ) {
if ( child.isMesh === true ) {
const mesh = child;
const geometry = mesh.geometry;
if ( geometry.isBufferGeometry !== true ) {
throw new Error( 'THREE.PLYExporter: Geometry is not of type THREE.BufferGeometry.' );
}
if ( geometry.hasAttribute( 'position' ) === true ) {
cb( mesh, geometry );
}
}
} );
}
// Default options
const defaultOptions = {
binary: false,
excludeAttributes: [], // normal, uv, color, index
littleEndian: false
};
options = Object.assign( defaultOptions, options );
const excludeAttributes = options.excludeAttributes;
let includeNormals = false;
let includeColors = false;
let includeUVs = false;
// count the vertices, check which properties are used,
// and cache the BufferGeometry
let vertexCount = 0;
let faceCount = 0;
object.traverse( function ( child ) {
if ( child.isMesh === true ) {
const mesh = child;
const geometry = mesh.geometry;
if ( geometry.isBufferGeometry !== true ) {
throw new Error( 'THREE.PLYExporter: Geometry is not of type THREE.BufferGeometry.' );
}
const vertices = geometry.getAttribute( 'position' );
const normals = geometry.getAttribute( 'normal' );
const uvs = geometry.getAttribute( 'uv' );
const colors = geometry.getAttribute( 'color' );
const indices = geometry.getIndex();
if ( vertices === undefined ) {
return;
}
vertexCount += vertices.count;
faceCount += indices ? indices.count / 3 : vertices.count / 3;
if ( normals !== undefined ) includeNormals = true;
if ( uvs !== undefined ) includeUVs = true;
if ( colors !== undefined ) includeColors = true;
}
} );
const tempColor = new Color();
const includeIndices = excludeAttributes.indexOf( 'index' ) === - 1;
includeNormals = includeNormals && excludeAttributes.indexOf( 'normal' ) === - 1;
includeColors = includeColors && excludeAttributes.indexOf( 'color' ) === - 1;
includeUVs = includeUVs && excludeAttributes.indexOf( 'uv' ) === - 1;
if ( includeIndices && faceCount !== Math.floor( faceCount ) ) {
// point cloud meshes will not have an index array and may not have a
// number of vertices that is divisble by 3 (and therefore representable
// as triangles)
console.error(
'PLYExporter: Failed to generate a valid PLY file with triangle indices because the ' +
'number of indices is not divisible by 3.'
);
return null;
}
const indexByteCount = 4;
let header =
'ply\n' +
`format ${ options.binary ? ( options.littleEndian ? 'binary_little_endian' : 'binary_big_endian' ) : 'ascii' } 1.0\n` +
`element vertex ${vertexCount}\n` +
// position
'property float x\n' +
'property float y\n' +
'property float z\n';
if ( includeNormals === true ) {
// normal
header +=
'property float nx\n' +
'property float ny\n' +
'property float nz\n';
}
if ( includeUVs === true ) {
// uvs
header +=
'property float s\n' +
'property float t\n';
}
if ( includeColors === true ) {
// colors
header +=
'property uchar red\n' +
'property uchar green\n' +
'property uchar blue\n';
}
if ( includeIndices === true ) {
// faces
header +=
`element face ${faceCount}\n` +
'property list uchar int vertex_index\n';
}
header += 'end_header\n';
// Generate attribute data
const vertex = new Vector3();
const normalMatrixWorld = new Matrix3();
let result = null;
if ( options.binary === true ) {
// Binary File Generation
const headerBin = new TextEncoder().encode( header );
// 3 position values at 4 bytes
// 3 normal values at 4 bytes
// 3 color channels with 1 byte
// 2 uv values at 4 bytes
const vertexListLength = vertexCount * ( 4 * 3 + ( includeNormals ? 4 * 3 : 0 ) + ( includeColors ? 3 : 0 ) + ( includeUVs ? 4 * 2 : 0 ) );
// 1 byte shape desciptor
// 3 vertex indices at ${indexByteCount} bytes
const faceListLength = includeIndices ? faceCount * ( indexByteCount * 3 + 1 ) : 0;
const output = new DataView( new ArrayBuffer( headerBin.length + vertexListLength + faceListLength ) );
new Uint8Array( output.buffer ).set( headerBin, 0 );
let vOffset = headerBin.length;
let fOffset = headerBin.length + vertexListLength;
let writtenVertices = 0;
traverseMeshes( function ( mesh, geometry ) {
const vertices = geometry.getAttribute( 'position' );
const normals = geometry.getAttribute( 'normal' );
const uvs = geometry.getAttribute( 'uv' );
const colors = geometry.getAttribute( 'color' );
const indices = geometry.getIndex();
normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
for ( let i = 0, l = vertices.count; i < l; i ++ ) {
vertex.x = vertices.getX( i );
vertex.y = vertices.getY( i );
vertex.z = vertices.getZ( i );
vertex.applyMatrix4( mesh.matrixWorld );
// Position information
output.setFloat32( vOffset, vertex.x, options.littleEndian );
vOffset += 4;
output.setFloat32( vOffset, vertex.y, options.littleEndian );
vOffset += 4;
output.setFloat32( vOffset, vertex.z, options.littleEndian );
vOffset += 4;
// Normal information
if ( includeNormals === true ) {
if ( normals != null ) {
vertex.x = normals.getX( i );
vertex.y = normals.getY( i );
vertex.z = normals.getZ( i );
vertex.applyMatrix3( normalMatrixWorld ).normalize();
output.setFloat32( vOffset, vertex.x, options.littleEndian );
vOffset += 4;
output.setFloat32( vOffset, vertex.y, options.littleEndian );
vOffset += 4;
output.setFloat32( vOffset, vertex.z, options.littleEndian );
vOffset += 4;
} else {
output.setFloat32( vOffset, 0, options.littleEndian );
vOffset += 4;
output.setFloat32( vOffset, 0, options.littleEndian );
vOffset += 4;
output.setFloat32( vOffset, 0, options.littleEndian );
vOffset += 4;
}
}
// UV information
if ( includeUVs === true ) {
if ( uvs != null ) {
output.setFloat32( vOffset, uvs.getX( i ), options.littleEndian );
vOffset += 4;
output.setFloat32( vOffset, uvs.getY( i ), options.littleEndian );
vOffset += 4;
} else {
output.setFloat32( vOffset, 0, options.littleEndian );
vOffset += 4;
output.setFloat32( vOffset, 0, options.littleEndian );
vOffset += 4;
}
}
// Color information
if ( includeColors === true ) {
if ( colors != null ) {
tempColor
.fromBufferAttribute( colors, i )
.convertLinearToSRGB();
output.setUint8( vOffset, Math.floor( tempColor.r * 255 ) );
vOffset += 1;
output.setUint8( vOffset, Math.floor( tempColor.g * 255 ) );
vOffset += 1;
output.setUint8( vOffset, Math.floor( tempColor.b * 255 ) );
vOffset += 1;
} else {
output.setUint8( vOffset, 255 );
vOffset += 1;
output.setUint8( vOffset, 255 );
vOffset += 1;
output.setUint8( vOffset, 255 );
vOffset += 1;
}
}
}
if ( includeIndices === true ) {
// Create the face list
if ( indices !== null ) {
for ( let i = 0, l = indices.count; i < l; i += 3 ) {
output.setUint8( fOffset, 3 );
fOffset += 1;
output.setUint32( fOffset, indices.getX( i + 0 ) + writtenVertices, options.littleEndian );
fOffset += indexByteCount;
output.setUint32( fOffset, indices.getX( i + 1 ) + writtenVertices, options.littleEndian );
fOffset += indexByteCount;
output.setUint32( fOffset, indices.getX( i + 2 ) + writtenVertices, options.littleEndian );
fOffset += indexByteCount;
}
} else {
for ( let i = 0, l = vertices.count; i < l; i += 3 ) {
output.setUint8( fOffset, 3 );
fOffset += 1;
output.setUint32( fOffset, writtenVertices + i, options.littleEndian );
fOffset += indexByteCount;
output.setUint32( fOffset, writtenVertices + i + 1, options.littleEndian );
fOffset += indexByteCount;
output.setUint32( fOffset, writtenVertices + i + 2, options.littleEndian );
fOffset += indexByteCount;
}
}
}
// Save the amount of verts we've already written so we can offset
// the face index on the next mesh
writtenVertices += vertices.count;
} );
result = output.buffer;
} else {
// Ascii File Generation
// count the number of vertices
let writtenVertices = 0;
let vertexList = '';
let faceList = '';
traverseMeshes( function ( mesh, geometry ) {
const vertices = geometry.getAttribute( 'position' );
const normals = geometry.getAttribute( 'normal' );
const uvs = geometry.getAttribute( 'uv' );
const colors = geometry.getAttribute( 'color' );
const indices = geometry.getIndex();
normalMatrixWorld.getNormalMatrix( mesh.matrixWorld );
// form each line
for ( let i = 0, l = vertices.count; i < l; i ++ ) {
vertex.x = vertices.getX( i );
vertex.y = vertices.getY( i );
vertex.z = vertices.getZ( i );
vertex.applyMatrix4( mesh.matrixWorld );
// Position information
let line =
vertex.x + ' ' +
vertex.y + ' ' +
vertex.z;
// Normal information
if ( includeNormals === true ) {
if ( normals != null ) {
vertex.x = normals.getX( i );
vertex.y = normals.getY( i );
vertex.z = normals.getZ( i );
vertex.applyMatrix3( normalMatrixWorld ).normalize();
line += ' ' +
vertex.x + ' ' +
vertex.y + ' ' +
vertex.z;
} else {
line += ' 0 0 0';
}
}
// UV information
if ( includeUVs === true ) {
if ( uvs != null ) {
line += ' ' +
uvs.getX( i ) + ' ' +
uvs.getY( i );
} else {
line += ' 0 0';
}
}
// Color information
if ( includeColors === true ) {
if ( colors != null ) {
tempColor
.fromBufferAttribute( colors, i )
.convertLinearToSRGB();
line += ' ' +
Math.floor( tempColor.r * 255 ) + ' ' +
Math.floor( tempColor.g * 255 ) + ' ' +
Math.floor( tempColor.b * 255 );
} else {
line += ' 255 255 255';
}
}
vertexList += line + '\n';
}
// Create the face list
if ( includeIndices === true ) {
if ( indices !== null ) {
for ( let i = 0, l = indices.count; i < l; i += 3 ) {
faceList += `3 ${ indices.getX( i + 0 ) + writtenVertices }`;
faceList += ` ${ indices.getX( i + 1 ) + writtenVertices }`;
faceList += ` ${ indices.getX( i + 2 ) + writtenVertices }\n`;
}
} else {
for ( let i = 0, l = vertices.count; i < l; i += 3 ) {
faceList += `3 ${ writtenVertices + i } ${ writtenVertices + i + 1 } ${ writtenVertices + i + 2 }\n`;
}
}
faceCount += indices ? indices.count / 3 : vertices.count / 3;
}
writtenVertices += vertices.count;
} );
result = `${ header }${vertexList}${ includeIndices ? `${faceList}\n` : '\n' }`;
}
if ( typeof onDone === 'function' ) requestAnimationFrame( () => onDone( result ) );
return result;
}
}
export { PLYExporter };

View File

@@ -0,0 +1,203 @@
import {
Vector3
} from 'three';
/**
* Usage:
* const exporter = new STLExporter();
*
* // second argument is a list of options
* const data = exporter.parse( mesh, { binary: true } );
*
*/
class STLExporter {
parse( scene, options = {} ) {
const binary = options.binary !== undefined ? options.binary : false;
//
const objects = [];
let triangles = 0;
scene.traverse( function ( object ) {
if ( object.isMesh ) {
const geometry = object.geometry;
if ( geometry.isBufferGeometry !== true ) {
throw new Error( 'THREE.STLExporter: Geometry is not of type THREE.BufferGeometry.' );
}
const index = geometry.index;
const positionAttribute = geometry.getAttribute( 'position' );
triangles += ( index !== null ) ? ( index.count / 3 ) : ( positionAttribute.count / 3 );
objects.push( {
object3d: object,
geometry: geometry
} );
}
} );
let output;
let offset = 80; // skip header
if ( binary === true ) {
const bufferLength = triangles * 2 + triangles * 3 * 4 * 4 + 80 + 4;
const arrayBuffer = new ArrayBuffer( bufferLength );
output = new DataView( arrayBuffer );
output.setUint32( offset, triangles, true ); offset += 4;
} else {
output = '';
output += 'solid exported\n';
}
const vA = new Vector3();
const vB = new Vector3();
const vC = new Vector3();
const cb = new Vector3();
const ab = new Vector3();
const normal = new Vector3();
for ( let i = 0, il = objects.length; i < il; i ++ ) {
const object = objects[ i ].object3d;
const geometry = objects[ i ].geometry;
const index = geometry.index;
const positionAttribute = geometry.getAttribute( 'position' );
if ( index !== null ) {
// indexed geometry
for ( let j = 0; j < index.count; j += 3 ) {
const a = index.getX( j + 0 );
const b = index.getX( j + 1 );
const c = index.getX( j + 2 );
writeFace( a, b, c, positionAttribute, object );
}
} else {
// non-indexed geometry
for ( let j = 0; j < positionAttribute.count; j += 3 ) {
const a = j + 0;
const b = j + 1;
const c = j + 2;
writeFace( a, b, c, positionAttribute, object );
}
}
}
if ( binary === false ) {
output += 'endsolid exported\n';
}
return output;
function writeFace( a, b, c, positionAttribute, object ) {
vA.fromBufferAttribute( positionAttribute, a );
vB.fromBufferAttribute( positionAttribute, b );
vC.fromBufferAttribute( positionAttribute, c );
if ( object.isSkinnedMesh === true ) {
object.boneTransform( a, vA );
object.boneTransform( b, vB );
object.boneTransform( c, vC );
}
vA.applyMatrix4( object.matrixWorld );
vB.applyMatrix4( object.matrixWorld );
vC.applyMatrix4( object.matrixWorld );
writeNormal( vA, vB, vC );
writeVertex( vA );
writeVertex( vB );
writeVertex( vC );
if ( binary === true ) {
output.setUint16( offset, 0, true ); offset += 2;
} else {
output += '\t\tendloop\n';
output += '\tendfacet\n';
}
}
function writeNormal( vA, vB, vC ) {
cb.subVectors( vC, vB );
ab.subVectors( vA, vB );
cb.cross( ab ).normalize();
normal.copy( cb ).normalize();
if ( binary === true ) {
output.setFloat32( offset, normal.x, true ); offset += 4;
output.setFloat32( offset, normal.y, true ); offset += 4;
output.setFloat32( offset, normal.z, true ); offset += 4;
} else {
output += '\tfacet normal ' + normal.x + ' ' + normal.y + ' ' + normal.z + '\n';
output += '\t\touter loop\n';
}
}
function writeVertex( vertex ) {
if ( binary === true ) {
output.setFloat32( offset, vertex.x, true ); offset += 4;
output.setFloat32( offset, vertex.y, true ); offset += 4;
output.setFloat32( offset, vertex.z, true ); offset += 4;
} else {
output += '\t\t\tvertex ' + vertex.x + ' ' + vertex.y + ' ' + vertex.z + '\n';
}
}
}
}
export { STLExporter };

View File

@@ -0,0 +1,535 @@
import * as fflate from '../libs/fflate.module.js';
class USDZExporter {
async parse( scene ) {
const files = {};
const modelFileName = 'model.usda';
// model file should be first in USDZ archive so we init it here
files[ modelFileName ] = null;
let output = buildHeader();
const materials = {};
const textures = {};
scene.traverseVisible( ( object ) => {
if ( object.isMesh ) {
if ( object.material.isMeshStandardMaterial ) {
const geometry = object.geometry;
const material = object.material;
const geometryFileName = 'geometries/Geometry_' + geometry.id + '.usd';
if ( ! ( geometryFileName in files ) ) {
const meshObject = buildMeshObject( geometry );
files[ geometryFileName ] = buildUSDFileAsString( meshObject );
}
if ( ! ( material.uuid in materials ) ) {
materials[ material.uuid ] = material;
}
output += buildXform( object, geometry, material );
} else {
console.warn( 'THREE.USDZExporter: Unsupported material type (USDZ only supports MeshStandardMaterial)', object );
}
}
} );
output += buildMaterials( materials, textures );
files[ modelFileName ] = fflate.strToU8( output );
output = null;
for ( const id in textures ) {
const texture = textures[ id ];
const color = id.split( '_' )[ 1 ];
const isRGBA = texture.format === 1023;
const canvas = imageToCanvas( texture.image, color );
const blob = await new Promise( resolve => canvas.toBlob( resolve, isRGBA ? 'image/png' : 'image/jpeg', 1 ) );
files[ `textures/Texture_${ id }.${ isRGBA ? 'png' : 'jpg' }` ] = 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 fflate.zipSync( files, { level: 0 } );
}
}
function imageToCanvas( image, color ) {
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 = 1024 / 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' );
context.drawImage( image, 0, 0, canvas.width, canvas.height );
if ( color !== undefined ) {
const hex = parseInt( color, 16 );
const r = ( hex >> 16 & 255 ) / 255;
const g = ( hex >> 8 & 255 ) / 255;
const b = ( hex & 255 ) / 255;
const imagedata = context.getImageData( 0, 0, canvas.width, canvas.height );
const data = imagedata.data;
for ( let i = 0; i < data.length; i += 4 ) {
data[ i + 0 ] = data[ i + 0 ] * r;
data[ i + 1 ] = data[ i + 1 ] * g;
data[ i + 2 ] = data[ i + 2 ] * b;
}
context.putImageData( imagedata, 0, 0 );
}
return canvas;
}
}
//
const PRECISION = 7;
function buildHeader() {
return `#usda 1.0
(
customLayerData = {
string creator = "Three.js USDZExporter"
}
metersPerUnit = 1
upAxis = "Y"
)
`;
}
function buildUSDFileAsString( dataToInsert ) {
let output = buildHeader();
output += dataToInsert;
return fflate.strToU8( output );
}
// Xform
function buildXform( object, geometry, material ) {
const name = 'Object_' + object.id;
const transform = buildMatrix( object.matrixWorld );
if ( object.matrixWorld.determinant() < 0 ) {
console.warn( 'THREE.USDZExporter: USDZ does not support negative scales', object );
}
return `def Xform "${ name }" (
prepend references = @./geometries/Geometry_${ geometry.id }.usd@</Geometry>
)
{
matrix4d xformOp:transform = ${ transform }
uniform token[] xformOpOrder = ["xformOp:transform"]
rel material:binding = </Materials/Material_${ material.id }>
}
`;
}
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 mesh = buildMesh( geometry );
return `
def "Geometry"
{
${mesh}
}
`;
}
function buildMesh( geometry ) {
const name = 'Geometry';
const attributes = geometry.attributes;
const count = attributes.position.count;
return `
def Mesh "${ name }"
{
int[] faceVertexCounts = [${ buildMeshVertexCount( geometry ) }]
int[] faceVertexIndices = [${ buildMeshVertexIndices( geometry ) }]
normal3f[] normals = [${ buildVector3Array( attributes.normal, count )}] (
interpolation = "vertex"
)
point3f[] points = [${ buildVector3Array( attributes.position, count )}]
float2[] primvars:st = [${ buildVector2Array( attributes.uv, count )}] (
interpolation = "vertex"
)
uniform token subdivisionScheme = "none"
}
`;
}
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, count ) {
if ( attribute === undefined ) {
console.warn( 'USDZExporter: UVs missing.' );
return Array( count ).fill( '(0, 0)' ).join( ', ' );
}
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 ) {
const array = [];
for ( const uuid in materials ) {
const material = materials[ uuid ];
array.push( buildMaterial( material, textures ) );
}
return `def "Materials"
{
${ array.join( '' ) }
}
`;
}
function buildMaterial( material, textures ) {
// https://graphics.pixar.com/usd/docs/UsdPreviewSurface-Proposal.html
const pad = ' ';
const inputs = [];
const samplers = [];
function buildTexture( texture, mapType, color ) {
const id = texture.id + ( color ? '_' + color.getHexString() : '' );
const isRGBA = texture.format === 1023;
textures[ id ] = texture;
return `
def Shader "Transform2d_${ mapType }" (
sdrMetadata = {
string role = "math"
}
)
{
uniform token info:id = "UsdTransform2d"
float2 inputs:in.connect = </Materials/Material_${ material.id }/uvReader_st.outputs:result>
float2 inputs:scale = ${ buildVector2( texture.repeat ) }
float2 inputs:translation = ${ buildVector2( texture.offset ) }
float2 outputs:result
}
def Shader "Texture_${ texture.id }_${ mapType }"
{
uniform token info:id = "UsdUVTexture"
asset inputs:file = @textures/Texture_${ id }.${ isRGBA ? 'png' : 'jpg' }@
float2 inputs:st.connect = </Materials/Material_${ material.id }/Transform2d_${ mapType }.outputs:result>
token inputs:wrapS = "repeat"
token inputs:wrapT = "repeat"
float outputs:r
float outputs:g
float outputs:b
float3 outputs:rgb
}`;
}
if ( material.map !== null ) {
inputs.push( `${ pad }color3f inputs:diffuseColor.connect = </Materials/Material_${ material.id }/Texture_${ material.map.id }_diffuse.outputs:rgb>` );
samplers.push( buildTexture( material.map, 'diffuse', material.color ) );
} else {
inputs.push( `${ pad }color3f inputs:diffuseColor = ${ buildColor( material.color ) }` );
}
if ( material.emissiveMap !== null ) {
inputs.push( `${ pad }color3f inputs:emissiveColor.connect = </Materials/Material_${ material.id }/Texture_${ material.emissiveMap.id }_emissive.outputs:rgb>` );
samplers.push( buildTexture( material.emissiveMap, 'emissive' ) );
} else if ( material.emissive.getHex() > 0 ) {
inputs.push( `${ pad }color3f inputs:emissiveColor = ${ buildColor( material.emissive ) }` );
}
if ( material.normalMap !== null ) {
inputs.push( `${ pad }normal3f inputs:normal.connect = </Materials/Material_${ material.id }/Texture_${ material.normalMap.id }_normal.outputs:rgb>` );
samplers.push( buildTexture( material.normalMap, 'normal' ) );
}
if ( material.aoMap !== null ) {
inputs.push( `${ pad }float inputs:occlusion.connect = </Materials/Material_${ material.id }/Texture_${ material.aoMap.id }_occlusion.outputs:r>` );
samplers.push( buildTexture( material.aoMap, 'occlusion' ) );
}
if ( material.roughnessMap !== null && material.roughness === 1 ) {
inputs.push( `${ pad }float inputs:roughness.connect = </Materials/Material_${ material.id }/Texture_${ material.roughnessMap.id }_roughness.outputs:g>` );
samplers.push( buildTexture( material.roughnessMap, 'roughness' ) );
} else {
inputs.push( `${ pad }float inputs:roughness = ${ material.roughness }` );
}
if ( material.metalnessMap !== null && material.metalness === 1 ) {
inputs.push( `${ pad }float inputs:metallic.connect = </Materials/Material_${ material.id }/Texture_${ material.metalnessMap.id }_metallic.outputs:b>` );
samplers.push( buildTexture( material.metalnessMap, 'metallic' ) );
} else {
inputs.push( `${ pad }float inputs:metallic = ${ material.metalness }` );
}
if ( material.alphaMap !== null ) {
inputs.push( `${pad}float inputs:opacity.connect = </Materials/Material_${material.id}/Texture_${material.alphaMap.id}_opacity.outputs:r>` );
inputs.push( `${pad}float inputs:opacityThreshold = 0.0001` );
samplers.push( buildTexture( material.alphaMap, 'opacity' ) );
} else {
inputs.push( `${pad}float inputs:opacity = ${material.opacity}` );
}
if ( material.isMeshPhysicalMaterial ) {
inputs.push( `${ pad }float inputs:clearcoat = ${ material.clearcoat }` );
inputs.push( `${ pad }float inputs:clearcoatRoughness = ${ material.clearcoatRoughness }` );
inputs.push( `${ pad }float inputs:ior = ${ material.ior }` );
}
return `
def Material "Material_${ material.id }"
{
def Shader "PreviewSurface"
{
uniform token info:id = "UsdPreviewSurface"
${ inputs.join( '\n' ) }
int inputs:useSpecularWorkflow = 0
token outputs:surface
}
token outputs:surface.connect = </Materials/Material_${ material.id }/PreviewSurface.outputs:surface>
token inputs:frame:stPrimvarName = "st"
def Shader "uvReader_st"
{
uniform token info:id = "UsdPrimvarReader_float2"
token inputs:varname.connect = </Materials/Material_${ material.id }.inputs:frame:stPrimvarName>
float2 inputs:fallback = (0.0, 0.0)
float2 outputs:result
}
${ samplers.join( '\n' ) }
}
`;
}
function buildColor( color ) {
return `(${ color.r }, ${ color.g }, ${ color.b })`;
}
function buildVector2( vector ) {
return `(${ vector.x }, ${ vector.y })`;
}
export { USDZExporter };