FBXLoader.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241
  1. /**
  2. * @author yamahigashi https://github.com/yamahigashi
  3. * @author Kyle-Larson https://github.com/Kyle-Larson
  4. *
  5. * This loader loads FBX file in *ASCII and version 7 format*.
  6. *
  7. * Support
  8. * - mesh
  9. * - skinning
  10. * - normal / uv
  11. * - material (Multi-Material too)
  12. * - textures (Must be in same directory)
  13. * - nurbs (Open, Closed and Periodic forms)
  14. *
  15. * No Support
  16. * - morph
  17. */
  18. ( function () {
  19. THREE.FBXLoader = function ( manager ) {
  20. THREE.Loader.call( this );
  21. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  22. this.textureLoader = null;
  23. this.textureBasePath = null;
  24. };
  25. THREE.FBXLoader.prototype = Object.create( THREE.Loader.prototype );
  26. THREE.FBXLoader.prototype.constructor = THREE.FBXLoader;
  27. Object.assign( THREE.FBXLoader.prototype, {
  28. load: function ( url, onLoad, onProgress, onError ) {
  29. var scope = this;
  30. var loader = new THREE.FileLoader( scope.manager );
  31. // loader.setCrossOrigin( this.crossOrigin );
  32. loader.load( url, function ( text ) {
  33. if ( ! scope.isFbxFormatASCII( text ) ) {
  34. console.warn( 'FBXLoader: !!! FBX Binary format not supported !!!' );
  35. } else if ( ! scope.isFbxVersionSupported( text ) ) {
  36. console.warn( 'FBXLoader: !!! FBX Version below 7 not supported !!!' );
  37. } else {
  38. scope.textureBasePath = scope.extractUrlBase( url );
  39. onLoad( scope.parse( text ) );
  40. }
  41. }, onProgress, onError );
  42. },
  43. setCrossOrigin: function ( value ) {
  44. this.crossOrigin = value;
  45. },
  46. isFbxFormatASCII: function ( body ) {
  47. var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
  48. var cursor = 0;
  49. var read = function ( offset ) {
  50. var result = body[ offset - 1 ];
  51. body = body.slice( cursor + offset );
  52. cursor ++;
  53. return result;
  54. };
  55. for ( var i = 0; i < CORRECT.length; ++ i ) {
  56. var num = read( 1 );
  57. if ( num == CORRECT[ i ] ) {
  58. return false;
  59. }
  60. }
  61. return true;
  62. },
  63. isFbxVersionSupported: function ( body ) {
  64. var versionExp = /FBXVersion: (\d+)/;
  65. var match = body.match( versionExp );
  66. if ( match ) {
  67. var version = parseInt( match[ 1 ] );
  68. console.log( 'FBXLoader: FBX version ' + version );
  69. return version >= 7000;
  70. }
  71. return false;
  72. },
  73. parse: function ( text ) {
  74. var scope = this;
  75. console.time( 'FBXLoader' );
  76. console.time( 'FBXLoader: TextParser' );
  77. var nodes = new FBXParser().parse( text );
  78. console.timeEnd( 'FBXLoader: TextParser' );
  79. console.time( 'FBXLoader: ObjectParser' );
  80. scope.hierarchy = ( new Bones() ).parseHierarchy( nodes );
  81. scope.weights = ( new Weights() ).parse( nodes, scope.hierarchy );
  82. scope.animations = ( new Animation() ).parse( nodes, scope.hierarchy );
  83. scope.textures = ( new Textures() ).parse( nodes, scope.hierarchy );
  84. scope.materials = ( new Materials() ).parse( nodes, scope.hierarchy );
  85. scope.geometries = ( new Geometries() ).parse( nodes, scope.hierarchy );
  86. console.timeEnd( 'FBXLoader: ObjectParser' );
  87. this.texture_cache = {};
  88. this.material_cache = {};
  89. this.geometry_cache = {};
  90. console.time( 'FBXLoader: MeshParser' );
  91. var meshes = this.parseMeshes( nodes );
  92. console.timeEnd( 'FBXLoader: MeshParser' );
  93. var container = new THREE.Group();
  94. for ( var i = 0; i < meshes.length; ++ i ) {
  95. if ( meshes[ i ] === undefined ) {
  96. continue;
  97. }
  98. container.add( meshes[ i ] );
  99. //wireframe = new THREE.WireframeHelper( geometries[i], 0x00ff00 );
  100. //container.add( wireframe );
  101. //vnh = new THREE.VertexNormalsHelper( geometries[i], 0.6 );
  102. //container.add( vnh );
  103. //skh = new THREE.SkeletonHelper( geometries[i] );
  104. //container.add( skh );
  105. // container.add( new THREE.BoxHelper( geometries[i] ) );
  106. }
  107. console.timeEnd( 'FBXLoader' );
  108. return container;
  109. },
  110. getTexture: function ( texNode ) {
  111. if ( ! ( texNode.id in this.texture_cache ) ) {
  112. if ( this.textureLoader === null ) {
  113. this.textureLoader = new THREE.TextureLoader();
  114. }
  115. this.texture_cache[ texNode.id ] = this.textureLoader.load( this.textureBasePath + '/' + texNode.fileName );
  116. }
  117. return this.texture_cache[ texNode.id ];
  118. },
  119. getMaterial: function ( matNode, nodes ) {
  120. if ( ! ( matNode.id in this.material_cache ) ) {
  121. // TODO:
  122. // Cannot find a list of possible ShadingModel values.
  123. // If someone finds a list, please add additional cases
  124. // and map to appropriate materials.
  125. var tmpMat;
  126. switch ( matNode.type ) {
  127. case "phong":
  128. tmpMat = new THREE.MeshPhongMaterial();
  129. break;
  130. case "lambert":
  131. tmpMat = new THREE.MeshLambertMaterial();
  132. break;
  133. default:
  134. console.warn( "No implementation given for material type " + matNode.type + " in FBXLoader.js. Defaulting to basic material" );
  135. tmpMat = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
  136. break;
  137. }
  138. var children = nodes.searchConnectionChildren( matNode.id );
  139. for ( var i = 0; i < children.length; ++ i ) {
  140. var type = nodes.searchConnectionType( children[ i ], matNode.id );
  141. switch ( type ) {
  142. case " \"AmbientColor":
  143. //TODO: Support AmbientColor textures
  144. break;
  145. case " \"DiffuseColor":
  146. matNode.parameters.map = this.getTexture( this.textures.textures[ children[ i ] ] );
  147. break;
  148. default:
  149. console.warn( 'Unknown texture application of type ' + type + ', skipping texture' );
  150. break;
  151. }
  152. }
  153. tmpMat.setValues( matNode.parameters );
  154. this.material_cache[ matNode.id ] = tmpMat;
  155. }
  156. return this.material_cache[ matNode.id ];
  157. },
  158. getGeometry: function ( geoNode ) {
  159. if ( ! ( geoNode.id in this.geometry_cache ) ) {
  160. var tmpGeo = new THREE.BufferGeometry();
  161. tmpGeo.name = geoNode.name;
  162. tmpGeo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geoNode.vertices ), 3 ) );
  163. if ( geoNode.normals !== undefined && geoNode.normals.length > 0 ) {
  164. tmpGeo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geoNode.normals ), 3 ) );
  165. }
  166. if ( geoNode.uvs !== undefined && geoNode.uvs.length > 0 ) {
  167. tmpGeo.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geoNode.uvs ), 2 ) );
  168. }
  169. if ( geoNode.indices !== undefined && geoNode.indices.length > 0 ) {
  170. tmpGeo.setIndex( geoNode.indices );
  171. }
  172. tmpGeo.verticesNeedUpdate = true;
  173. tmpGeo.computeBoundingSphere();
  174. tmpGeo.computeBoundingBox();
  175. //Material groupings
  176. if ( geoNode.materialIndices.length > 1 ) {
  177. tmpGeo.groups = [];
  178. for ( var i = 0, prevIndex = - 1; i < geoNode.materialIndices.length; ++ i ) {
  179. if ( geoNode.materialIndices[ i ] !== prevIndex ) {
  180. tmpGeo.groups.push( { start: i * 3, count: 0, materialIndex: geoNode.materialIndices[ i ] } );
  181. prevIndex = geoNode.materialIndices[ i ];
  182. }
  183. tmpGeo.groups[ tmpGeo.groups.length - 1 ].count += 3;
  184. }
  185. }
  186. this.geometry_cache[ geoNode.id ] = new THREE.Geometry().fromBufferGeometry( tmpGeo );
  187. this.geometry_cache[ geoNode.id ].bones = geoNode.bones;
  188. this.geometry_cache[ geoNode.id ].skinIndices = this.weights.skinIndices;
  189. this.geometry_cache[ geoNode.id ].skinWeights = this.weights.skinWeights;
  190. }
  191. return this.geometry_cache[ geoNode.id ];
  192. },
  193. parseMeshes: function ( node ) {
  194. var modelNode = node.Objects.subNodes.Model;
  195. var meshes = [];
  196. for ( var ID in modelNode ) {
  197. if ( modelNode[ ID ].attrType === 'Mesh' ) {
  198. //Parse Mesh
  199. meshes.push( this.parseMesh( modelNode[ ID ], node ) );
  200. } else if ( modelNode[ ID ].attrType === 'NurbsCurve' ) {
  201. //Parse NURBS
  202. meshes.push( this.parseNURBS( modelNode[ ID ], node ) );
  203. }
  204. }
  205. return meshes;
  206. },
  207. parseFloatList: function ( floatList ) {
  208. return floatList.split( ',' ).map( function ( number ) {
  209. return parseFloat( number );
  210. } );
  211. },
  212. parseNURBS: function ( meshNode, FBXNodes ) {
  213. if ( THREE.NURBSCurve === undefined ) {
  214. console.error( "THREE.FBXLoader relies on THREE.NURBSCurve" );
  215. return;
  216. }
  217. var geoNodes = FBXNodes.Objects.subNodes.Geometry;
  218. var children = FBXNodes.searchConnectionChildren( meshNode.id );
  219. var nurbsInfo;
  220. for ( var i = 0; i < children.length; ++ i ) {
  221. if ( children[ i ] in geoNodes ) {
  222. nurbsInfo = geoNodes[ children[ i ] ];
  223. break;
  224. }
  225. }
  226. if ( nurbsInfo === undefined ) {
  227. return;
  228. }
  229. var order = parseInt( nurbsInfo.properties.Order );
  230. if ( isNaN( order ) ) {
  231. console.error( "Invalid Order: `" + nurbsInfo.properties.Order + "` (should be an integer)" );
  232. return;
  233. }
  234. var degree = order - 1;
  235. var knots = this.parseFloatList( nurbsInfo.subNodes.KnotVector.properties.a );
  236. var controlPoints = [];
  237. var pointsValues = this.parseFloatList( nurbsInfo.subNodes.Points.properties.a );
  238. for ( var i = 0; i < pointsValues.length; i += 4 ) {
  239. // NURBSCurve recreates a Vector4, so no need to construct it twice
  240. controlPoints.push( { x: pointsValues[ i ], y: pointsValues[ i + 1 ], z: pointsValues[ i + 2 ], w: pointsValues[ i + 3 ] } );
  241. }
  242. var startKnot, endKnot;
  243. if ( nurbsInfo.properties.Form == "Closed" ) {
  244. controlPoints.push( controlPoints[ 0 ] );
  245. } else if ( nurbsInfo.properties.Form === 'Periodic' ) {
  246. startKnot = degree;
  247. endKnot = knots.length - 1 - startKnot;
  248. for ( var i = 0; i < degree; ++ i ) {
  249. controlPoints.push( controlPoints[ i ] );
  250. }
  251. }
  252. var curve = new THREE.NURBSCurve( degree, knots, controlPoints, startKnot, endKnot );
  253. // Pre-generate a geometry
  254. var geometry = new THREE.Geometry();
  255. geometry.vertices = curve.getPoints( controlPoints.length * 7 );
  256. var mesh = new THREE.Line( geometry );
  257. // Store the THREE.NURBSCurve class so the user can recreate a new geometry with a different number of points
  258. mesh.userData.curve = curve;
  259. return mesh;
  260. },
  261. parseMesh: function ( meshNode, FBXNodes ) {
  262. var geoNodes = FBXNodes.Objects.subNodes.Geometry;
  263. var matNodes = FBXNodes.Objects.subNodes.Material;
  264. var children = FBXNodes.searchConnectionChildren( meshNode.id );
  265. var geometry;
  266. var materials = [];
  267. var material;
  268. var mesh;
  269. for ( var i = 0; i < children.length; ++ i ) {
  270. if ( children[ i ] in geoNodes ) {
  271. geometry = this.getGeometry( this.geometries.geometries[ children[ i ] ] );
  272. continue;
  273. }
  274. if ( children[ i ] in matNodes ) {
  275. materials.push( this.getMaterial( this.materials.materials[ children[ i ] ], FBXNodes ) );
  276. continue;
  277. }
  278. }
  279. if ( materials.length > 1 ) {
  280. material = new THREE.MultiMaterial( materials );
  281. //material = materials[ 0 ];
  282. } else {
  283. material = materials[ 0 ];
  284. }
  285. if ( geometry.bones !== undefined && geometry.skinWeights !== undefined && geometry.skinWeights.length > 0 ) {
  286. mesh = new THREE.SkinnedMesh( geometry, material );
  287. } else {
  288. mesh = new THREE.Mesh( geometry, material );
  289. }
  290. if ( this.animations !== undefined ) {
  291. this.addAnimation( mesh, this.weights.matrices, this.animations );
  292. }
  293. return mesh;
  294. },
  295. addAnimation: function ( mesh, matrices, animations ) {
  296. for ( var key in animations.stacks ) {
  297. var animationData = {
  298. name: animations.stacks[ key ].name,
  299. fps: 30,
  300. length: animations.stacks[ key ].length,
  301. hierarchy: []
  302. };
  303. for ( var i = 0; i < mesh.geometry.bones.length; ++ i ) {
  304. var name = mesh.geometry.bones[ i ].name;
  305. name = name.replace( /.*:/, '' );
  306. animationData.hierarchy.push( { parent: mesh.geometry.bones[ i ].parent, name: name, keys: [] } );
  307. }
  308. function hasCurve( animNode, attr ) {
  309. if ( animNode === undefined ) {
  310. return false;
  311. }
  312. var attrNode;
  313. switch ( attr ) {
  314. case 'S':
  315. if ( ! ( animNode.S ) ) {
  316. return false;
  317. }
  318. attrNode = animNode.S;
  319. break;
  320. case 'R':
  321. if ( ! ( animNode.R ) ) {
  322. return false;
  323. }
  324. attrNode = animNode.R;
  325. break;
  326. case 'T':
  327. if ( ! ( animNode.T ) ) {
  328. return false;
  329. }
  330. attrNode = animNode.T;
  331. break;
  332. }
  333. if ( attrNode.curves.x === undefined ) {
  334. return false;
  335. }
  336. if ( attrNode.curves.y === undefined ) {
  337. return false;
  338. }
  339. if ( attrNode.curves.z === undefined ) {
  340. return false;
  341. }
  342. return true;
  343. }
  344. function hasKeyOnFrame( attrNode, frame ) {
  345. var x = isKeyExistOnFrame( attrNode.curves.x, frame );
  346. var y = isKeyExistOnFrame( attrNode.curves.y, frame );
  347. var z = isKeyExistOnFrame( attrNode.curves.z, frame );
  348. return x && y && z;
  349. }
  350. function isKeyExistOnFrame( curve, frame ) {
  351. var value = curve.values[ frame ];
  352. return value !== undefined;
  353. }
  354. function genKey( animNode, bone ) {
  355. // key initialize with its bone's bind pose at first
  356. var key = {};
  357. key.time = frame / animations.fps; // TODO:
  358. key.pos = bone.pos;
  359. key.rot = bone.rotq;
  360. key.scl = bone.scl;
  361. if ( animNode === undefined ) {
  362. return key;
  363. }
  364. try {
  365. if ( hasCurve( animNode, 'T' ) && hasKeyOnFrame( animNode.T, frame ) ) {
  366. var pos = new THREE.Vector3(
  367. animNode.T.curves.x.values[ frame ],
  368. animNode.T.curves.y.values[ frame ],
  369. animNode.T.curves.z.values[ frame ] );
  370. key.pos = [ pos.x, pos.y, pos.z ];
  371. }
  372. if ( hasCurve( animNode, 'R' ) && hasKeyOnFrame( animNode.R, frame ) ) {
  373. var rx = degToRad( animNode.R.curves.x.values[ frame ] );
  374. var ry = degToRad( animNode.R.curves.y.values[ frame ] );
  375. var rz = degToRad( animNode.R.curves.z.values[ frame ] );
  376. var eul = new THREE.Vector3( rx, ry, rz );
  377. var rot = quatFromVec( eul.x, eul.y, eul.z );
  378. key.rot = [ rot.x, rot.y, rot.z, rot.w ];
  379. }
  380. if ( hasCurve( animNode, 'S' ) && hasKeyOnFrame( animNode.S, frame ) ) {
  381. var scl = new THREE.Vector3(
  382. animNode.S.curves.x.values[ frame ],
  383. animNode.S.curves.y.values[ frame ],
  384. animNode.S.curves.z.values[ frame ] );
  385. key.scl = [ scl.x, scl.y, scl.z ];
  386. }
  387. } catch ( e ) {
  388. // curve is not full plotted
  389. console.log( bone );
  390. console.log( e );
  391. }
  392. return key;
  393. }
  394. var bones = mesh.geometry.bones;
  395. for ( var frame = 0; frame < animations.stacks[ key ].frames; frame ++ ) {
  396. for ( i = 0; i < bones.length; i ++ ) {
  397. var bone = bones[ i ];
  398. var animNode = animations.stacks[ key ].layers[ 0 ][ i ];
  399. for ( var j = 0; j < animationData.hierarchy.length; j ++ ) {
  400. if ( animationData.hierarchy[ j ].name === bone.name ) {
  401. animationData.hierarchy[ j ].keys.push( genKey( animNode, bone ) );
  402. }
  403. }
  404. }
  405. }
  406. if ( mesh.geometry.animations === undefined ) {
  407. mesh.geometry.animations = [];
  408. }
  409. mesh.geometry.animations.push( THREE.AnimationClip.parseAnimation( animationData, mesh.geometry.bones ) );
  410. }
  411. },
  412. loadFile: function ( url, onLoad, onProgress, onError, responseType ) {
  413. var loader = new THREE.FileLoader( this.manager );
  414. loader.setResponseType( responseType );
  415. var request = loader.load( url, onLoad, onProgress, onError );
  416. return request;
  417. },
  418. loadFileAsBuffer: function ( url, onLoad, onProgress, onError ) {
  419. this.loadFile( url, onLoad, onProgress, onError, 'arraybuffer' );
  420. },
  421. loadFileAsText: function ( url, onLoad, onProgress, onError ) {
  422. this.loadFile( url, onLoad, onProgress, onError, 'text' );
  423. }
  424. } );
  425. /* ----------------------------------------------------------------- */
  426. function FBXNodes() {}
  427. Object.assign( FBXNodes.prototype, {
  428. add: function ( key, val ) {
  429. this[ key ] = val;
  430. },
  431. searchConnectionParent: function ( id ) {
  432. if ( this.__cache_search_connection_parent === undefined ) {
  433. this.__cache_search_connection_parent = [];
  434. }
  435. if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
  436. return this.__cache_search_connection_parent[ id ];
  437. } else {
  438. this.__cache_search_connection_parent[ id ] = [];
  439. }
  440. var conns = this.Connections.properties.connections;
  441. var results = [];
  442. for ( var i = 0; i < conns.length; ++ i ) {
  443. if ( conns[ i ][ 0 ] == id ) {
  444. // 0 means scene root
  445. var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
  446. results.push( res );
  447. }
  448. }
  449. if ( results.length > 0 ) {
  450. this.__cache_search_connection_parent[ id ] = this.__cache_search_connection_parent[ id ].concat( results );
  451. return results;
  452. } else {
  453. this.__cache_search_connection_parent[ id ] = [ - 1 ];
  454. return [ - 1 ];
  455. }
  456. },
  457. searchConnectionChildren: function ( id ) {
  458. if ( this.__cache_search_connection_children === undefined ) {
  459. this.__cache_search_connection_children = [];
  460. }
  461. if ( this.__cache_search_connection_children[ id ] !== undefined ) {
  462. return this.__cache_search_connection_children[ id ];
  463. } else {
  464. this.__cache_search_connection_children[ id ] = [];
  465. }
  466. var conns = this.Connections.properties.connections;
  467. var res = [];
  468. for ( var i = 0; i < conns.length; ++ i ) {
  469. if ( conns[ i ][ 1 ] == id ) {
  470. // 0 means scene root
  471. res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
  472. // there may more than one kid, then search to the end
  473. }
  474. }
  475. if ( res.length > 0 ) {
  476. this.__cache_search_connection_children[ id ] = this.__cache_search_connection_children[ id ].concat( res );
  477. return res;
  478. } else {
  479. this.__cache_search_connection_children[ id ] = [ ];
  480. return [ ];
  481. }
  482. },
  483. searchConnectionType: function ( id, to ) {
  484. var key = id + ',' + to; // TODO: to hash
  485. if ( this.__cache_search_connection_type === undefined ) {
  486. this.__cache_search_connection_type = {};
  487. }
  488. if ( this.__cache_search_connection_type[ key ] !== undefined ) {
  489. return this.__cache_search_connection_type[ key ];
  490. } else {
  491. this.__cache_search_connection_type[ key ] = '';
  492. }
  493. var conns = this.Connections.properties.connections;
  494. for ( var i = 0; i < conns.length; ++ i ) {
  495. if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
  496. // 0 means scene root
  497. this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
  498. return conns[ i ][ 2 ];
  499. }
  500. }
  501. this.__cache_search_connection_type[ id ] = null;
  502. return null;
  503. }
  504. } );
  505. function FBXParser() {}
  506. Object.assign( FBXParser.prototype, {
  507. getPrevNode: function () {
  508. return this.nodeStack[ this.currentIndent - 2 ];
  509. },
  510. getCurrentNode: function () {
  511. return this.nodeStack[ this.currentIndent - 1 ];
  512. },
  513. getCurrentProp: function () {
  514. return this.currentProp;
  515. },
  516. pushStack: function ( node ) {
  517. this.nodeStack.push( node );
  518. this.currentIndent += 1;
  519. },
  520. popStack: function () {
  521. this.nodeStack.pop();
  522. this.currentIndent -= 1;
  523. },
  524. setCurrentProp: function ( val, name ) {
  525. this.currentProp = val;
  526. this.currentPropName = name;
  527. },
  528. // ----------parse ---------------------------------------------------
  529. parse: function ( text ) {
  530. this.currentIndent = 0;
  531. this.allNodes = new FBXNodes();
  532. this.nodeStack = [];
  533. this.currentProp = [];
  534. this.currentPropName = '';
  535. var split = text.split( "\n" );
  536. for ( var line in split ) {
  537. var l = split[ line ];
  538. // short cut
  539. if ( l.match( /^[\s\t]*;/ ) ) {
  540. continue;
  541. } // skip comment line
  542. if ( l.match( /^[\s\t]*$/ ) ) {
  543. continue;
  544. } // skip empty line
  545. // beginning of node
  546. var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' );
  547. var match = l.match( beginningOfNodeExp );
  548. if ( match ) {
  549. var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" );
  550. var nodeAttrs = match[ 2 ].split( ',' ).map( function ( element ) {
  551. return element.trim().replace( /^"/, '' ).replace( /"$/, '' );
  552. } );
  553. this.parseNodeBegin( l, nodeName, nodeAttrs || null );
  554. continue;
  555. }
  556. // node's property
  557. var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" );
  558. var match = l.match( propExp );
  559. if ( match ) {
  560. var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  561. var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
  562. this.parseNodeProperty( l, propName, propValue );
  563. continue;
  564. }
  565. // end of node
  566. var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" );
  567. if ( l.match( endOfNodeExp ) ) {
  568. this.nodeEnd();
  569. continue;
  570. }
  571. // for special case,
  572. //
  573. // Vertices: *8670 {
  574. // a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
  575. // -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
  576. // 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
  577. // 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
  578. //
  579. // these case the lines must contiue with previous line
  580. if ( l.match( /^[^\s\t}]/ ) ) {
  581. this.parseNodePropertyContinued( l );
  582. }
  583. }
  584. return this.allNodes;
  585. },
  586. parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
  587. // var nodeName = match[1];
  588. var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
  589. var attrs = this.parseNodeAttr( nodeAttrs );
  590. var currentNode = this.getCurrentNode();
  591. // a top node
  592. if ( this.currentIndent === 0 ) {
  593. this.allNodes.add( nodeName, node );
  594. } else {
  595. // a subnode
  596. // already exists subnode, then append it
  597. if ( nodeName in currentNode.subNodes ) {
  598. var tmp = currentNode.subNodes[ nodeName ];
  599. // console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
  600. if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
  601. if ( attrs.id === '' ) {
  602. currentNode.subNodes[ nodeName ] = [];
  603. currentNode.subNodes[ nodeName ].push( tmp );
  604. } else {
  605. currentNode.subNodes[ nodeName ] = {};
  606. currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
  607. }
  608. }
  609. if ( attrs.id === '' ) {
  610. currentNode.subNodes[ nodeName ].push( node );
  611. } else {
  612. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  613. }
  614. } else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
  615. currentNode.subNodes[ nodeName ] = {};
  616. currentNode.subNodes[ nodeName ][ attrs.id ] = node;
  617. } else {
  618. currentNode.subNodes[ nodeName ] = node;
  619. }
  620. }
  621. // for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
  622. // NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
  623. if ( nodeAttrs ) {
  624. node.id = attrs.id;
  625. node.attrName = attrs.name;
  626. node.attrType = attrs.type;
  627. }
  628. this.pushStack( node );
  629. },
  630. parseNodeAttr: function ( attrs ) {
  631. var id = attrs[ 0 ];
  632. if ( attrs[ 0 ] !== "" ) {
  633. id = parseInt( attrs[ 0 ] );
  634. if ( isNaN( id ) ) {
  635. // PolygonVertexIndex: *16380 {
  636. id = attrs[ 0 ];
  637. }
  638. }
  639. var name;
  640. var type;
  641. if ( attrs.length > 1 ) {
  642. name = attrs[ 1 ].replace( /^(\w+)::/, '' );
  643. type = attrs[ 2 ];
  644. }
  645. return { id: id, name: name || '', type: type || '' };
  646. },
  647. parseNodeProperty: function ( line, propName, propValue ) {
  648. var currentNode = this.getCurrentNode();
  649. var parentName = currentNode.name;
  650. // special case parent node's is like "Properties70"
  651. // these chilren nodes must treat with careful
  652. if ( parentName !== undefined ) {
  653. var propMatch = parentName.match( /Properties(\d)+/ );
  654. if ( propMatch ) {
  655. this.parseNodeSpecialProperty( line, propName, propValue );
  656. return;
  657. }
  658. }
  659. // special case Connections
  660. if ( propName == 'C' ) {
  661. var connProps = propValue.split( ',' ).slice( 1 );
  662. var from = parseInt( connProps[ 0 ] );
  663. var to = parseInt( connProps[ 1 ] );
  664. var rest = propValue.split( ',' ).slice( 3 );
  665. propName = 'connections';
  666. propValue = [ from, to ];
  667. propValue = propValue.concat( rest );
  668. if ( currentNode.properties[ propName ] === undefined ) {
  669. currentNode.properties[ propName ] = [];
  670. }
  671. }
  672. // special case Connections
  673. if ( propName == 'Node' ) {
  674. var id = parseInt( propValue );
  675. currentNode.properties.id = id;
  676. currentNode.id = id;
  677. }
  678. // already exists in properties, then append this
  679. if ( propName in currentNode.properties ) {
  680. // console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
  681. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  682. currentNode.properties[ propName ].push( propValue );
  683. } else {
  684. currentNode.properties[ propName ] += propValue;
  685. }
  686. } else {
  687. // console.log( propName + ": " + propValue );
  688. if ( Array.isArray( currentNode.properties[ propName ] ) ) {
  689. currentNode.properties[ propName ].push( propValue );
  690. } else {
  691. currentNode.properties[ propName ] = propValue;
  692. }
  693. }
  694. this.setCurrentProp( currentNode.properties, propName );
  695. },
  696. // TODO:
  697. parseNodePropertyContinued: function ( line ) {
  698. this.currentProp[ this.currentPropName ] += line;
  699. },
  700. parseNodeSpecialProperty: function ( line, propName, propValue ) {
  701. // split this
  702. // P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
  703. // into array like below
  704. // ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
  705. var props = propValue.split( '",' ).map( function ( element ) {
  706. return element.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
  707. } );
  708. var innerPropName = props[ 0 ];
  709. var innerPropType1 = props[ 1 ];
  710. var innerPropType2 = props[ 2 ];
  711. var innerPropFlag = props[ 3 ];
  712. var innerPropValue = props[ 4 ];
  713. /*
  714. if ( innerPropValue === undefined ) {
  715. innerPropValue = props[3];
  716. }
  717. */
  718. // cast value in its type
  719. switch ( innerPropType1 ) {
  720. case "int":
  721. innerPropValue = parseInt( innerPropValue );
  722. break;
  723. case "double":
  724. innerPropValue = parseFloat( innerPropValue );
  725. break;
  726. case "ColorRGB":
  727. case "Vector3D":
  728. var tmp = innerPropValue.split( ',' );
  729. innerPropValue = new THREE.Vector3( tmp[ 0 ], tmp[ 1 ], tmp[ 2 ] );
  730. break;
  731. }
  732. // CAUTION: these props must append to parent's parent
  733. this.getPrevNode().properties[ innerPropName ] = {
  734. 'type': innerPropType1,
  735. 'type2': innerPropType2,
  736. 'flag': innerPropFlag,
  737. 'value': innerPropValue
  738. };
  739. this.setCurrentProp( this.getPrevNode().properties, innerPropName );
  740. },
  741. nodeEnd: function () {
  742. this.popStack();
  743. },
  744. /* ---------------------------------------------------------------- */
  745. /* util */
  746. isFlattenNode: function ( node ) {
  747. return ( 'subNodes' in node && 'properties' in node ) ? true : false;
  748. }
  749. } );
  750. // generate skinIndices, skinWeights
  751. // @skinIndices: per vertex data, this represents the bone indexes affects that vertex
  752. // @skinWeights: per vertex data, this represents the Weight Values affects that vertex
  753. // @matrices: per `bones` data
  754. function Weights() {
  755. this.skinIndices = [];
  756. this.skinWeights = [];
  757. this.matrices = [];
  758. }
  759. Weights.prototype.parseCluster = function ( node, id, entry ) {
  760. var _p = node.searchConnectionParent( id );
  761. var _indices = parseArrayToInt( entry.subNodes.Indexes.properties.a );
  762. var _weights = parseArrayToFloat( entry.subNodes.Weights.properties.a );
  763. var _transform = parseArrayToMatrix( entry.subNodes.Transform.properties.a );
  764. var _link = parseArrayToMatrix( entry.subNodes.TransformLink.properties.a );
  765. return {
  766. 'parent': _p,
  767. 'id': parseInt( id ),
  768. 'indices': _indices,
  769. 'weights': _weights,
  770. 'transform': _transform,
  771. 'transformlink': _link,
  772. 'linkMode': entry.properties.Mode
  773. };
  774. };
  775. Weights.prototype.parse = function ( node, bones ) {
  776. this.skinIndices = [];
  777. this.skinWeights = [];
  778. this.matrices = [];
  779. var deformers = node.Objects.subNodes.Deformer;
  780. var clusters = {};
  781. for ( var id in deformers ) {
  782. if ( deformers[ id ].attrType === 'Cluster' ) {
  783. if ( ! ( 'Indexes' in deformers[ id ].subNodes ) ) {
  784. continue;
  785. }
  786. //clusters.push( this.parseCluster( node, id, deformers[id] ) );
  787. var cluster = this.parseCluster( node, id, deformers[ id ] );
  788. var boneId = node.searchConnectionChildren( cluster.id )[ 0 ];
  789. clusters[ boneId ] = cluster;
  790. }
  791. }
  792. // this clusters is per Bone data, thus we make this into per vertex data
  793. var weights = [];
  794. var hi = bones.hierarchy;
  795. for ( var b = 0; b < hi.length; ++ b ) {
  796. var bid = hi[ b ].internalId;
  797. if ( clusters[ bid ] === undefined ) {
  798. //console.log( bid );
  799. this.matrices.push( new THREE.Matrix4() );
  800. continue;
  801. }
  802. var clst = clusters[ bid ];
  803. // store transform matrix per bones
  804. this.matrices.push( clst.transform );
  805. //this.matrices.push( clst.transformlink );
  806. for ( var v = 0; v < clst.indices.length; ++ v ) {
  807. if ( weights[ clst.indices[ v ] ] === undefined ) {
  808. weights[ clst.indices[ v ] ] = {};
  809. weights[ clst.indices[ v ] ].joint = [];
  810. weights[ clst.indices[ v ] ].weight = [];
  811. }
  812. // indices
  813. var affect = node.searchConnectionChildren( clst.id );
  814. if ( affect.length > 1 ) {
  815. console.warn( "FBXLoader: node " + clst.id + " have many weight kids: " + affect );
  816. }
  817. weights[ clst.indices[ v ] ].joint.push( bones.getBoneIdfromInternalId( node, affect[ 0 ] ) );
  818. // weight value
  819. weights[ clst.indices[ v ] ].weight.push( clst.weights[ v ] );
  820. }
  821. }
  822. // normalize the skin weights
  823. // TODO - this might be a good place to choose greatest 4 weights
  824. for ( var i = 0; i < weights.length; i ++ ) {
  825. if ( weights[ i ] === undefined ) {
  826. this.skinIndices.push( new THREE.Vector4( 0, 0, 0, 0 ) );
  827. this.skinWeights.push( new THREE.Vector4( 0, 0, 0, 0 ) );
  828. continue;
  829. }
  830. var indicies = new THREE.Vector4(
  831. weights[ i ].joint[ 0 ] ? weights[ i ].joint[ 0 ] : 0,
  832. weights[ i ].joint[ 1 ] ? weights[ i ].joint[ 1 ] : 0,
  833. weights[ i ].joint[ 2 ] ? weights[ i ].joint[ 2 ] : 0,
  834. weights[ i ].joint[ 3 ] ? weights[ i ].joint[ 3 ] : 0 );
  835. var weight = new THREE.Vector4(
  836. weights[ i ].weight[ 0 ] ? weights[ i ].weight[ 0 ] : 0,
  837. weights[ i ].weight[ 1 ] ? weights[ i ].weight[ 1 ] : 0,
  838. weights[ i ].weight[ 2 ] ? weights[ i ].weight[ 2 ] : 0,
  839. weights[ i ].weight[ 3 ] ? weights[ i ].weight[ 3 ] : 0 );
  840. this.skinIndices.push( indicies );
  841. this.skinWeights.push( weight );
  842. }
  843. //console.log( this );
  844. return this;
  845. };
  846. function Bones() {
  847. // returns bones hierarchy tree.
  848. // [
  849. // {
  850. // "parent": id,
  851. // "name": name,
  852. // "pos": pos,
  853. // "rotq": quat
  854. // },
  855. // ...
  856. // {},
  857. // ...
  858. // ]
  859. //
  860. /* sample response
  861. "bones" : [
  862. {"parent":-1, "name":"Fbx01", "pos":[-0.002, 98.739, 1.6e-05], "rotq":[0, 0, 0, 1]},
  863. {"parent":0, "name":"Fbx01_Pelvis", "pos":[0.00015963, 0, 7.33107e-08], "rotq":[0, 0, 0, 1]},
  864. {"parent":1, "name":"Fbx01_Spine", "pos":[6.577e-06, 10.216, 0.0106811], "rotq":[0, 0, 0, 1]},
  865. {"parent":2, "name":"Fbx01_R_Thigh", "pos":[14.6537, -10.216, -0.00918758], "rotq":[0, 0, 0, 1]},
  866. {"parent":3, "name":"Fbx01_R_Calf", "pos":[-3.70047, -42.9681, -7.78158], "rotq":[0, 0, 0, 1]},
  867. {"parent":4, "name":"Fbx01_R_Foot", "pos":[-2.0696, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]},
  868. {"parent":5, "name":"Fbx01_R_Toe0", "pos":[-0.0234785, -9.46233, -15.3187], "rotq":[0, 0, 0, 1]},
  869. {"parent":2, "name":"Fbx01_L_Thigh", "pos":[-14.6537, -10.216, -0.00918314], "rotq":[0, 0, 0, 1]},
  870. {"parent":7, "name":"Fbx01_L_Calf", "pos":[3.70037, -42.968, -7.78155], "rotq":[0, 0, 0, 1]},
  871. {"parent":8, "name":"Fbx01_L_Foot", "pos":[2.06954, -46.0488, 9.42052], "rotq":[0, 0, 0, 1]},
  872. {"parent":9, "name":"Fbx01_L_Toe0", "pos":[0.0234566, -9.46235, -15.3187], "rotq":[0, 0, 0, 1]},
  873. {"parent":2, "name":"Fbx01_Spine1", "pos":[-2.97523e-05, 11.5892, -9.81027e-05], "rotq":[0, 0, 0, 1]},
  874. {"parent":11, "name":"Fbx01_Spine2", "pos":[-2.91292e-05, 11.4685, 8.27126e-05], "rotq":[0, 0, 0, 1]},
  875. {"parent":12, "name":"Fbx01_Spine3", "pos":[-4.48857e-05, 11.5783, 8.35108e-05], "rotq":[0, 0, 0, 1]},
  876. {"parent":13, "name":"Fbx01_Neck", "pos":[1.22987e-05, 11.5582, -0.0044775], "rotq":[0, 0, 0, 1]},
  877. {"parent":14, "name":"Fbx01_Head", "pos":[-3.50709e-05, 6.62915, -0.00523254], "rotq":[0, 0, 0, 1]},
  878. {"parent":15, "name":"Fbx01_R_Eye", "pos":[3.31681, 12.739, -10.5267], "rotq":[0, 0, 0, 1]},
  879. {"parent":15, "name":"Fbx01_L_Eye", "pos":[-3.32038, 12.7391, -10.5267], "rotq":[0, 0, 0, 1]},
  880. {"parent":15, "name":"Jaw", "pos":[-0.0017738, 7.43481, -4.08114], "rotq":[0, 0, 0, 1]},
  881. {"parent":14, "name":"Fbx01_R_Clavicle", "pos":[3.10919, 2.46577, -0.0115284], "rotq":[0, 0, 0, 1]},
  882. {"parent":19, "name":"Fbx01_R_UpperArm", "pos":[16.014, 4.57764e-05, 3.10405], "rotq":[0, 0, 0, 1]},
  883. {"parent":20, "name":"Fbx01_R_Forearm", "pos":[22.7068, -1.66322, -2.13803], "rotq":[0, 0, 0, 1]},
  884. {"parent":21, "name":"Fbx01_R_Hand", "pos":[25.5881, -0.80249, -6.37307], "rotq":[0, 0, 0, 1]},
  885. ...
  886. {"parent":27, "name":"Fbx01_R_Finger32", "pos":[2.15572, -0.548737, -0.539604], "rotq":[0, 0, 0, 1]},
  887. {"parent":22, "name":"Fbx01_R_Finger2", "pos":[9.79318, 0.132553, -2.97845], "rotq":[0, 0, 0, 1]},
  888. {"parent":29, "name":"Fbx01_R_Finger21", "pos":[2.74037, 0.0483093, -0.650531], "rotq":[0, 0, 0, 1]},
  889. {"parent":55, "name":"Fbx01_L_Finger02", "pos":[-1.65308, -1.43208, -1.82885], "rotq":[0, 0, 0, 1]}
  890. ]
  891. */
  892. this.hierarchy = [];
  893. }
  894. Bones.prototype.parseHierarchy = function ( node ) {
  895. var objects = node.Objects;
  896. var models = objects.subNodes.Model;
  897. var bones = [];
  898. for ( var id in models ) {
  899. if ( models[ id ].attrType === undefined ) {
  900. continue;
  901. }
  902. bones.push( models[ id ] );
  903. }
  904. this.hierarchy = [];
  905. for ( var i = 0; i < bones.length; ++ i ) {
  906. var bone = bones[ i ];
  907. var p = node.searchConnectionParent( bone.id )[ 0 ];
  908. var t = [ 0.0, 0.0, 0.0 ];
  909. var r = [ 0.0, 0.0, 0.0, 1.0 ];
  910. var s = [ 1.0, 1.0, 1.0 ];
  911. if ( 'Lcl_Translation' in bone.properties ) {
  912. t = parseArrayToFloat( bone.properties.Lcl_Translation.value );
  913. }
  914. if ( 'Lcl_Rotation' in bone.properties ) {
  915. r = parseArrayToRadians( bone.properties.Lcl_Rotation.value );
  916. var q = new THREE.Quaternion();
  917. q.setFromEuler( new THREE.Euler( r[ 0 ], r[ 1 ], r[ 2 ], 'ZYX' ) );
  918. r = [ q.x, q.y, q.z, q.w ];
  919. }
  920. if ( 'Lcl_Scaling' in bone.properties ) {
  921. s = parseArrayToFloat( bone.properties.Lcl_Scaling.value );
  922. }
  923. // replace unsafe character
  924. var name = bone.attrName;
  925. name = name.replace( /:/, '' );
  926. name = name.replace( /_/, '' );
  927. name = name.replace( /-/, '' );
  928. this.hierarchy.push( { "parent": p, "name": name, "pos": t, "rotq": r, "scl": s, "internalId": bone.id } );
  929. }
  930. this.reindexParentId();
  931. this.restoreBindPose( node );
  932. return this;
  933. };
  934. Bones.prototype.reindexParentId = function () {
  935. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  936. for ( var ii = 0; ii < this.hierarchy.length; ++ ii ) {
  937. if ( this.hierarchy[ h ].parent == this.hierarchy[ ii ].internalId ) {
  938. this.hierarchy[ h ].parent = ii;
  939. break;
  940. }
  941. }
  942. }
  943. };
  944. Bones.prototype.restoreBindPose = function ( node ) {
  945. var bindPoseNode = node.Objects.subNodes.Pose;
  946. if ( bindPoseNode === undefined ) {
  947. return;
  948. }
  949. for ( var key in bindPoseNode ) {
  950. if ( bindPoseNode[ key ].attrType === 'BindPose' ) {
  951. bindPoseNode = bindPoseNode[ key ];
  952. break;
  953. }
  954. }
  955. var poseNode = bindPoseNode.subNodes.PoseNode;
  956. var localMatrices = {}; // store local matrices, modified later( initialy world space )
  957. var worldMatrices = {}; // store world matrices
  958. for ( var i = 0; i < poseNode.length; ++ i ) {
  959. var rawMatLcl = parseArrayToMatrix( poseNode[ i ].subNodes.Matrix.properties.a );
  960. var rawMatWrd = parseArrayToMatrix( poseNode[ i ].subNodes.Matrix.properties.a );
  961. localMatrices[ poseNode[ i ].id ] = rawMatLcl;
  962. worldMatrices[ poseNode[ i ].id ] = rawMatWrd;
  963. }
  964. for ( var h = 0; h < this.hierarchy.length; ++ h ) {
  965. var bone = this.hierarchy[ h ];
  966. var inId = bone.internalId;
  967. if ( worldMatrices[ inId ] === undefined ) {
  968. // has no bind pose node, possibly be mesh
  969. // console.log( bone );
  970. continue;
  971. }
  972. var t = new THREE.Vector3( 0, 0, 0 );
  973. var r = new THREE.Quaternion();
  974. var s = new THREE.Vector3( 1, 1, 1 );
  975. var parentId;
  976. var parentNodes = node.searchConnectionParent( inId );
  977. for ( var pn = 0; pn < parentNodes.length; ++ pn ) {
  978. if ( this.isBoneNode( parentNodes[ pn ] ) ) {
  979. parentId = parentNodes[ pn ];
  980. break;
  981. }
  982. }
  983. if ( parentId !== undefined && localMatrices[ parentId ] !== undefined ) {
  984. // convert world space matrix into local space
  985. var inv = new THREE.Matrix4();
  986. inv.getInverse( worldMatrices[ parentId ] );
  987. inv.multiply( localMatrices[ inId ] );
  988. localMatrices[ inId ] = inv;
  989. } else {
  990. //console.log( bone );
  991. }
  992. localMatrices[ inId ].decompose( t, r, s );
  993. bone.pos = [ t.x, t.y, t.z ];
  994. bone.rotq = [ r.x, r.y, r.z, r.w ];
  995. bone.scl = [ s.x, s.y, s.z ];
  996. }
  997. };
  998. Bones.prototype.searchRealId = function ( internalId ) {
  999. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  1000. if ( internalId == this.hierarchy[ h ].internalId ) {
  1001. return h;
  1002. }
  1003. }
  1004. // console.warn( 'FBXLoader: notfound internalId in bones: ' + internalId);
  1005. return - 1;
  1006. };
  1007. Bones.prototype.getByInternalId = function ( internalId ) {
  1008. for ( var h = 0; h < this.hierarchy.length; h ++ ) {
  1009. if ( internalId == this.hierarchy[ h ].internalId ) {
  1010. return this.hierarchy[ h ];
  1011. }
  1012. }
  1013. return null;
  1014. };
  1015. Bones.prototype.isBoneNode = function ( id ) {
  1016. for ( var i = 0; i < this.hierarchy.length; ++ i ) {
  1017. if ( id === this.hierarchy[ i ].internalId ) {
  1018. return true;
  1019. }
  1020. }
  1021. return false;
  1022. };
  1023. Bones.prototype.getBoneIdfromInternalId = function ( node, id ) {
  1024. if ( node.__cache_get_boneid_from_internalid === undefined ) {
  1025. node.__cache_get_boneid_from_internalid = [];
  1026. }
  1027. if ( node.__cache_get_boneid_from_internalid[ id ] !== undefined ) {
  1028. return node.__cache_get_boneid_from_internalid[ id ];
  1029. }
  1030. for ( var i = 0; i < this.hierarchy.length; ++ i ) {
  1031. if ( this.hierarchy[ i ].internalId == id ) {
  1032. node.__cache_get_boneid_from_internalid[ id ] = i;
  1033. return i;
  1034. }
  1035. }
  1036. // console.warn( 'FBXLoader: bone internalId(' + id + ') not found in bone hierarchy' );
  1037. return - 1;
  1038. };
  1039. function Geometries() {
  1040. this.geometries = {};
  1041. }
  1042. Object.assign( Geometries.prototype, {
  1043. parse: function ( FBXNodes, hierarchy ) {
  1044. if ( ! ( 'Geometry' in FBXNodes.Objects.subNodes ) ) {
  1045. return this;
  1046. }
  1047. for ( var geo in FBXNodes.Objects.subNodes.Geometry ) {
  1048. if ( FBXNodes.Objects.subNodes.Geometry[ geo ].attrType === 'Mesh' ) {
  1049. this.geometries[ geo ] = ( new Geometry() ).parse( FBXNodes.Objects.subNodes.Geometry[ geo ] );
  1050. this.geometries[ geo ].addBones( hierarchy.hierarchy );
  1051. }
  1052. }
  1053. return this;
  1054. }
  1055. } );
  1056. function Geometry() {
  1057. this.node = null;
  1058. this.name = null;
  1059. this.id = null;
  1060. this.vertices = [];
  1061. this.indices = [];
  1062. this.normals = [];
  1063. this.uvs = [];
  1064. this.bones = [];
  1065. }
  1066. Geometry.prototype.parse = function ( geoNode ) {
  1067. this.node = geoNode;
  1068. this.name = geoNode.attrName;
  1069. this.id = geoNode.id;
  1070. this.vertices = this.getVertices();
  1071. if ( this.vertices === undefined ) {
  1072. console.log( 'FBXLoader: Geometry.parse(): pass' + this.node.id );
  1073. return;
  1074. }
  1075. this.indices = this.getPolygonVertexIndices();
  1076. this.uvs = ( new UV() ).parse( this.node, this );
  1077. this.normals = ( new Normal() ).parse( this.node, this );
  1078. this.materialIndices = ( new MaterialIndex() ).parse( this.node );
  1079. if ( this.getPolygonTopologyMax() > 3 ) {
  1080. var indexInfo = this.convertPolyIndicesToTri(
  1081. this.indices,
  1082. this.materialIndices,
  1083. this.getPolygonTopologyArray() );
  1084. this.indices = indexInfo.res;
  1085. this.materialIndices = indexInfo.materialIndices;
  1086. this.polyIndices = indexInfo.polyIndices;
  1087. }
  1088. return this;
  1089. };
  1090. Geometry.prototype.getVertices = function () {
  1091. if ( this.node.__cache_vertices ) {
  1092. return this.node.__cache_vertices;
  1093. }
  1094. if ( this.node.subNodes.Vertices === undefined ) {
  1095. console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have Vertices" );
  1096. this.node.__cache_vertices = undefined;
  1097. return null;
  1098. }
  1099. var rawTextVert = this.node.subNodes.Vertices.properties.a;
  1100. var vertices = rawTextVert.split( ',' ).map( function ( element ) {
  1101. return parseFloat( element );
  1102. } );
  1103. this.node.__cache_vertices = vertices;
  1104. return this.node.__cache_vertices;
  1105. };
  1106. Geometry.prototype.getPolygonVertexIndices = function () {
  1107. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1108. return this.node.__cache_indices;
  1109. }
  1110. if ( this.node.subNodes === undefined ) {
  1111. console.error( 'this.node.subNodes undefined' );
  1112. console.log( this.node );
  1113. return;
  1114. }
  1115. if ( this.node.subNodes.PolygonVertexIndex === undefined ) {
  1116. console.warn( 'this.node: ' + this.node.attrName + "(" + this.node.id + ") does not have PolygonVertexIndex " );
  1117. this.node.__cache_indices = undefined;
  1118. return;
  1119. }
  1120. var rawTextIndices = this.node.subNodes.PolygonVertexIndex.properties.a;
  1121. var indices = rawTextIndices.split( ',' );
  1122. var currentTopo = 1;
  1123. var topologyN = null;
  1124. var topologyArr = [];
  1125. // The indices that make up the polygon are in order and a negative index
  1126. // means that it’s the last index of the polygon. That index needs
  1127. // to be made positive and then you have to subtract 1 from it!
  1128. for ( var i = 0; i < indices.length; ++ i ) {
  1129. var tmpI = parseInt( indices[ i ] );
  1130. // found n
  1131. if ( tmpI < 0 ) {
  1132. if ( currentTopo > topologyN ) {
  1133. topologyN = currentTopo;
  1134. }
  1135. indices[ i ] = tmpI ^ - 1;
  1136. topologyArr.push( currentTopo );
  1137. currentTopo = 1;
  1138. } else {
  1139. indices[ i ] = tmpI;
  1140. currentTopo ++;
  1141. }
  1142. }
  1143. if ( topologyN === null ) {
  1144. console.warn( "FBXLoader: topology N not found: " + this.node.attrName );
  1145. console.warn( this.node );
  1146. topologyN = 3;
  1147. }
  1148. this.node.__cache_poly_topology_max = topologyN;
  1149. this.node.__cache_poly_topology_arr = topologyArr;
  1150. this.node.__cache_indices = indices;
  1151. return this.node.__cache_indices;
  1152. };
  1153. Geometry.prototype.getPolygonTopologyMax = function () {
  1154. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1155. return this.node.__cache_poly_topology_max;
  1156. }
  1157. this.getPolygonVertexIndices( this.node );
  1158. return this.node.__cache_poly_topology_max;
  1159. };
  1160. Geometry.prototype.getPolygonTopologyArray = function () {
  1161. if ( this.node.__cache_indices && this.node.__cache_poly_topology_max ) {
  1162. return this.node.__cache_poly_topology_arr;
  1163. }
  1164. this.getPolygonVertexIndices( this.node );
  1165. return this.node.__cache_poly_topology_arr;
  1166. };
  1167. // a - d
  1168. // | |
  1169. // b - c
  1170. //
  1171. // [( a, b, c, d ) ...........
  1172. // [( a, b, c ), (a, c, d )....
  1173. // Also keep track of original poly index.
  1174. Geometry.prototype.convertPolyIndicesToTri = function ( indices, materialIndices, strides ) {
  1175. var res = [];
  1176. var i = 0;
  1177. var currentPolyNum = 0;
  1178. var currentStride = 0;
  1179. var polyIndices = [];
  1180. while ( i < indices.length ) {
  1181. currentStride = strides[ currentPolyNum ];
  1182. // CAUTIN: NG over 6gon
  1183. for ( var j = 0; j <= ( currentStride - 3 ); j ++ ) {
  1184. res.push( indices[ i ] );
  1185. res.push( indices[ i + ( currentStride - 2 - j ) ] );
  1186. res.push( indices[ i + ( currentStride - 1 - j ) ] );
  1187. polyIndices.push( currentPolyNum );
  1188. }
  1189. currentPolyNum ++;
  1190. i += currentStride;
  1191. }
  1192. var newMaterialIndices = [ materialIndices[ 0 ] ];
  1193. if ( materialIndices.length > 1 ) {
  1194. for ( var i = 0; i < polyIndices.length; ++ i ) {
  1195. newMaterialIndices[ i ] = materialIndices[ polyIndices[ i ] ];
  1196. }
  1197. }
  1198. return {
  1199. res: res,
  1200. materialIndices: newMaterialIndices,
  1201. polyIndices: polyIndices };
  1202. };
  1203. Geometry.prototype.addBones = function ( bones ) {
  1204. this.bones = bones;
  1205. };
  1206. function UV() {
  1207. this.uv = null;
  1208. this.map = null;
  1209. this.ref = null;
  1210. this.node = null;
  1211. this.index = null;
  1212. }
  1213. UV.prototype.getUV = function ( node ) {
  1214. if ( this.node && this.uv && this.map && this.ref ) {
  1215. return this.uv;
  1216. } else {
  1217. return this._parseText( node );
  1218. }
  1219. };
  1220. UV.prototype.getMap = function ( node ) {
  1221. if ( this.node && this.uv && this.map && this.ref ) {
  1222. return this.map;
  1223. } else {
  1224. this._parseText( node );
  1225. return this.map;
  1226. }
  1227. };
  1228. UV.prototype.getRef = function ( node ) {
  1229. if ( this.node && this.uv && this.map && this.ref ) {
  1230. return this.ref;
  1231. } else {
  1232. this._parseText( node );
  1233. return this.ref;
  1234. }
  1235. };
  1236. UV.prototype.getIndex = function ( node ) {
  1237. if ( this.node && this.uv && this.map && this.ref ) {
  1238. return this.index;
  1239. } else {
  1240. this._parseText( node );
  1241. return this.index;
  1242. }
  1243. };
  1244. UV.prototype.getNode = function ( topnode ) {
  1245. if ( this.node !== null ) {
  1246. return this.node;
  1247. }
  1248. this.node = topnode.subNodes.LayerElementUV;
  1249. return this.node;
  1250. };
  1251. UV.prototype._parseText = function ( node ) {
  1252. var uvNode = this.getNode( node )[ 0 ];
  1253. if ( uvNode === undefined ) {
  1254. // console.log( node.attrName + "(" + node.id + ")" + " has no LayerElementUV." );
  1255. return [];
  1256. }
  1257. var count = 0;
  1258. for ( var n in uvNode ) {
  1259. if ( n.match( /^\d+$/ ) ) {
  1260. count ++;
  1261. }
  1262. }
  1263. if ( count > 0 ) {
  1264. console.warn( 'multi uv not supported' );
  1265. uvNode = uvNode[ n ];
  1266. }
  1267. var uvIndex = uvNode.subNodes.UVIndex.properties.a;
  1268. var uvs = uvNode.subNodes.UV.properties.a;
  1269. var uvMap = uvNode.properties.MappingInformationType;
  1270. var uvRef = uvNode.properties.ReferenceInformationType;
  1271. this.uv = parseArrayToFloat( uvs );
  1272. this.index = parseArrayToInt( uvIndex );
  1273. this.map = uvMap; // TODO: normalize notation shaking... FOR BLENDER
  1274. this.ref = uvRef;
  1275. return this.uv;
  1276. };
  1277. UV.prototype.parse = function ( node, geo ) {
  1278. if ( ! ( 'LayerElementUV' in node.subNodes ) ) {
  1279. return;
  1280. }
  1281. this.uvNode = this.getNode( node );
  1282. this.uv = this.getUV( node );
  1283. var mappingType = this.getMap( node );
  1284. var refType = this.getRef( node );
  1285. var indices = this.getIndex( node );
  1286. var strides = geo.getPolygonTopologyArray();
  1287. // it means that there is a normal for every vertex of every polygon of the model.
  1288. // For example, if the models has 8 vertices that make up four quads, then there
  1289. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1290. // that generally a game engine needs the vertices to have only one normal defined.
  1291. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1292. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1293. //if ( mappingType == "ByPolygonVertex" ){
  1294. switch ( mappingType ) {
  1295. case "ByPolygonVertex":
  1296. switch ( refType ) {
  1297. // Direct
  1298. // The this.uv are in order.
  1299. case "Direct":
  1300. this.uv = this.parseUV_ByPolygonVertex_Direct( this.uv, indices, strides, 2 );
  1301. break;
  1302. // IndexToDirect
  1303. // The order of the this.uv is given by the uvsIndex property.
  1304. case "IndexToDirect":
  1305. this.uv = this.parseUV_ByPolygonVertex_IndexToDirect( this.uv, indices );
  1306. break;
  1307. }
  1308. // convert from by polygon(vert) data into by verts data
  1309. this.uv = mapByPolygonVertexToByVertex( this.uv, geo.getPolygonVertexIndices( node ), 2 );
  1310. break;
  1311. case "ByPolygon":
  1312. switch ( refType ) {
  1313. // Direct
  1314. // The this.uv are in order.
  1315. case "Direct":
  1316. this.uv = this.parseUV_ByPolygon_Direct();
  1317. break;
  1318. // IndexToDirect
  1319. // The order of the this.uv is given by the uvsIndex property.
  1320. case "IndexToDirect":
  1321. this.uv = this.parseUV_ByPolygon_IndexToDirect();
  1322. break;
  1323. }
  1324. break;
  1325. }
  1326. return this.uv;
  1327. };
  1328. UV.prototype.parseUV_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) {
  1329. return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize );
  1330. };
  1331. UV.prototype.parseUV_ByPolygonVertex_IndexToDirect = function ( node, indices ) {
  1332. return parse_Data_ByPolygonVertex_IndexToDirect( node, indices, 2 );
  1333. };
  1334. UV.prototype.parseUV_ByPolygon_Direct = function ( node ) {
  1335. console.warn( "not implemented" );
  1336. return node;
  1337. };
  1338. UV.prototype.parseUV_ByPolygon_IndexToDirect = function ( node ) {
  1339. console.warn( "not implemented" );
  1340. return node;
  1341. };
  1342. UV.prototype.parseUV_ByVertex_Direct = function ( node ) {
  1343. console.warn( "not implemented" );
  1344. return node;
  1345. };
  1346. function Normal() {
  1347. this.normal = null;
  1348. this.map = null;
  1349. this.ref = null;
  1350. this.node = null;
  1351. this.index = null;
  1352. }
  1353. Normal.prototype.getNormal = function ( node ) {
  1354. if ( this.node && this.normal && this.map && this.ref ) {
  1355. return this.normal;
  1356. } else {
  1357. this._parseText( node );
  1358. return this.normal;
  1359. }
  1360. };
  1361. // mappingType: possible variant
  1362. // ByPolygon
  1363. // ByPolygonVertex
  1364. // ByVertex (or also ByVertice, as the Blender exporter writes)
  1365. // ByEdge
  1366. // AllSame
  1367. // var mappingType = node.properties.MappingInformationType;
  1368. Normal.prototype.getMap = function ( node ) {
  1369. if ( this.node && this.normal && this.map && this.ref ) {
  1370. return this.map;
  1371. } else {
  1372. this._parseText( node );
  1373. return this.map;
  1374. }
  1375. };
  1376. // refType: possible variants
  1377. // Direct
  1378. // IndexToDirect (or Index for older versions)
  1379. // var refType = node.properties.ReferenceInformationType;
  1380. Normal.prototype.getRef = function ( node ) {
  1381. if ( this.node && this.normal && this.map && this.ref ) {
  1382. return this.ref;
  1383. } else {
  1384. this._parseText( node );
  1385. return this.ref;
  1386. }
  1387. };
  1388. Normal.prototype.getNode = function ( node ) {
  1389. if ( this.node ) {
  1390. return this.node;
  1391. }
  1392. this.node = node.subNodes.LayerElementNormal;
  1393. return this.node;
  1394. };
  1395. Normal.prototype._parseText = function ( node ) {
  1396. var normalNode = this.getNode( node )[ 0 ];
  1397. if ( normalNode === undefined ) {
  1398. console.warn( 'node: ' + node.attrName + "(" + node.id + ") does not have LayerElementNormal" );
  1399. return;
  1400. }
  1401. var mappingType = normalNode.properties.MappingInformationType;
  1402. var refType = normalNode.properties.ReferenceInformationType;
  1403. var rawTextNormals = normalNode.subNodes.Normals.properties.a;
  1404. this.normal = parseArrayToFloat( rawTextNormals );
  1405. // TODO: normalize notation shaking, vertex / vertice... blender...
  1406. this.map = mappingType;
  1407. this.ref = refType;
  1408. };
  1409. Normal.prototype.parse = function ( topnode, geo ) {
  1410. var normals = this.getNormal( topnode );
  1411. //var normalNode = this.getNode( topnode );
  1412. var mappingType = this.getMap( topnode );
  1413. var refType = this.getRef( topnode );
  1414. var indices = geo.getPolygonVertexIndices( topnode );
  1415. var strides = geo.getPolygonTopologyArray( topnode );
  1416. // it means that there is a normal for every vertex of every polygon of the model.
  1417. // For example, if the models has 8 vertices that make up four quads, then there
  1418. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1419. // that generally a game engine needs the vertices to have only one normal defined.
  1420. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1421. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1422. //if ( mappingType == "ByPolygonVertex" ){
  1423. switch ( mappingType ) {
  1424. case "ByPolygonVertex":
  1425. switch ( refType ) {
  1426. // Direct
  1427. // The normals are in order.
  1428. case "Direct":
  1429. normals = this.parseNormal_ByPolygonVertex_Direct( normals, indices, strides, 3 );
  1430. break;
  1431. // IndexToDirect
  1432. // The order of the normals is given by the NormalsIndex property.
  1433. case "IndexToDirect":
  1434. normals = this.parseNormal_ByPolygonVertex_IndexToDirect();
  1435. break;
  1436. }
  1437. break;
  1438. case "ByPolygon":
  1439. switch ( refType ) {
  1440. // Direct
  1441. // The normals are in order.
  1442. case "Direct":
  1443. normals = this.parseNormal_ByPolygon_Direct();
  1444. break;
  1445. // IndexToDirect
  1446. // The order of the normals is given by the NormalsIndex property.
  1447. case "IndexToDirect":
  1448. normals = this.parseNormal_ByPolygon_IndexToDirect();
  1449. break;
  1450. }
  1451. break;
  1452. }
  1453. return normals;
  1454. };
  1455. Normal.prototype.parseNormal_ByPolygonVertex_Direct = function ( node, indices, strides, itemSize ) {
  1456. return parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize );
  1457. };
  1458. Normal.prototype.parseNormal_ByPolygonVertex_IndexToDirect = function ( node ) {
  1459. console.warn( "not implemented" );
  1460. return node;
  1461. };
  1462. Normal.prototype.parseNormal_ByPolygon_Direct = function ( node ) {
  1463. console.warn( "not implemented" );
  1464. return node;
  1465. };
  1466. Normal.prototype.parseNormal_ByPolygon_IndexToDirect = function ( node ) {
  1467. console.warn( "not implemented" );
  1468. return node;
  1469. };
  1470. Normal.prototype.parseNormal_ByVertex_Direct = function ( node ) {
  1471. console.warn( "not implemented" );
  1472. return node;
  1473. };
  1474. function MaterialIndex() {
  1475. this.indexBuffer = [];
  1476. }
  1477. Object.assign( MaterialIndex.prototype, {
  1478. parse: function ( node ) {
  1479. if ( ! ( 'LayerElementMaterial' in node.subNodes ) ) {
  1480. return;
  1481. }
  1482. var indexNode = node.subNodes.LayerElementMaterial[ 0 ];
  1483. var mappingType = indexNode.properties.MappingInformationType;
  1484. var refType = indexNode.properties.ReferenceInformationType;
  1485. var indices = parseArrayToInt( indexNode.subNodes.Materials.properties.a );
  1486. // it means that there is a normal for every vertex of every polygon of the model.
  1487. // For example, if the models has 8 vertices that make up four quads, then there
  1488. // will be 16 normals (one normal * 4 polygons * 4 vertices of the polygon). Note
  1489. // that generally a game engine needs the vertices to have only one normal defined.
  1490. // So, if you find a vertex has more tha one normal, you can either ignore the normals
  1491. // you find after the first, or calculate the mean from all of them (normal smoothing).
  1492. //if ( mappingType == "ByPolygonVertex" ){
  1493. switch ( mappingType ) {
  1494. case "ByPolygon":
  1495. switch ( refType ) {
  1496. // Direct
  1497. // The material indices are in order.
  1498. case "IndexToDirect":
  1499. this.indexBuffer = this.parse_ByPolygon_IndexToDirect( indices );
  1500. break;
  1501. default:
  1502. this.indexBuffer = [ 0 ];
  1503. break;
  1504. }
  1505. break;
  1506. default:
  1507. this.indexBuffer = [ 0 ];
  1508. break;
  1509. }
  1510. return this.indexBuffer;
  1511. },
  1512. parse_ByPolygon_IndexToDirect: function ( indices ) {
  1513. return indices;
  1514. },
  1515. } );
  1516. function AnimationCurve() {
  1517. this.version = null;
  1518. this.id = null;
  1519. this.internalId = null;
  1520. this.times = null;
  1521. this.values = null;
  1522. this.attrFlag = null; // tangeant
  1523. this.attrData = null; // slope, weight
  1524. }
  1525. AnimationCurve.prototype.fromNode = function ( curveNode ) {
  1526. this.id = curveNode.id;
  1527. this.internalId = curveNode.id;
  1528. this.times = curveNode.subNodes.KeyTime.properties.a;
  1529. this.values = curveNode.subNodes.KeyValueFloat.properties.a;
  1530. this.attrFlag = curveNode.subNodes.KeyAttrFlags.properties.a;
  1531. this.attrData = curveNode.subNodes.KeyAttrDataFloat.properties.a;
  1532. this.times = parseArrayToFloat( this.times );
  1533. this.values = parseArrayToFloat( this.values );
  1534. this.attrData = parseArrayToFloat( this.attrData );
  1535. this.attrFlag = parseArrayToInt( this.attrFlag );
  1536. this.times = this.times.map( function ( element ) {
  1537. return FBXTimeToSeconds( element );
  1538. } );
  1539. return this;
  1540. };
  1541. AnimationCurve.prototype.getLength = function () {
  1542. return this.times[ this.times.length - 1 ];
  1543. };
  1544. function AnimationNode() {
  1545. this.id = null;
  1546. this.attr = null; // S, R, T
  1547. this.attrX = false;
  1548. this.attrY = false;
  1549. this.attrZ = false;
  1550. this.internalId = null;
  1551. this.containerInternalId = null; // bone, null etc Id
  1552. this.containerBoneId = null; // bone, null etc Id
  1553. this.curveIdx = null; // AnimationCurve's indices
  1554. this.curves = {}; // AnimationCurve refs
  1555. }
  1556. AnimationNode.prototype.fromNode = function ( allNodes, node, bones ) {
  1557. this.id = node.id;
  1558. this.attr = node.attrName;
  1559. this.internalId = node.id;
  1560. if ( this.attr.match( /S|R|T/ ) ) {
  1561. for ( var attrKey in node.properties ) {
  1562. if ( attrKey.match( /X/ ) ) {
  1563. this.attrX = true;
  1564. }
  1565. if ( attrKey.match( /Y/ ) ) {
  1566. this.attrY = true;
  1567. }
  1568. if ( attrKey.match( /Z/ ) ) {
  1569. this.attrZ = true;
  1570. }
  1571. }
  1572. } else {
  1573. // may be deform percent nodes
  1574. return null;
  1575. }
  1576. this.containerIndices = allNodes.searchConnectionParent( this.id );
  1577. this.curveIdx = allNodes.searchConnectionChildren( this.id );
  1578. for ( var i = this.containerIndices.length - 1; i >= 0; -- i ) {
  1579. var boneId = bones.searchRealId( this.containerIndices[ i ] );
  1580. if ( boneId >= 0 ) {
  1581. this.containerBoneId = boneId;
  1582. this.containerId = this.containerIndices[ i ];
  1583. }
  1584. if ( boneId >= 0 ) {
  1585. break;
  1586. }
  1587. }
  1588. // this.containerBoneId = bones.searchRealId( this.containerIndices );
  1589. return this;
  1590. };
  1591. AnimationNode.prototype.setCurve = function ( curve ) {
  1592. this.curves.push( curve );
  1593. };
  1594. function Animation() {
  1595. this.curves = {};
  1596. this.length = 0.0;
  1597. this.fps = 30.0;
  1598. this.frames = 0.0;
  1599. }
  1600. Animation.prototype.parse = function ( node, bones ) {
  1601. var rawNodes = node.Objects.subNodes.AnimationCurveNode;
  1602. var rawCurves = node.Objects.subNodes.AnimationCurve;
  1603. var rawLayers = node.Objects.subNodes.AnimationLayer;
  1604. var rawStacks = node.Objects.subNodes.AnimationStack;
  1605. // first: expand AnimationCurveNode into curve nodes
  1606. var curveNodes = [];
  1607. for ( var key in rawNodes ) {
  1608. if ( key.match( /\d+/ ) ) {
  1609. var a = ( new AnimationNode() ).fromNode( node, rawNodes[ key ], bones );
  1610. curveNodes.push( a );
  1611. }
  1612. }
  1613. // second: gen dict, mapped by internalId
  1614. var tmp = {};
  1615. for ( var i = 0; i < curveNodes.length; ++ i ) {
  1616. if ( curveNodes[ i ] === null ) {
  1617. continue;
  1618. }
  1619. tmp[ curveNodes[ i ].id ] = curveNodes[ i ];
  1620. }
  1621. // third: insert curves into the dict
  1622. var ac = [];
  1623. for ( key in rawCurves ) {
  1624. if ( key.match( /\d+/ ) ) {
  1625. var c = ( new AnimationCurve() ).fromNode( rawCurves[ key ] );
  1626. ac.push( c );
  1627. var parentId = node.searchConnectionParent( c.id )[ 0 ];
  1628. var axis = node.searchConnectionType( c.id, parentId );
  1629. if ( axis.match( /X/ ) ) {
  1630. axis = 'x';
  1631. } else if ( axis.match( /Y/ ) ) {
  1632. axis = 'y';
  1633. } else if ( axis.match( /Z/ ) ) {
  1634. axis = 'z';
  1635. } else {
  1636. continue;
  1637. }
  1638. tmp[ parentId ].curves[ axis ] = c;
  1639. }
  1640. }
  1641. // forth:
  1642. for ( var t in tmp ) {
  1643. var id = tmp[ t ].containerBoneId;
  1644. if ( this.curves[ id ] === undefined ) {
  1645. this.curves[ id ] = {
  1646. T: null,
  1647. R: null,
  1648. S: null
  1649. };
  1650. }
  1651. this.curves[ id ][ tmp[ t ].attr ] = tmp[ t ];
  1652. }
  1653. //Layers
  1654. this.layers = {};
  1655. for ( var key in rawLayers ) {
  1656. var layer = [];
  1657. var children = node.searchConnectionChildren( key );
  1658. for ( var i = 0; i < children.length; ++ i ) {
  1659. //Skip lockInfluenceWeights
  1660. if ( tmp[ children[ i ] ] ) {
  1661. if ( layer[ tmp[ children[ i ] ].containerBoneId ] === undefined ) {
  1662. layer[ tmp[ children[ i ] ].containerBoneId ] = {
  1663. T: null,
  1664. R: null,
  1665. S: null
  1666. };
  1667. }
  1668. layer[ tmp[ children[ i ] ].containerBoneId ][ tmp[ children[ i ] ].attr ] = tmp[ children[ i ] ];
  1669. }
  1670. }
  1671. this.layers[ key ] = layer;
  1672. }
  1673. //Takes
  1674. this.stacks = {};
  1675. for ( var key in rawStacks ) {
  1676. var layers = [];
  1677. var children = node.searchConnectionChildren( key );
  1678. var max = 0.0;
  1679. var min = Number.MAX_VALUE;
  1680. for ( var i = 0; i < children.length; ++ i ) {
  1681. if ( children[ i ] in this.layers ) {
  1682. layers.push( this.layers[ children[ i ] ] );
  1683. for ( var j = 0; j < this.layers[ children[ i ] ].length; ++ j ) {
  1684. function getMaxMin( layer ) {
  1685. function _getMaxMin( curves ) {
  1686. if ( curves.x ) {
  1687. max = curves.x.getLength() > max ? curves.x.getLength() : max;
  1688. min = curves.x.times[ 0 ] < min ? curves.x.times[ 0 ] : min;
  1689. }
  1690. if ( curves.y ) {
  1691. max = curves.y.getLength() > max ? curves.y.getLength() : max;
  1692. min = curves.y.times[ 0 ] < min ? curves.y.times[ 0 ] : min;
  1693. }
  1694. if ( curves.z ) {
  1695. max = curves.z.getLength() > max ? curves.z.getLength() : max;
  1696. min = curves.z.times[ 0 ] < min ? curves.z.times[ 0 ] : min;
  1697. }
  1698. }
  1699. if ( layer.R ) {
  1700. _getMaxMin( layer.R.curves );
  1701. }
  1702. if ( layer.S ) {
  1703. _getMaxMin( layer.S.curves );
  1704. }
  1705. if ( layer.T ) {
  1706. _getMaxMin( layer.T.curves );
  1707. }
  1708. }
  1709. var layer = this.layers[ children[ i ] ][ j ];
  1710. if ( layer ) {
  1711. getMaxMin( layer );
  1712. }
  1713. }
  1714. }
  1715. }
  1716. //Do we have an animation clip with an actual length?
  1717. if ( max > min ) {
  1718. this.stacks[ key ] = {
  1719. name: rawStacks[ key ].attrName,
  1720. layers: layers,
  1721. length: max - min,
  1722. frames: ( max - min ) * 30,
  1723. };
  1724. }
  1725. }
  1726. return this;
  1727. };
  1728. function Textures() {
  1729. this.textures = {};
  1730. //this.perGeoMap = {};
  1731. }
  1732. Textures.prototype.add = function ( tex ) {
  1733. debugger;
  1734. if ( this.textures === undefined ) {
  1735. this.textures = [];
  1736. }
  1737. this.textures.push( tex );
  1738. for ( var i = 0; i < tex.parentIds.length; ++ i ) {
  1739. if ( this.perGeoMap[ tex.parentIds[ i ] ] === undefined ) {
  1740. this.perGeoMap[ tex.parentIds[ i ] ] = [];
  1741. }
  1742. this.perGeoMap[ tex.parentIds[ i ] ].push( this.textures[ this.textures.length - 1 ] );
  1743. }
  1744. };
  1745. Textures.prototype.parse = function ( node ) {
  1746. var rawNodes = node.Objects.subNodes.Texture;
  1747. for ( var n in rawNodes ) {
  1748. var tex = ( new Texture() ).parse( rawNodes[ n ], node );
  1749. this.textures[ n ] = tex;
  1750. }
  1751. return this;
  1752. };
  1753. Textures.prototype.getById = function ( id ) {
  1754. return this.perGeoMap[ id ];
  1755. };
  1756. function Texture() {
  1757. this.fileName = "";
  1758. this.name = "";
  1759. this.id = null;
  1760. this.parentIds = [];
  1761. }
  1762. Texture.prototype.parse = function ( node, nodes ) {
  1763. this.id = node.id;
  1764. this.name = node.attrName;
  1765. this.fileName = this.parseFileName( node.properties.FileName );
  1766. this.parentIds = this.searchParents( this.id, nodes );
  1767. return this;
  1768. };
  1769. // TODO: support directory
  1770. Texture.prototype.parseFileName = function ( fname ) {
  1771. if ( fname === undefined ) {
  1772. return "";
  1773. }
  1774. // ignore directory structure, flatten path
  1775. var splitted = fname.split( /[\\\/]/ );
  1776. if ( splitted.length > 0 ) {
  1777. return splitted[ splitted.length - 1 ];
  1778. } else {
  1779. return fname;
  1780. }
  1781. };
  1782. Texture.prototype.searchParents = function ( id, nodes ) {
  1783. var p = nodes.searchConnectionParent( id );
  1784. return p;
  1785. };
  1786. function Materials() {
  1787. this.materials = {};
  1788. this.perGeoMap = {};
  1789. }
  1790. Object.assign( Materials.prototype, {
  1791. parse: function ( node ) {
  1792. var rawNodes = node.Objects.subNodes.Material;
  1793. for ( var n in rawNodes ) {
  1794. var mat = ( new Material() ).parse( rawNodes[ n ], node );
  1795. this.materials[ n ] = mat;
  1796. }
  1797. return this;
  1798. }
  1799. } );
  1800. function Material() {
  1801. this.fileName = "";
  1802. this.name = "";
  1803. this.id = null;
  1804. this.parentIds = [];
  1805. }
  1806. Object.assign( Material.prototype, {
  1807. parse: function ( node, nodes ) {
  1808. this.id = node.id;
  1809. this.name = node.attrName;
  1810. this.type = node.properties.ShadingModel;
  1811. this.parameters = this.parseParameters( node.properties );
  1812. this.parentIds = this.searchParents( this.id, nodes );
  1813. return this;
  1814. },
  1815. parseParameters: function ( properties ) {
  1816. var parameters = {};
  1817. //TODO: Missing parameters:
  1818. // - Ambient
  1819. // - MultiLayer
  1820. // - ShininessExponent (Same vals as Shininess)
  1821. // - Specular (Same vals as SpecularColor)
  1822. // - TransparencyFactor (Maybe same as Opacity?).
  1823. if ( properties.Diffuse ) {
  1824. parameters.color = new THREE.Color().fromArray( [ parseFloat( properties.Diffuse.value.x ), parseFloat( properties.Diffuse.value.y ), parseFloat( properties.Diffuse.value.z ) ] );
  1825. }
  1826. if ( properties.Specular ) {
  1827. parameters.specular = new THREE.Color().fromArray( [ parseFloat( properties.Specular.value.x ), parseFloat( properties.Specular.value.y ), parseFloat( properties.Specular.value.z ) ] );
  1828. }
  1829. if ( properties.Shininess ) {
  1830. parameters.shininess = properties.Shininess.value;
  1831. }
  1832. if ( properties.Emissive ) {
  1833. parameters.emissive = new THREE.Color().fromArray( [ parseFloat( properties.Emissive.value.x ), parseFloat( properties.Emissive.value.y ), parseFloat( properties.Emissive.value.z ) ] );
  1834. }
  1835. if ( properties.EmissiveFactor ) {
  1836. parameters.emissiveIntensity = properties.EmissiveFactor.value;
  1837. }
  1838. if ( properties.Reflectivity ) {
  1839. parameters.reflectivity = properties.Reflectivity.value;
  1840. }
  1841. if ( properties.Opacity ) {
  1842. parameters.opacity = properties.Opacity.value;
  1843. }
  1844. if ( parameters.opacity < 1.0 ) {
  1845. parameters.transparent = true;
  1846. }
  1847. //Assigning textures
  1848. return parameters;
  1849. },
  1850. searchParents: function ( id, nodes ) {
  1851. return nodes.searchConnectionParent( id );
  1852. }
  1853. } );
  1854. /* --------------------------------------------------------------------- */
  1855. /* --------------------------------------------------------------------- */
  1856. /* --------------------------------------------------------------------- */
  1857. /* --------------------------------------------------------------------- */
  1858. // LayerElementUV: 0 {
  1859. // Version: 101
  1860. // Name: "Texture_Projection"
  1861. // MappingInformationType: "ByPolygonVertex"
  1862. // ReferenceInformationType: "IndexToDirect"
  1863. // UV: *1746 {
  1864. // UVIndex: *7068 {
  1865. //
  1866. // The order of the uvs is given by the UVIndex property.
  1867. function parse_Data_ByPolygonVertex_IndexToDirect( node, indices, itemSize ) {
  1868. var res = [];
  1869. for ( var i = 0; i < indices.length; ++ i ) {
  1870. for ( var j = 0; j < itemSize; ++ j ) {
  1871. res.push( node[ ( indices[ i ] * itemSize ) + j ] );
  1872. }
  1873. }
  1874. return res;
  1875. }
  1876. // what want: normal per vertex, order vertice
  1877. // i have: normal per polygon
  1878. // i have: indice per polygon
  1879. function parse_Data_ByPolygonVertex_Direct( node, indices, strides, itemSize ) {
  1880. // *21204 > 3573
  1881. // Geometry: 690680816, "Geometry::", "Mesh" {
  1882. // Vertices: *3573 {
  1883. // PolygonVertexIndex: *7068 {
  1884. var tmp = [];
  1885. var currentIndex = 0;
  1886. // first: sort to per vertex
  1887. for ( var i = 0; i < indices.length; ++ i ) {
  1888. tmp[ indices[ i ] ] = [];
  1889. // TODO: duped entry? blend or something?
  1890. for ( var s = 0; s < itemSize; ++ s ) {
  1891. tmp[ indices[ i ] ][ s ] = node[ currentIndex + s ];
  1892. }
  1893. currentIndex += itemSize;
  1894. }
  1895. // second: expand x,y,z into serial array
  1896. var res = [];
  1897. for ( var jj = 0; jj < tmp.length; ++ jj ) {
  1898. if ( tmp[ jj ] === undefined ) {
  1899. continue;
  1900. }
  1901. for ( var t = 0; t < itemSize; ++ t ) {
  1902. if ( tmp[ jj ][ t ] === undefined ) {
  1903. continue;
  1904. }
  1905. res.push( tmp[ jj ][ t ] );
  1906. }
  1907. }
  1908. return res;
  1909. }
  1910. // convert from by polygon(vert) data into by verts data
  1911. function mapByPolygonVertexToByVertex( data, indices, stride ) {
  1912. var tmp = {};
  1913. var res = [];
  1914. var max = 0;
  1915. for ( var i = 0; i < indices.length; ++ i ) {
  1916. if ( indices[ i ] in tmp ) {
  1917. continue;
  1918. }
  1919. tmp[ indices[ i ] ] = {};
  1920. for ( var j = 0; j < stride; ++ j ) {
  1921. tmp[ indices[ i ] ][ j ] = data[ i * stride + j ];
  1922. }
  1923. max = max < indices[ i ] ? indices[ i ] : max;
  1924. }
  1925. try {
  1926. for ( i = 0; i <= max; i ++ ) {
  1927. for ( var s = 0; s < stride; s ++ ) {
  1928. res.push( tmp[ i ][ s ] );
  1929. }
  1930. }
  1931. } catch ( e ) {
  1932. //console.log( max );
  1933. //console.log( tmp );
  1934. //console.log( i );
  1935. //console.log( e );
  1936. }
  1937. return res;
  1938. }
  1939. // AUTODESK uses broken clock. i guess
  1940. function FBXTimeToSeconds( adskTime ) {
  1941. return adskTime / 46186158000;
  1942. }
  1943. function degToRad( degrees ) {
  1944. return degrees * Math.PI / 180;
  1945. }
  1946. function quatFromVec( x, y, z ) {
  1947. var euler = new THREE.Euler( x, y, z, 'ZYX' );
  1948. var quat = new THREE.Quaternion();
  1949. quat.setFromEuler( euler );
  1950. return quat;
  1951. }
  1952. function parseArrayToInt( string ) {
  1953. return string.split( ',' ).map( function ( element ) {
  1954. return parseInt( element );
  1955. } );
  1956. }
  1957. function parseArrayToFloat( string ) {
  1958. return string.split( ',' ).map( function ( element ) {
  1959. return parseFloat( element );
  1960. } );
  1961. }
  1962. function parseArrayToRadians( string ) {
  1963. return string.split( ',' ).map( function ( element ) {
  1964. return degToRad( parseFloat( element ) );
  1965. } );
  1966. }
  1967. function parseArrayToMatrix( string ) {
  1968. var arr = parseArrayToFloat( string );
  1969. return new THREE.Matrix4().fromArray( arr );
  1970. }
  1971. } )();