FBXLoader.js 57 KB

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