提交 c922e6de 编写于 作者: K Kyle Larson

Mid-Commit

上级 ea70646c
......@@ -27,7 +27,7 @@
};
THREE.FBXLoader.prototype = Object.create( THREE.Loader.prototype );
Object.assign( THREE.FBXLoader.prototype, THREE.Loader.prototype );
THREE.FBXLoader.prototype.constructor = THREE.FBXLoader;
......@@ -149,17 +149,6 @@
container.add( meshes[ i ] );
//wireframe = new THREE.WireframeHelper( geometries[i], 0x00ff00 );
//container.add( wireframe );
//vnh = new THREE.VertexNormalsHelper( geometries[i], 0.6 );
//container.add( vnh );
//skh = new THREE.SkeletonHelper( geometries[i] );
//container.add( skh );
// container.add( new THREE.BoxHelper( geometries[i] ) );
}
console.timeEnd( 'FBXLoader' );
......@@ -247,31 +236,17 @@
var tmpGeo = new THREE.BufferGeometry();
tmpGeo.name = geoNode.name;
tmpGeo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geoNode.vertices ), 3 ) );
tmpGeo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geoNode.positionBuffer ), 3 ) );
if ( geoNode.normals !== undefined && geoNode.normals.length > 0 ) {
if ( geoNode.normalBuffer !== undefined && geoNode.normalBuffer.length > 0 ) {
tmpGeo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geoNode.normals ), 3 ) );
tmpGeo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geoNode.normalBuffer ), 3 ) );
}
if ( geoNode.uvs !== undefined && geoNode.uvs.length > 0 ) {
if ( geoNode.uvBuffer !== undefined && geoNode.uvBuffer.length > 0 ) {
tmpGeo.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geoNode.uvs ), 2 ) );
}
if ( geoNode.indices !== undefined && geoNode.indices.length > 0 ) {
if ( geoNode.indices.length > 65535 ) {
tmpGeo.setIndex( new THREE.BufferAttribute( new Uint32Array( geoNode.indices ), 1 ) );
} else {
tmpGeo.setIndex( new THREE.BufferAttribute( new Uint16Array( geoNode.indices ), 1 ) );
}
tmpGeo.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geoNode.uvBuffer ), 2 ) );
}
......@@ -280,16 +255,16 @@
tmpGeo.computeBoundingBox();
//Material groupings
if ( geoNode.materialIndices.length > 1 ) {
if ( geoNode.materialBuffer.length > 1 ) {
tmpGeo.groups = [];
for ( var i = 0, prevIndex = - 1; i < geoNode.materialIndices.length; ++ i ) {
for ( var i = 0, prevIndex = - 1; i < geoNode.materialBuffer.length; ++ i ) {
if ( geoNode.materialIndices[ i ] !== prevIndex ) {
if ( geoNode.materialBuffer[ i ] !== prevIndex ) {
tmpGeo.groups.push( { start: i * 3, count: 0, materialIndex: geoNode.materialIndices[ i ] } );
prevIndex = geoNode.materialIndices[ i ];
tmpGeo.groups.push( { start: i * 3, count: 0, materialIndex: geoNode.materialBuffer[ i ] } );
prevIndex = geoNode.materialBuffer[ i ];
}
......@@ -299,7 +274,7 @@
}
this.geometry_cache[ geoNode.id ] = new THREE.Geometry().fromBufferGeometry( tmpGeo );
this.geometry_cache[ geoNode.id ] = tmpGeo;
this.geometry_cache[ geoNode.id ].bones = geoNode.bones;
this.geometry_cache[ geoNode.id ].skinIndices = this.weights.skinIndices;
this.geometry_cache[ geoNode.id ].skinWeights = this.weights.skinWeights;
......@@ -1733,19 +1708,506 @@
function Geometry() {
this.node = null;
this.name = null;
this.id = null;
this.fbxNode = null;
this.name = '';
this.fbxID = - 1;
this.vertices = [];
this.indices = [];
this.normals = [];
this.uvs = [];
this.positionBuffer = [];
this.normalBuffer = [];
this.uvBuffer = [];
this.materialBuffer = [];
this.bones = [];
}
Object.assign( Geometry.prototype, {
parse: function ( geoNode ) {
this.fbxNode = geoNode;
this.name = geoNode.attrName;
this.fbxID = geoNode.id;
var vertexInfo = getVertices( geoNode );
if ( vertexInfo.buffer.length > 0 ) {
console.log( 'FBXLoader: Geometry for ID: ' + geoNode.id + ' has no vertices.' );
return;
}
var uvInfo = getUVs( geoNode );
var normalInfo = getNormals( geoNode );
var materialInfo = getMaterials( geoNode );
//Now lets create the non-indexed buffers.
var vertexBuffer = [];
var normalBuffer = [];
var uvBuffer = [];
var materialBuffer = [];
for ( var faceIndex = 0; faceIndex < vertexInfo.verticesPerFace.length; ++ faceIndex ) {
for ( var polygonVertexIndex = 0; polygonVertexIndex < vertexInfo.verticesPerFace[ faceIndex ]; ++ polygonVertexIndex ) {
var vertex;
if ( polygonVertexIndex > 2 ) {
//Add material for previous Tri before beginning new tri.
materialBuffer.push( getData( polygonVertexIndex, faceIndex, 1, vertexInfo.verticesPerFace, materialInfo ) );
//Re-add vertex 0 and n-1 to triangulate mesh.
vertex = getVertex( 0, faceIndex, vertexInfo, normalInfo, uvInfo );
vertexBuffer.push( vertex.position );
normalBuffer.push( vertex.normal );
uvBuffer.push( vertex.uv );
vertex = getVertex( polygonVertexIndex - 1, faceIndex, vertexInfo, normalInfo, uvInfo );
vertexBuffer.push( vertex.position );
normalBuffer.push( vertex.normal );
uvBuffer.push( vertex.uv );
}
vertex = getVertex( polygonVertexIndex, faceIndex, vertexInfo, normalInfo, uvInfo );
vertexBuffer.push( vertex.position );
normalBuffer.push( vertex.normal );
uvBuffer.push( vertex.uv );
}
materialBuffer.push( getData( 0, faceIndex, 1, vertexInfo.verticesPerFace, materialInfo ) );
}
this.positionBuffer = vertexBuffer;
this.normalBuffer = normalBuffer;
this.uvBuffer = uvBuffer;
this.materialBuffer = materialBuffer;
/**
* Pushes vertex data into appropriate buffers based on given info.
* @param {number} polyVertexIndex - Index of vertex within polygon.
* @param {number} polyIndex - Index of polygon within geometry.
* @param {{buffer: number[], indices: number[], mappingType: string, referenceType: string, maxNGon: number, verticesPerFace: number[]}} positionInfo
* @param {{buffer: number[], indices: number[], mappingType: string, referenceType: string}} normalInfo
* @param {{buffer: number[], indices: number[], mappingType: string, referenceType: string}} uvInfo
* @returns {{ position: number[], normal: number[], uv: number[] }}
*/
function getVertex( polyVertexIndex, polyIndex, positionInfo, normalInfo, uvInfo ) {
/**
* Describes which vertex index we are looking at.
*/
var positionIndexIndex = 0;
for ( var i = 0; i < polyIndex; ++ i ) {
positionIndexIndex += positionInfo.verticesPerFace[ i ];
}
var positionIndex = positionInfo.indices[ positionIndexIndex ];
var position = [
positionInfo.buffer[ ( positionIndex * 3 ) ],
positionInfo.buffer[ ( positionIndex * 3 ) + 1 ],
positionInfo.buffer[ ( positionIndex * 3 ) + 2 ] ];
var normal = getData( polyVertexIndex, polyIndex, 3, positionInfo.verticesPerFace, normalInfo );
var uvs = getData( polyVertexIndex, polyIndex, 2, positionInfo.verticesPerFace, uvInfo );
return {
position: position,
normal: normal,
uv: uvs
};
}
/**
* Grabs data based on mapping and reference type of data and returns data buffer.
* @param {number} polyVertexIndex - Index of vertex within polygon.
* @param {number} polyIndex - Index of polygon within geometry.
* @param {number} dataSize - Number of data values per vertex for this type of data.
* @param {number[]} verticesPerFace - Number of vertices per polygon face.
* @param {{buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object holding info for data.
* @returns {number[]}
*/
function getData( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
var GetData = {
ByPolygonVertex: {
/**
* Grabs data mapped by polygon vertex and referenced directly and returns the data for
* the specific instance based on the polygon vertex index and polygon index.
* @param {number} polyVertexIndex - Index of vertex within polygon.
* @param {number} polyIndex - Index of polygon within geometry.
* @param {number} dataSize - Number of data values per vertex for given data type.
* @param {number[]} verticesPerFace - Number of polygon vertices per face.
* @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
* @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
*/
Direct: function ( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
var dataIndex = 0;
for ( var i = 0; i < polyIndex; ++ i ) {
dataIndex += verticesPerFace[ i ];
}
dataIndex += polyVertexIndex;
var returnBuffer = [];
for ( var i = 0; i < dataSize; ++ i ) {
returnBuffer.push( infoObject.buffer[ ( dataIndex * dataSize ) + i ] );
}
return returnBuffer;
},
/**
* Grabs data mapped by polygon vertex and referenced via index buffer and returns the data for
* the specific instance based on the polygon vertex index and polygon index.
* @param {number} polyVertexIndex - Index of vertex within polygon.
* @param {number} polyIndex - Index of polygon within geometry.
* @param {number} dataSize - Number of data values per vertex for given data type.
* @param {number[]} verticesPerFace - Number of polygon vertices per face.
* @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
* @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
*/
IndexToDirect: function ( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
var dataIndexIndex = 0;
for ( var i = 0; i < polyIndex; ++ i ) {
dataIndexIndex += verticesPerFace[ i ];
}
dataIndexIndex += polyVertexIndex;
var dataIndex = infoObject.indices[ dataIndexIndex ];
var returnBuffer = [];
for ( var i = 0; i < dataSize; ++ i ) {
returnBuffer.push( infoObject.buffer[ ( dataIndex * dataSize ) + i ] );
}
return returnBuffer;
}
},
ByPolygon: {
/**
* Grabs data mapped by polygon and referenced directly and returns the data for
* the specific instance based on the polygon index.
* @param {number} polyVertexIndex - Index of vertex within polygon (Ignored for this function).
* @param {number} polyIndex - Index of polygon within geometry.
* @param {number} dataSize - Number of data values per vertex for given data type.
* @param {number[]} verticesPerFace - Number of polygon vertices per face (Ignored for this function).
* @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
* @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
*/
Direct: function ( polyVertexIndex, polyIndex, dataSize, vericesPerFace, infoObject ) {
var returnBuffer = [];
for ( var i = 0; i < dataSize; ++ i ) {
returnBuffer.push( infoObject.buffer[ ( polyIndex * dataSize ) + i ] );
}
return returnBuffer;
},
/**
* Grabs data mapped by polygon and referenced via index buffer and returns the data for
* the specific instance based on the polygon index.
* @param {number} polyVertexIndex - Index of vertex within polygon (Ignored for this function).
* @param {number} polyIndex - Index of polygon within geometry.
* @param {number} dataSize - Number of data values per vertex for given data type.
* @param {number[]} verticesPerFace - Number of polygon vertices per face (Ignored for this function).
* @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
* @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
*/
IndexToDirect: function ( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
var index = infoObject.indices[ polyIndex ];
var returnBuffer = [];
for ( var i = 0; i < dataSize; ++ i ) {
returnBuffer.push( infoObject.buffer[ ( index * dataSize ) + i ] );
}
return returnBuffer;
}
},
AllSame: {
/**
* Grabs data mapped all the same and referenced via index buffer and returns the data for
* the specific instance based on the polygon vertex index and polygon index.
* @param {number} polyVertexIndex - Index of vertex within polygon (Ignored in this function).
* @param {number} polyIndex - Index of polygon within geometry (Ignored in this function).
* @param {number} dataSize - Number of data values per vertex for given data type.
* @param {number[]} verticesPerFace - Number of polygon vertices per face (Ignored in this function).
* @param {{buffer: number[], indices: number[]}} infoObject - Object containing buffer and index buffer data.
* @returns {number[]} - Buffer for specific vertex instance, length of dataSize.
*/
IndexToDirect: function ( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject ) {
var returnBuffer;
for ( var i = 0; i < dataSize; ++ i ) {
returnBuffer.push( infoObject.buffer[ ( infoObject.indices[ 0 ] * dataSize ) + i ] );
}
return returnBuffer;
}
}
};
return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polyVertexIndex, polyIndex, dataSize, verticesPerFace, infoObject );
}
/**
* Extracts vertex array and returns array of floats
* representing vertex position data.
* @param {Object} geoNode - Parsed FBX node for geometry.
* @returns {{buffer: number[], indices: number[], mappingType: string, referenceType: string, maxNGon: number, verticesPerFace: number[]}}
*/
function getVertices( geoNode ) {
if ( geoNode.subNodes.Vertices === undefined ) {
console.warn( 'Geo Node ' + geoNode.attrName + "(" + geoNode.id + ") does not define vertices." );
return {
buffer: [],
indices: [],
mappingType: 'ByPolygonVertex',
referenceType: 'IndexToDirect',
maxNGon: 3,
verticesPerFace: []
};
}
var buffer = parseArrayToFloat( geoNode.subNodes.Vertices.properties.a );
var indices = parseArrayToInt( geoNode.subNodes.PolygonVertexIndex.properties.a );
var currentNumVerticesThisFace = 1;
var maxVerticesOnAFace = 0;
var verticesPerFace = [];
// The indices that make up the polygon are in order. A negative index means
// that it's the last index of the polygon. That index needs to be made positive
// and subtract 1 from it.
for ( var i = 0; i < indices.length; ++ i ) {
var index = indices[ i ];
if ( index < 0 ) {
if ( currentNumVerticesThisFace > maxVerticesOnAFace ) {
maxVerticesOnAFace = currentNumVerticesThisFace;
}
indices[ i ] = index ^ - 1;
verticesPerFace.push( currentNumVerticesThisFace );
currentNumVerticesThisFace = 1;
} else {
currentNumVerticesThisFace ++;
}
}
if ( maxVerticesOnAFace === 0 ) {
console.warn( 'FBXLoader: Max vertices on a face not found: ' + geoNode.attrName );
maxVerticesOnAFace = 3;
}
return {
buffer: buffer,
indices: indices,
mappingType: 'ByPolygonVertex',
referenceType: 'IndexToDirect',
maxNGon: maxVerticesOnAFace,
verticesPerFace: verticesPerFace
};
}
/**
* Extracts UV information and returns object describing UVs.
* @param {Object} geoNode - Parsed FBX node for geometry.
* @returns {{buffer: number[], indices: number[], mappingType: string, referenceType: string}}
*/
function getUVs( geoNode ) {
if ( ! ( 'LayerElementUV' in geoNode.subNodes ) ) {
// No UVs defined. Nothing to do here.
return {
buffer: [],
indices: [],
mappingType: 'AllSame',
referenceType: 'IndexToDirect'
};
}
var UVNode = geoNode.subNodes.LayerElementUV;
if ( UVNode === undefined ) {
// No UV information.
return [];
}
for ( var node in UVNode ) {
if ( node.match( /^\d+$/ ) ) {
console.warn( 'multi UV is not supported.' );
UVNode = UVNode[ node ];
break;
}
}
var rawUVBuffer = UVNode.subNodes.UV.properties.a;
var mappingType = UVNode.properties.MappingInformationType;
var refType = UVNode.properties.ReferenceInformationType;
var UVBuffer = parseArrayToFloat( rawUVBuffer );
var IndexBuffer = [];
if ( mappingType === 'IndexToDirect' ) {
var rawIndexBuffer = UVNode.subNodes.UVIndex.properties.a;
IndexBuffer = parseArrayToInt( rawIndexBuffer );
}
return {
buffer: UVBuffer,
indices: IndexBuffer,
mappingType: mappingType,
referenceType: refType
};
}
/**
* Extracts normal information and returns object describing normals.
* @param {Object} geoNode - Parsed FBX node for geometry.
* @returns {{buffer: number[], indices: number[], mappingType: string, referenceType: string}}
*/
function getNormals( geoNode ) {
var NormalNode = geoNode.subNodes.LayerElementNormal;
if ( NormalNode === undefined ) {
console.warn( 'Node: ' + geoNode.attrName + "(" + geoNode.id + ") does not have Normals defined." );
return {
buffer: [],
indices: [],
mappingType: 'AllSame',
referenceType: 'IndexToDirect'
};
}
var mappingType = NormalNode.properties.MappingInformationType;
var referenceType = NormalNode.properties.ReferenceInformationType;
var normalBuffer = parseArrayToFloat( NormalNode.subNodes.Normals.properties.a );
var indexBuffer = [];
if ( referenceType === 'IndexToDirect' ) {
var rawIndexBuffer = NormalNode.subNodes.NormalIndex.properties.a;
indexBuffer = parseArrayToInt( rawIndexBuffer );
}
return {
buffer: normalBuffer,
indices: indexBuffer,
mappingType: mappingType,
referenceType: referenceType
};
}
/**
* Extracts material index information and returns object describing material assignment.
* @param {Object} geoNode - Parsed FBX node for geometry.
* @returns {{buffer: number[], mappingType: string, referenceType: string}}
*/
function getMaterials( geoNode ) {
if ( ! ( 'LayerElementMaterial' in geoNode.subNodes ) ) {
// No material info.
return {
buffer: [ 0 ],
indices: [ 0 ],
mappingType: 'AllSame',
referenceType: 'IndexToDirect'
};
}
var indexNode = geoNode.subNodes.LayerElementMaterial;
var mapType = indexNode.properties.MappingInformationType;
var refType = indexNode.properties.ReferenceInformationType;
var matBuffer = parseArrayToInt( indexNode.subNodes.Materials.properties.a );
var matIndexes = [];
matBuffer.forEach( function ( materialIndex, index ) {
matIndexes.push( index );
} );
return {
buffer: matBuffer,
indices: matIndexes,
mappingType: mapType,
referenceType: refType
};
}
},
addBones: function ( bones ) {
this.bones = bones;
}
} );
/**
Geometry.prototype.parse = function ( geoNode ) {
this.node = geoNode;
......@@ -2473,6 +2935,7 @@
},
} );
*/
function AnimationCurve() {
......@@ -3209,6 +3672,12 @@
}
/**
* Parses a string of comma separated ints and returns
* an array of ints.
* @param {string} string - String comtaining comma separated float values.
* @returns {number[]}
*/
function parseArrayToInt( string ) {
return string.split( ',' ).map( function ( element ) {
......@@ -3219,6 +3688,12 @@
}
/**
* Parses a string of comma separated floats and returns
* an array of floats.
* @param {string} string - String containing comma separated float values.
* @returns {number[]}
*/
function parseArrayToFloat( string ) {
return string.split( ',' ).map( function ( element ) {
......
/**
* @author Kyle-Larson https://github.com/Kyle-Larson
*
* Loader loads FBX file and generates Group representing FBX scene.
* Requires FBX file to be >= 7.0 and in ASCII format.
*/
( function () {
THREE.FBXLoader = function ( manager ) {
THREE.Loader.call( this );
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
this.fileLoader = new THREE.FileLoader( this.manager );
this.textureLoader = new THREE.TextureLoader( this.manager );
};
Object.assign( THREE.FBXLoader.prototype, THREE.Loader.prototype );
THREE.FBXLoader.prototype.constructor = THREE.FBXLoader;
Object.assign( THREE.FBXLoader.prototype, {
load: function ( url, onLoad, onProgress, onError ) {
var self = this;
var resourceDirectory = url.split( /[\\\/]/ );
resourceDirectory.pop();
resourceDirectory = "".concat( resourceDirectory );
this.fileLoader.load( url, function ( text ) {
if ( ! isFbxFormatASCII( text ) ) {
console.error( 'FBXLoader: FBX Binary format not supported.' );
return;
}
if ( getFbxVersion( text ) < 7000 ) {
console.error( 'FBXLoader: FBX version not supported for file at ' + url + ', FileVersion: ' + getFbxVersion( text ) );
return;
}
var scene = self.parse( text, resourceDirectory );
onLoad( scene );
}, onProgress, onError );
},
parse: function ( FBXText, resourceDirectory ) {
var loader = this;
var FBXTree = new TextParser().parse( FBXText );
console.log( FBXTree );
var connections = parseConnections( FBXTree );
/**
* @returns {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
*/
function parseConnections( FBXTree ) {
var connectionMap = new Map();
if ( 'Connections' in FBXTree ) {
/**
* @type {number[]}
*/
var connectionArray = FBXTree.Connections.properties.connections;
connectionArray.forEach( function ( connection ) {
if ( ! connectionMap.has( connection[ 0 ] ) ) {
connectionMap.set( connection[ 0 ], {
parents: [],
children: []
} );
}
var relationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
connectionMap.get( connection[ 0 ] ).parents.push( relationship );
if ( ! connectionMap.has( connection[ 1 ] ) ) {
connectionMap.set( connection[ 1 ], {
parents: [],
children: []
} );
}
relationship.ID = connection[ 0 ];
connectionMap.get( connection[ 1 ] ).children.push( relationship );
} );
}
return connectionMap;
}
var textures = parseTextures( FBXTree );
function parseTextures( FBXTree ) {
var textureMap = new Map();
if ( 'Texture' in FBXTree.Objects.subNodes ) {
var textureNodes = FBXTree.Objects.subNodes.Texture;
for ( var nodeID in textureNodes ) {
var texture = parseTexture( textureNodes[ nodeID ] );
textureMap.set( parseInt( nodeID ), texture );
}
}
return textureMap;
function parseTexture( textureNode ) {
var FBX_ID = textureNode.id;
var name = textureNode.name;
var filePath = textureNode.properties.FileName;
var split = filePath.split( /[\\\/]/ );
if ( split.length > 0 ) {
var fileName = split[ split.length - 1 ];
} else {
var fileName = filePath;
}
var texture = loader.textureLoader.load( resourceDirectory + '/' + fileName );
texture.name = name;
texture.FBX_ID = FBX_ID;
return texture;
}
}
var materials = parseMaterials( FBXTree, textures, connections );
/**
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
*/
function parseMaterials( FBXTree, textureMap, connections ) {
var materialMap = new Map();
if ( 'Material' in FBXTree.Objects.subNodes ) {
var materialNodes = FBXTree.Objects.subNodes.Material;
for ( var nodeID in materialNodes ) {
var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
materialMap.set( parseInt( nodeID ), material );
}
}
return materialMap;
/**
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
*/
function parseMaterial( materialNode, textureMap, connections ) {
var FBX_ID = materialNode.id;
var name = materialNode.attrName;
var type = materialNode.properties.ShadingModel;
var children = connections.get( FBX_ID ).children;
var parameters = parseParameters( materialNode.properties, textureMap, children );
var material;
switch ( type ) {
case 'phong':
material = new THREE.MeshPhongMaterial();
break;
case 'lambert':
material = new THREE.MeshLambertMaterial();
break;
default:
console.warn( 'No implementation given for material type ' + type + ' in FBXLoader.js. Defaulting to basic material' );
material = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
break;
}
material.setValues( parameters );
material.name = name;
return material;
/**
* @param {{ID: number, relationship: string}[]} childrenRelationships
*/
function parseParameters( properties, textureMap, childrenRelationships ) {
var parameters = {};
if ( properties.Diffuse ) {
parameters.color = parseColor( properties.Diffuse );
}
if ( properties.Specular ) {
parameters.specular = parseColor( properties.Specular );
}
if ( properties.Shininess ) {
parameters.shininess = properties.Shininess.value;
}
if ( properties.Emissive ) {
parameters.emissive = parseColor( properties.Emissive );
}
if ( properties.EmissiveFactor ) {
parameters.emissiveIntensity = properties.EmissiveFactor.value;
}
if ( properties.Opacity ) {
parameters.opacity = properties.Opacity.value;
}
if ( parameters.opacity < 1.0 ) {
parameters.transparent = true;
}
childrenRelationships.forEach( function ( relationship ) {
var type = relationship.relationship;
switch ( type ) {
case " \"AmbientColor":
//TODO: Support AmbientColor textures
break;
case " \"DiffuseColor":
parameters.map = textureMap.get( relationship.ID );
break;
default:
console.warn( 'Unknown texture application of type ' + type + ', skipping texture' );
break;
}
} );
return parameters;
}
}
}
console.log( materials );
var deformerMap = parseDeformers( FBXTree, connections );
/**
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
* @returns {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>}
*/
function parseDeformers( FBXTree, connections ) {
var skeletonMap = new Map();
if ( 'Deformer' in FBXTree.Objects.subNodes ) {
var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
for ( var nodeID in DeformerNodes ) {
var deformerNode = DeformerNodes[ nodeID ];
if ( deformerNode.attrType === 'Skin' ) {
var conns = connections.get( parseInt( nodeID ) );
var skeleton = parseSkeleton( deformerNode, conns, DeformerNodes );
skeletonMap.set( parseInt( nodeID ), skeleton );
}
}
}
return skeletonMap;
/**
* @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} connections
* @returns {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}}
*/
function parseSkeleton( deformerNode, connections, DeformerNodes ) {
var subDeformers = new Map();
var subDeformerArray = [];
connections.children.forEach( function ( child ) {
var subDeformerNode = DeformerNodes[ child.ID ];
var subDeformer = {
FBX_ID: child.ID,
indices: parseIntArray( subDeformerNode.subNodes.Indexes.properties.a ),
weights: parseFloatArray( subDeformerNode.subNodes.Weights.properties.a ),
transform: parseMatrixArray( subDeformerNode.subNodes.Transform.properties.a ),
transformLink: parseMatrixArray( subDeformerNode.subNodes.TransformLink.properties.a ),
linkMode: subDeformerNode.properties.Mode
};
subDeformers.set( child.ID, subDeformer );
subDeformerArray.push( subDeformer );
} );
return {
map: subDeformers,
array: subDeformerArray,
skeleton: null
};
}
}
var geometryMap = parseGeometries( FBXTree, connections, deformerMap );
/**
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
* @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformerMap
* @returns {Map<number, THREE.BufferGeometry>}
*/
function parseGeometries( FBXTree, connections, deformerMap ) {
var geometryMap = new Map();
if ( 'Geometry' in FBXTree.Objects.subNodes ) {
var geometryNodes = FBXTree.Objects.subNodes.Geometry;
for ( var nodeID in geometryNodes ) {
var relationships = connections.get( parseInt( nodeID ) );
var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformerMap );
geometryMap.set( parseInt( nodeID ), geo );
}
}
return geometryMap;
/**
* @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
* @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformerMap
*/
function parseGeometry( geometryNode, relationships, deformerMap ) {
switch ( geometryNode.attrType ) {
case 'Mesh':
return parseMeshGeometry( geometryNode, relationships, deformerMap );
break;
case 'NurbsCurve':
return parseNurbsGeometry( geometryNode, relationships, deformerMap );
break;
}
/**
* @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
* @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformerMap
*/
function parseMeshGeometry( geometryNode, relationships, deformerMap ) {
var FBX_ID = geometryNode.id;
var name = geometryNode.attrName;
for ( var i = 0; i < relationships.children.length; ++ i ) {
if ( deformerMap.has( relationships.children[ i ].ID ) ) {
var deformer = deformerMap.get( relationships.children[ i ].ID );
break;
}
}
var geometry = genGeometry( geometryNode, deformer );
return geometry;
/**
* @param {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}} deformer
* @returns {THREE.BufferGeometry}
*/
function genGeometry( geometryNode, deformer ) {
var geometry = new Geometry();
//First, each index is going to be its own vertex.
var vertexBuffer = parseFloatArray( geometryNode.subNodes.Vertices.properties.a );
var indexBuffer = parseIntArray( geometryNode.subNodes.PolygonVertexIndex.properties.a );
if ( 'LayerElementNormal' in geometryNode.subNodes ) {
var normalInfo = getNormals( geometryNode );
}
if ( 'LayerElementUV' in geometryNode.subNodes ) {
var uvInfo = getUVs( geometryNode );
}
if ( 'LayerElementMaterial' in geometryNode.subNodes ) {
var materialInfo = getMaterials( geometryNode );
}
var faceVertexBuffer = [];
var polygonIndex = 0;
for ( var polygonVertexIndex = 0; polygonVertexIndex < indexBuffer.length; ++ polygonVertexIndex ) {
var endOfFace;
var vertexIndex = indexBuffer[ polygonVertexIndex ];
if ( indexBuffer[ polygonVertexIndex ] < - 1 ) {
vertexIndex = vertexIndex ^ - 1;
endOfFace = true;
}
var vertex = new Vertex();
var weightIndices = [];
var weights = [];
vertex.position.fromArray( vertexBuffer, vertexIndex * 3 );
if ( deformer ) {
for ( var j = 0; j < deformer.array.length; ++ j ) {
var index = deformer.array[ j ].indices.findIndex( function ( index ) {
return index === indexBuffer[ polygonVertexIndex ];
} );
if ( index !== - 1 ) {
weights.push( deformer.array[ j ].weights[ index ] );
weightIndices.push( j );
}
}
if ( weights.length > 4 ) {
console.warn( 'FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
var WIndex = [ 0, 0, 0, 0 ];
var Weight = [ 0, 0, 0, 0 ];
for ( var polygonVertexIndex = 0; polygonVertexIndex < weights.length; ++ polygonVertexIndex ) {
var currentWeight = weights[ polygonVertexIndex ];
var currentIndex = weightIndices[ polygonVertexIndex ];
for ( var j = 0; j < Weight.length; ++ j ) {
if ( currentWeight > Weight[ j ] ) {
var tmp = Weight[ j ];
Weight[ j ] = currentWeight;
currentWeight = tmp;
tmp = WIndex[ j ];
WIndex[ j ] = currentIndex;
currentIndex = tmp;
}
}
}
weightIndices = WIndex;
weights = Weight;
}
vertex.skinWeights.fromArray( weights );
vertex.skinIndices.fromArray( weightIndices );
vertex.skinWeights.normalize();
}
if ( normalInfo ) {
vertex.normal.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo ) );
}
if ( uvInfo ) {
vertex.uv.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo ) );
}
//Add vertex to face buffer.
faceVertexBuffer.push( vertex );
// If index was negative to start with, we have finished this individual face
// and can generate the face data to the geometry.
if ( endOfFace ) {
var face = new Face();
var materials = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo );
face.genTrianglesFromVertices( faceVertexBuffer );
face.materialIndex = materials[ 0 ];
geometry.faces.push( face );
faceVertexBuffer = [];
polygonIndex ++;
endOfFace = false;
}
}
/**
* @type {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
*/
var bufferInfo = geometry.flattenToBuffers();
var geo = new THREE.BufferGeometry();
geo.name = geometryNode.name;
geo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( bufferInfo.vertexBuffer ), 3 ) );
if ( bufferInfo.normalBuffer.length > 0 ) {
geo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( bufferInfo.normalBuffer ), 3 ) );
}
if ( bufferInfo.uvBuffer.length > 0 ) {
geo.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( bufferInfo.uvBuffer ), 2 ) );
}
if ( deformer ) {
geo.addAttribute( 'skinIndex', new THREE.BufferAttribute( new Float32Array( bufferInfo.skinIndexBuffer ), 4 ) );
geo.addAttribute( 'skinWeight', new THREE.BufferAttribute( new Float32Array( bufferInfo.skinWeightBuffer ), 4 ) );
geo.FBX_Deformer = deformer;
}
var prevMaterialIndex = bufferInfo.materialIndexBuffer[ 0 ];
var startIndex = 0;
for ( var materialBufferIndex = 0; i < bufferInfo.materialIndexBuffer.length; ++ materialBufferIndex ) {
if ( bufferInfo.materialIndexBuffer[ materialBufferIndex ] !== prevMaterialIndex ) {
geo.addGroup( startIndex, materialBufferIndex - startIndex, prevMaterialIndex );
startIndex = materialBufferIndex;
prevMaterialIndex = bufferInfo.materialIndexBuffer[ materialBufferIndex ];
}
}
return geo;
/**
* @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
*/
function getNormals( geometryNode ) {
var NormalNode = geometryNode.subNodes.LayerElementNormal;
var mappingType = NormalNode.properties.MappingInformationType;
var referenceType = NormalNode.properties.ReferenceInformationType;
var buffer = parseFloatArray( NormalNode.subNodes.Normals.properties.a );
var indexBuffer = [];
if ( referenceType === 'IndexToDirect' ) {
indexBuffer = parseIntArray( NormalNode.subNodes.NormalIndex.properties.a );
}
return {
dataSize: 3,
buffer: buffer,
indices: indexBuffer,
mappingType: mappingType,
referenceType: referenceType
};
}
/**
* @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
*/
function getUVs( geometryNode ) {
var UVNode = geometryNode.subNodes.LayerElementUV;
var mappingType = UVNode.properties.MappingInformationType;
var referenceType = UVNode.properties.ReferenceInformationType;
var buffer = parseFloatArray( UVNode.subNodes.UV.properties.a );
var indexBuffer = [];
if ( referenceType === 'IndexToDirect' ) {
indexBuffer = parseIntArray( UVNode.subNodes.UVIndex.properties.a );
}
return {
dataSize: 2,
buffer: buffer,
indices: indexBuffer,
mappingType: mappingType,
referenceType: referenceType
};
}
/**
* @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
*/
function getMaterials( geometryNode ) {
var MaterialNode = geometryNode.subNodes.LayerElementMaterial;
var mappingType = MaterialNode.properties.mappingInformationType;
var referenceType = MaterialNode.properties.ReferenceInformationType;
var materialIndexBuffer = parseIntArray( MaterialNode.subNodes.Materials.properties.a );
// Since materials are stored as indices, there's a bit of a mismatch between FBX and what
// we expect. So we create an intermediate buffer that points to the index in the buffer,
// for conforming with the other functions we've written for other data.
var materialIndices = [];
materialIndexBuffer.forEach( function ( materialIndex, index ) {
materialIndices.push( index );
} );
return {
dataSize: 1,
buffer: materialIndexBuffer,
indices: materialIndices,
mappingType: mappingType,
referenceType: referenceType
};
}
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
var GetData = {
ByPolygonVertex: {
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
return infoObject.buffer.slice( ( polygonVertexIndex * infoObject.dataSize ), ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize );
},
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
var index = infoObject.indices[ polygonVertexIndex ];
return infoObject.buffer.slice( ( index * infoObject.dataSize ), ( index * infoObject.dataSize ) + infoObject.dataSize );
}
},
ByPolygon: {
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
return infoObject.buffer.slice( polygonIndex * infoObject.dataSize, polygonIndex * infoObject.dataSize + infoObject.dataSize );
},
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
var index = infoObject.indices[ polygonIndex ];
return infoObject.buffer.slice( index * infoObject.dataSize, index * infoObject.dataSize + infoObject.dataSize );
}
},
AllSame: {
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
return infoObject.buffer.slice( infoObject.indices[ 0 ] * infoObject.dataSize, infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize );
}
}
};
return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
}
}
}
}
}
var sceneGraph = parseScene( FBXTree, connections, deformerMap, geometryMap, materials );
/**
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
* @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformerMap
* @param {Map<number, THREE.BufferGeometry>} geometryMap
* @param {Map<number, THREE.Material>} materialMap
*/
function parseScene( FBXTree, connections, deformerMap, geometryMap, materialMap ) {
var sceneGraph = new THREE.Group();
var ModelNode = FBXTree.Objects.subNodes.Model;
var models = [];
for ( var nodeID in ModelNode ) {
var id = parseInt( nodeID );
var node = ModelNode[ nodeID ];
var conns = connections.get( id );
var model;
for ( var i = 0; i < conns.parents.length; ++ i ) {
deformerMap.forEach( function ( deformer ) {
if ( deformer.map.has( conns.parents[ i ] ) ) {
model = new THREE.Bone();
var index = deformer.array.findIndex( function ( subDeformer ) {
return subDeformer.FBX_ID === conns.parents[ i ].ID;
} );
deformer.skeleton.bones[ index ] = model;
}
} );
}
if ( ! model ) {
switch ( node.attrType ) {
case "Mesh":
var geometry;
var material;
var materials;
conns.children.forEach( function ( child ) {
if ( geometryMap.has( child.ID ) ) {
geometry = geometryMap.get( child.ID );
}
if ( materialMap.has( child.ID ) ) {
materials.push( materialMap.get( child.ID ) );
}
} );
if ( materials.length > 1 ) {
material = new THREE.MultiMaterial( materials );
} else if ( materials.length > 0 ) {
material = materials[ 0 ];
} else {
material = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
}
model = new THREE.Mesh( geometry, material );
break;
default:
model = new THREE.Object3D();
break;
}
}
model.name = node.attrName.replace( /:/, '' ).replace( /_/, '' ).replace( /-/, '' );
model.FBX_ID = id;
if ( 'Lcl_Translation' in node.properties ) {
model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) );
}
if ( 'Lcl_Rotation' in node.properties ) {
var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( function ( value ) {
return value * Math.PI / 180;
} );
rotation.push( 'ZYX' );
model.rotation.fromArray( rotation );
}
if ( 'Lcl_Scaling' in node.properties ) {
model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) );
}
models.push( model );
}
models.forEach( function ( model ) {
var conns = connections.get( model.FBX_ID );
conns.parents.forEach( function ( parent ) {
for ( var i = 0; i < models.length; ++ i ) {
if ( models[ i ].FBX_ID === parent.ID ) {
models[ i ].add( model );
return;
}
}
//Parent not found, root node?
if ( parent.ID === 0 ) {
sceneGraph.add( model );
}
} );
} );
return sceneGraph;
}
// UTILS
function parseVector3( property ) {
return new THREE.Vector3( parseFloat( property.value.x ), parseFloat( property.value.y ), parseFloat( property.value.z ) );
}
function parseColor( property ) {
return new THREE.Color().fromArray( parseVector3( property ).toArray() );
}
}
} );
/**
* An instance of a Vertex with data for drawing vertices to the screen.
* @constructor
*/
function Vertex() {
/**
* Position of the vertex.
* @type {THREE.Vector3}
*/
this.position = new THREE.Vector3( );
/**
* Normal of the vertex
* @type {THREE.Vector3}
*/
this.normal = new THREE.Vector3( );
/**
* UV coordinates of the vertex.
* @type {THREE.Vector2}
*/
this.uv = new THREE.Vector2( );
/**
* Indices of the bones vertex is influenced by.
* @type {THREE.Vector4}
*/
this.skinIndices = new THREE.Vector4( );
/**
* Weights that each bone influences the vertex.
* @type {THREE.Vector4}
*/
this.skinWeights = new THREE.Vector4( );
}
Object.assign( Vertex.prototype, {
copy: function ( target ) {
var returnVar = target || new Vertex();
returnVar.position.copy( this.position );
returnVar.normal.copy( this.normal );
returnVar.uv.copy( this.uv );
returnVar.skinIndices.copy( this.skinIndices );
returnVar.skinWeights.copy( this.skinWeights );
return returnVar;
},
flattenToBuffers: function () {
var vertexBuffer = this.position.toArray();
var normalBuffer = this.normal.toArray();
var uvBuffer = this.uv.toArray();
var skinIndexBuffer = this.skinIndices.toArray();
var skinWeightBuffer = this.skinWeights.toArray();
return {
vertexBuffer: vertexBuffer,
normalBuffer: normalBuffer,
uvBuffer: uvBuffer,
skinIndexBuffer: skinIndexBuffer,
skinWeightBuffer: skinWeightBuffer,
};
}
} );
/**
* @constructor
*/
function Triangle() {
/**
* @type {{position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}
*/
this.vertices = [ ];
}
Object.assign( Triangle.prototype, {
copy: function ( target ) {
var returnVar = target || new Triangle();
for ( var i = 0; i < this.vertices.length; ++ i ) {
this.vertices[ i ].copy( returnVar.vertices[ i ] );
}
return returnVar;
},
flattenToBuffers: function () {
var vertexBuffer = [];
var normalBuffer = [];
var uvBuffer = [];
var skinIndexBuffer = [];
var skinWeightBuffer = [];
this.vertices.forEach( function ( vertex ) {
var flatVertex = vertex.flattenToBuffers();
vertexBuffer.push( flatVertex.vertexBuffer );
normalBuffer.push( flatVertex.normalBuffer );
uvBuffer.push( flatVertex.uvBuffer );
skinIndexBuffer.push( flatVertex.skinIndexBuffer );
skinWeightBuffer.push( flatVertex.skinWeightBuffer );
} );
return {
vertexBuffer: vertexBuffer,
normalBuffer: normalBuffer,
uvBuffer: uvBuffer,
skinIndexBuffer: skinIndexBuffer,
skinWeightBuffer: skinWeightBuffer,
};
}
} );
/**
* @constructor
*/
function Face() {
/**
* @type {{vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[]}
*/
this.triangles = [ ];
this.materialIndex = 0;
}
Object.assign( Face.prototype, {
copy: function ( target ) {
var returnVar = target || new Face();
for ( var i = 0; i < this.triangles.length; ++ i ) {
this.triangles[ i ].copy( returnVar.triangles[ i ] );
}
returnVar.materialIndex = this.materialIndex;
return returnVar;
},
genTrianglesFromVertices: function ( vertexArray ) {
for ( var i = 2; i < vertexArray.length; ++ i ) {
var triangle = new Triangle();
triangle.vertices[ 0 ] = vertexArray[ 0 ];
triangle.vertices[ 1 ] = vertexArray[ i - 1 ];
triangle.vertices[ 2 ] = vertexArray[ i ];
this.triangles.push( triangle );
}
},
flattenToBuffers: function () {
var vertexBuffer = [];
var normalBuffer = [];
var uvBuffer = [];
var skinIndexBuffer = [];
var skinWeightBuffer = [];
var materialIndexBuffer = [];
this.triangles.forEach( function ( triangle ) {
var flatTriangle = triangle.flattenToBuffers();
vertexBuffer.push( flatTriangle.vertexBuffer );
normalBuffer.push( flatTriangle.normalBuffer );
uvBuffer.push( flatTriangle.uvBuffer );
skinIndexBuffer.push( flatTriangle.skinIndexBuffer );
skinWeightBuffer.push( flatTriangle.skinWeightBuffer );
materialIndexBuffer.push( [ this.materialIndex, this.materialIndex, this.materialIndex ] );
} );
return {
vertexBuffer: vertexBuffer,
normalBuffer: normalBuffer,
uvBuffer: uvBuffer,
skinIndexBuffer: skinIndexBuffer,
skinWeightBuffer: skinWeightBuffer,
materialIndexBuffer: materialIndexBuffer
};
}
} );
/**
* @constructor
*/
function Geometry() {
/**
* @type {{triangles: {vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[], materialIndex: number}[]}
*/
this.faces = [ ];
/**
* @type {null|THREE.Skeleton}
*/
this.skeleton = null;
}
Object.assign( Geometry.prototype, {
/**
* @returns {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
*/
flattenToBuffers: function () {
var vertexBuffer = [];
var normalBuffer = [];
var uvBuffer = [];
var skinIndexBuffer = [];
var skinWeightBuffer = [];
var materialIndexBuffer = [];
this.faces.forEach( function ( face ) {
var flatFace = face.flattenToBuffers();
vertexBuffer.push( flatFace.vertexBuffer );
normalBuffer.push( flatFace.normalBuffer );
uvBuffer.push( flatFace.uvBuffer );
skinIndexBuffer.push( flatFace.skinIndexBuffer );
skinWeightBuffer.push( flatFace.skinWeightBuffer );
materialIndexBuffer.push( face.materialIndexBuffer );
} );
return {
vertexBuffer: vertexBuffer,
normalBuffer: normalBuffer,
uvBuffer: uvBuffer,
skinIndexBuffer: skinIndexBuffer,
skinWeightBuffer: skinWeightBuffer,
materialIndexBuffer: materialIndexBuffer
};
}
} );
function TextParser() {}
Object.assign( TextParser.prototype, {
getPrevNode: function () {
return this.nodeStack[ this.currentIndent - 2 ];
},
getCurrentNode: function () {
return this.nodeStack[ this.currentIndent - 1 ];
},
getCurrentProp: function () {
return this.currentProp;
},
pushStack: function ( node ) {
this.nodeStack.push( node );
this.currentIndent += 1;
},
popStack: function () {
this.nodeStack.pop();
this.currentIndent -= 1;
},
setCurrentProp: function ( val, name ) {
this.currentProp = val;
this.currentPropName = name;
},
// ----------parse ---------------------------------------------------
parse: function ( text ) {
this.currentIndent = 0;
this.allNodes = new FBXTree();
this.nodeStack = [];
this.currentProp = [];
this.currentPropName = '';
var split = text.split( "\n" );
for ( var line in split ) {
var l = split[ line ];
// short cut
if ( l.match( /^[\s\t]*;/ ) ) {
continue;
} // skip comment line
if ( l.match( /^[\s\t]*$/ ) ) {
continue;
} // skip empty line
// beginning of node
var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' );
var match = l.match( beginningOfNodeExp );
if ( match ) {
var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" );
var nodeAttrs = match[ 2 ].split( ',' ).map( function ( element ) {
return element.trim().replace( /^"/, '' ).replace( /"$/, '' );
} );
this.parseNodeBegin( l, nodeName, nodeAttrs || null );
continue;
}
// node's property
var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" );
var match = l.match( propExp );
if ( match ) {
var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
this.parseNodeProperty( l, propName, propValue );
continue;
}
// end of node
var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" );
if ( l.match( endOfNodeExp ) ) {
this.nodeEnd();
continue;
}
// for special case,
//
// Vertices: *8670 {
// a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
// -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
// 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
// 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
//
// these case the lines must contiue with previous line
if ( l.match( /^[^\s\t}]/ ) ) {
this.parseNodePropertyContinued( l );
}
}
return this.allNodes;
},
parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
// var nodeName = match[1];
var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
var attrs = this.parseNodeAttr( nodeAttrs );
var currentNode = this.getCurrentNode();
// a top node
if ( this.currentIndent === 0 ) {
this.allNodes.add( nodeName, node );
} else {
// a subnode
// already exists subnode, then append it
if ( nodeName in currentNode.subNodes ) {
var tmp = currentNode.subNodes[ nodeName ];
// console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
if ( attrs.id === '' ) {
currentNode.subNodes[ nodeName ] = [];
currentNode.subNodes[ nodeName ].push( tmp );
} else {
currentNode.subNodes[ nodeName ] = {};
currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
}
}
if ( attrs.id === '' ) {
currentNode.subNodes[ nodeName ].push( node );
} else {
currentNode.subNodes[ nodeName ][ attrs.id ] = node;
}
} else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
currentNode.subNodes[ nodeName ] = {};
currentNode.subNodes[ nodeName ][ attrs.id ] = node;
} else {
currentNode.subNodes[ nodeName ] = node;
}
}
// for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
if ( nodeAttrs ) {
node.id = attrs.id;
node.attrName = attrs.name;
node.attrType = attrs.type;
}
this.pushStack( node );
},
parseNodeAttr: function ( attrs ) {
var id = attrs[ 0 ];
if ( attrs[ 0 ] !== "" ) {
id = parseInt( attrs[ 0 ] );
if ( isNaN( id ) ) {
// PolygonVertexIndex: *16380 {
id = attrs[ 0 ];
}
}
var name;
var type;
if ( attrs.length > 1 ) {
name = attrs[ 1 ].replace( /^(\w+)::/, '' );
type = attrs[ 2 ];
}
return { id: id, name: name || '', type: type || '' };
},
parseNodeProperty: function ( line, propName, propValue ) {
var currentNode = this.getCurrentNode();
var parentName = currentNode.name;
// special case parent node's is like "Properties70"
// these chilren nodes must treat with careful
if ( parentName !== undefined ) {
var propMatch = parentName.match( /Properties(\d)+/ );
if ( propMatch ) {
this.parseNodeSpecialProperty( line, propName, propValue );
return;
}
}
// special case Connections
if ( propName == 'C' ) {
var connProps = propValue.split( ',' ).slice( 1 );
var from = parseInt( connProps[ 0 ] );
var to = parseInt( connProps[ 1 ] );
var rest = propValue.split( ',' ).slice( 3 );
propName = 'connections';
propValue = [ from, to ];
propValue = propValue.concat( rest );
if ( currentNode.properties[ propName ] === undefined ) {
currentNode.properties[ propName ] = [];
}
}
// special case Connections
if ( propName == 'Node' ) {
var id = parseInt( propValue );
currentNode.properties.id = id;
currentNode.id = id;
}
// already exists in properties, then append this
if ( propName in currentNode.properties ) {
// console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
if ( Array.isArray( currentNode.properties[ propName ] ) ) {
currentNode.properties[ propName ].push( propValue );
} else {
currentNode.properties[ propName ] += propValue;
}
} else {
// console.log( propName + ": " + propValue );
if ( Array.isArray( currentNode.properties[ propName ] ) ) {
currentNode.properties[ propName ].push( propValue );
} else {
currentNode.properties[ propName ] = propValue;
}
}
this.setCurrentProp( currentNode.properties, propName );
},
// TODO:
parseNodePropertyContinued: function ( line ) {
this.currentProp[ this.currentPropName ] += line;
},
parseNodeSpecialProperty: function ( line, propName, propValue ) {
// split this
// P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
// into array like below
// ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
var props = propValue.split( '",' ).map( function ( element ) {
return element.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
} );
var innerPropName = props[ 0 ];
var innerPropType1 = props[ 1 ];
var innerPropType2 = props[ 2 ];
var innerPropFlag = props[ 3 ];
var innerPropValue = props[ 4 ];
/*
if ( innerPropValue === undefined ) {
innerPropValue = props[3];
}
*/
// cast value in its type
switch ( innerPropType1 ) {
case "int":
innerPropValue = parseInt( innerPropValue );
break;
case "double":
innerPropValue = parseFloat( innerPropValue );
break;
case "ColorRGB":
case "Vector3D":
var tmp = innerPropValue.split( ',' );
innerPropValue = new THREE.Vector3( tmp[ 0 ], tmp[ 1 ], tmp[ 2 ] );
break;
}
// CAUTION: these props must append to parent's parent
this.getPrevNode().properties[ innerPropName ] = {
'type': innerPropType1,
'type2': innerPropType2,
'flag': innerPropFlag,
'value': innerPropValue
};
this.setCurrentProp( this.getPrevNode().properties, innerPropName );
},
nodeEnd: function () {
this.popStack();
},
/* ---------------------------------------------------------------- */
/* util */
isFlattenNode: function ( node ) {
return ( 'subNodes' in node && 'properties' in node ) ? true : false;
}
} );
function FBXTree() {}
Object.assign( FBXTree.prototype, {
add: function ( key, val ) {
this[ key ] = val;
},
searchConnectionParent: function ( id ) {
if ( this.__cache_search_connection_parent === undefined ) {
this.__cache_search_connection_parent = [];
}
if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
return this.__cache_search_connection_parent[ id ];
} else {
this.__cache_search_connection_parent[ id ] = [];
}
var conns = this.Connections.properties.connections;
var results = [];
for ( var i = 0; i < conns.length; ++ i ) {
if ( conns[ i ][ 0 ] == id ) {
// 0 means scene root
var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
results.push( res );
}
}
if ( results.length > 0 ) {
this.__cache_search_connection_parent[ id ] = this.__cache_search_connection_parent[ id ].concat( results );
return results;
} else {
this.__cache_search_connection_parent[ id ] = [ - 1 ];
return [ - 1 ];
}
},
searchConnectionChildren: function ( id ) {
if ( this.__cache_search_connection_children === undefined ) {
this.__cache_search_connection_children = [];
}
if ( this.__cache_search_connection_children[ id ] !== undefined ) {
return this.__cache_search_connection_children[ id ];
} else {
this.__cache_search_connection_children[ id ] = [];
}
var conns = this.Connections.properties.connections;
var res = [];
for ( var i = 0; i < conns.length; ++ i ) {
if ( conns[ i ][ 1 ] == id ) {
// 0 means scene root
res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
// there may more than one kid, then search to the end
}
}
if ( res.length > 0 ) {
this.__cache_search_connection_children[ id ] = this.__cache_search_connection_children[ id ].concat( res );
return res;
} else {
this.__cache_search_connection_children[ id ] = [ ];
return [ ];
}
},
searchConnectionType: function ( id, to ) {
var key = id + ',' + to; // TODO: to hash
if ( this.__cache_search_connection_type === undefined ) {
this.__cache_search_connection_type = {};
}
if ( this.__cache_search_connection_type[ key ] !== undefined ) {
return this.__cache_search_connection_type[ key ];
} else {
this.__cache_search_connection_type[ key ] = '';
}
var conns = this.Connections.properties.connections;
for ( var i = 0; i < conns.length; ++ i ) {
if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
// 0 means scene root
this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
return conns[ i ][ 2 ];
}
}
this.__cache_search_connection_type[ id ] = null;
return null;
}
} );
/**
* @returns {boolean}
*/
function isFbxFormatASCII( text ) {
var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
var cursor = 0;
var read = function ( offset ) {
var result = text[ offset - 1 ];
text = text.slice( cursor + offset );
cursor ++;
return result;
};
for ( var i = 0; i < CORRECT.length; ++ i ) {
var num = read( 1 );
if ( num == CORRECT[ i ] ) {
return false;
}
}
return true;
}
/**
* @returns {number}
*/
function getFbxVersion( text ) {
var versionRegExp = /FBXVersion: (\d+)/;
var match = text.match( versionRegExp );
if ( match ) {
var version = parseInt( match[ 1 ] );
return version;
}
throw new Error( 'FBXLoader: Cannot find the version number for the file given.' );
}
/**
* Parses comma separated list of float numbers and returns them in an array.
* @example
* // Returns [ 5.6, 9.4, 2.5, 1.4 ]
* parseFloatArray( "5.6,9.4,2.5,1.4" )
* @returns {number[]}
*/
function parseFloatArray( floatString ) {
return floatString.split( ',' ).map( function ( stringValue ) {
return parseFloat( stringValue );
} );
}
/**
* Parses comma separated list of int numbers and returns them in an array.
* @example
* // Returns [ 5, 8, 2, 3 ]
* parseFloatArray( "5,8,2,3" )
* @returns {number[]}
*/
function parseIntArray( intString ) {
return intString.split( ',' ).map( function ( stringValue ) {
return parseInt( stringValue );
} );
}
function parseMatrixArray( floatString ) {
return new THREE.Matrix4().fromArray( parseFloatArray( floatString ) );
}
} )();
......@@ -36,7 +36,7 @@
<script src="js/curves/NURBSCurve.js"></script>
<script src="js/curves/NURBSUtils.js"></script>
<script src="js/loaders/FBXLoader.js"></script>
<script src="js/loaders/FBXLoader2.js"></script>
<script src="js/Detector.js"></script>
<script src="js/libs/stats.min.js"></script>
......@@ -95,29 +95,30 @@
};
var loader = new THREE.FBXLoader( manager );
loader.load( 'models/fbx/xsi_man_skinning.fbx', function( object ) {
debugger;
loader.load( 'models/fbx/xsi_man.fbx', function( object ) {
object.traverse( function( child ) {
if ( child instanceof THREE.Mesh ) {
// if ( child instanceof THREE.Mesh ) {
// pass
// // pass
}
// }
if ( child instanceof THREE.SkinnedMesh ) {
// if ( child instanceof THREE.SkinnedMesh ) {
if ( child.geometry.animations !== undefined || child.geometry.morphAnimations !== undefined ) {
// if ( child.geometry.animations !== undefined || child.geometry.morphAnimations !== undefined ) {
child.mixer = new THREE.AnimationMixer( child );
mixers.push( child.mixer );
// child.mixer = new THREE.AnimationMixer( child );
// mixers.push( child.mixer );
var action = child.mixer.clipAction( child.geometry.animations[ 0 ] );
action.play();
// var action = child.mixer.clipAction( child.geometry.animations[ 0 ] );
// action.play();
}
// }
}
// }
} );
......
{
"globalDependencies": {
"three": "registry:dt/three#0.0.0+20161228004308"
}
}
因为 它太大了无法显示 source diff 。你可以改为 查看blob
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/962bd3a27382a5164f5aec29a42e7c5f4f6eca36/three/index.d.ts",
"raw": "registry:dt/three#0.0.0+20161228004308",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/962bd3a27382a5164f5aec29a42e7c5f4f6eca36/three/index.d.ts"
}
}
/// <reference path="globals/three/index.d.ts" />
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册