123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956 |
- /**
- * @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 = resourceDirectory.join( '/' );
- 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 parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
- connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
- if ( ! connectionMap.has( connection[ 1 ] ) ) {
- connectionMap.set( connection[ 1 ], {
- parents: [],
- children: []
- } );
- }
- var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
- connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
- } );
- }
- 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;
- }
- debugger;
- 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 );
- console.log( deformerMap );
- /**
- * @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 );
- skeleton.FBX_ID = parseInt( nodeID );
- 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,
- bones: []
- };
- }
- }
- var geometryMap = parseGeometries( FBXTree, connections, deformerMap );
- console.log( geometryMap );
- /**
- * @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 ] < 0 ) {
- 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;
- }
- }
- debugger;
- /**
- * @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; materialBufferIndex < 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[ 0 ];
- 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[ 0 ];
- 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[ 0 ];
- 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 );
- console.log( sceneGraph );
- return sceneGraph;
- /**
- * Finally generates Scene graph and Scene graph Objects.
- * @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
- * @returns {THREE.Group}
- */
- function parseScene( FBXTree, connections, deformerMap, geometryMap, materialMap ) {
- var sceneGraph = new THREE.Group();
- var ModelNode = FBXTree.Objects.subNodes.Model;
- /**
- * @type {Array.<THREE.Object3D>}
- */
- var modelArray = [];
- /**
- * @type {Map.<number, THREE.Object3D>}
- */
- var modelMap = new Map();
- for ( var nodeID in ModelNode ) {
- var id = parseInt( nodeID );
- var node = ModelNode[ nodeID ];
- var conns = connections.get( id );
- var model = null;
- for ( var i = 0; i < conns.parents.length; ++ i ) {
- deformerMap.forEach( function ( deformer ) {
- if ( deformer.map.has( conns.parents[ i ].ID ) ) {
- model = new THREE.Bone();
- var index = deformer.array.findIndex( function ( subDeformer ) {
- return subDeformer.FBX_ID === conns.parents[ i ].ID;
- } );
- deformer.bones[ index ] = model;
- }
- } );
- }
- if ( ! model ) {
- switch ( node.attrType ) {
- case "Mesh":
- /**
- * @type {?THREE.BufferGeometry}
- */
- var geometry = null;
- /**
- * @type {THREE.MultiMaterial|THREE.Material}
- */
- var material = null;
- /**
- * @type {Array.<THREE.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 } );
- }
- if ( geometry.FBX_Deformer ) {
- model = new THREE.SkinnedMesh( geometry, material );
- } else {
- 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 ) );
- }
- modelArray.push( model );
- modelMap.set( id, model );
- }
- modelArray.forEach( function ( model ) {
- var conns = connections.get( model.FBX_ID );
- conns.parents.forEach( function ( parent ) {
- for ( var i = 0; i < modelArray.length; ++ i ) {
- if ( modelArray[ i ].FBX_ID === parent.ID ) {
- modelArray[ i ].add( model );
- return;
- }
- }
- //Parent not found, root node?
- if ( parent.ID === 0 ) {
- sceneGraph.add( model );
- }
- } );
- } );
- // Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
- sceneGraph.updateMatrixWorld( true );
- deformerMap.forEach( function ( deformer, FBX_ID ) {
- deformer.skeleton = new THREE.Skeleton( deformer.bones );
- var conns = connections.get( FBX_ID );
- conns.parents.forEach( function ( parent ) {
- if ( geometryMap.has( parent.ID ) ) {
- var geoID = parent.ID;
- var geoConns = connections.get( geoID );
- for ( var i = 0; i < geoConns.parents.length; ++ i ) {
- if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
- var model = modelMap.get( geoConns.parents[ i ].ID );
- //ASSERT model typeof SkinnedMesh
- model.bind( deformer.skeleton, model.matrixWorld );
- break;
- }
- }
- }
- } );
- } );
- return sceneGraph;
- }
- // UTILS
- /**
- * Parses Vector3 property from FBXTree. Property is given as .value.x, .value.y, etc.
- * @param {{value: { x: string, y: string, z: string }}} property - Property to parse as Vector3.
- * @returns {THREE.Vector3}
- */
- function parseVector3( property ) {
- return new THREE.Vector3( parseFloat( property.value.x ), parseFloat( property.value.y ), parseFloat( property.value.z ) );
- }
- /**
- * Parses Color property from FBXTree. Property is given as .value.x, .value.y, etc.
- * @param {{value: { x: string, y: string, z: string }}} property - Property to parse as Color.
- * @returns {THREE.Color}
- */
- 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 = vertexBuffer.concat( flatVertex.vertexBuffer );
- normalBuffer = normalBuffer.concat( flatVertex.normalBuffer );
- uvBuffer = uvBuffer.concat( flatVertex.uvBuffer );
- skinIndexBuffer = skinIndexBuffer.concat( flatVertex.skinIndexBuffer );
- skinWeightBuffer = skinWeightBuffer.concat( 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 = [];
- var materialIndex = this.materialIndex;
- this.triangles.forEach( function ( triangle ) {
- var flatTriangle = triangle.flattenToBuffers();
- vertexBuffer = vertexBuffer.concat( flatTriangle.vertexBuffer );
- normalBuffer = normalBuffer.concat( flatTriangle.normalBuffer );
- uvBuffer = uvBuffer.concat( flatTriangle.uvBuffer );
- skinIndexBuffer = skinIndexBuffer.concat( flatTriangle.skinIndexBuffer );
- skinWeightBuffer = skinWeightBuffer.concat( flatTriangle.skinWeightBuffer );
- materialIndexBuffer = materialIndexBuffer.concat( [ materialIndex, materialIndex, 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 {{}|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 = vertexBuffer.concat( flatFace.vertexBuffer );
- normalBuffer = normalBuffer.concat( flatFace.normalBuffer );
- uvBuffer = uvBuffer.concat( flatFace.uvBuffer );
- skinIndexBuffer = skinIndexBuffer.concat( flatFace.skinIndexBuffer );
- skinWeightBuffer = skinWeightBuffer.concat( flatFace.skinWeightBuffer );
- materialIndexBuffer = materialIndexBuffer.concat( flatFace.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 ) );
- }
- } )();
|