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