ColladaLoader.js 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496
  1. /**
  2. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  3. * @author Tony Parisi / http://www.tonyparisi.com/
  4. */
  5. THREE.ColladaLoader = function () {
  6. var COLLADA = null;
  7. var scene = null;
  8. var visualScene;
  9. var kinematicsModel;
  10. var readyCallbackFunc = null;
  11. var sources = {};
  12. var images = {};
  13. var animations = {};
  14. var controllers = {};
  15. var geometries = {};
  16. var materials = {};
  17. var effects = {};
  18. var cameras = {};
  19. var lights = {};
  20. var animData;
  21. var kinematics;
  22. var visualScenes;
  23. var kinematicsModels;
  24. var baseUrl;
  25. var morphs;
  26. var skins;
  27. var flip_uv = true;
  28. var preferredShading = THREE.SmoothShading;
  29. var options = {
  30. // Force Geometry to always be centered at the local origin of the
  31. // containing Mesh.
  32. centerGeometry: false,
  33. // Axis conversion is done for geometries, animations, and controllers.
  34. // If we ever pull cameras or lights out of the COLLADA file, they'll
  35. // need extra work.
  36. convertUpAxis: false,
  37. subdivideFaces: true,
  38. upAxis: 'Y',
  39. // For reflective or refractive materials we'll use this cubemap
  40. defaultEnvMap: null
  41. };
  42. var colladaUnit = 1.0;
  43. var colladaUp = 'Y';
  44. var upConversion = null;
  45. function load ( url, readyCallback, progressCallback, failCallback ) {
  46. var length = 0;
  47. if ( document.implementation && document.implementation.createDocument ) {
  48. var request = new XMLHttpRequest();
  49. request.onreadystatechange = function() {
  50. if ( request.readyState === 4 ) {
  51. if ( request.status === 0 || request.status === 200 ) {
  52. if ( request.response ) {
  53. readyCallbackFunc = readyCallback;
  54. parse( request.response, undefined, url );
  55. } else {
  56. if ( failCallback ) {
  57. failCallback();
  58. } else {
  59. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  60. }
  61. }
  62. }
  63. } else if ( request.readyState === 3 ) {
  64. if ( progressCallback ) {
  65. if ( length === 0 ) {
  66. length = request.getResponseHeader( "Content-Length" );
  67. }
  68. progressCallback( { total: length, loaded: request.responseText.length } );
  69. }
  70. }
  71. };
  72. request.open( "GET", url, true );
  73. request.send( null );
  74. } else {
  75. alert( "Don't know how to parse XML!" );
  76. }
  77. }
  78. function parse( text, callBack, url ) {
  79. COLLADA = new DOMParser().parseFromString( text, 'text/xml' );
  80. callBack = callBack || readyCallbackFunc;
  81. if ( url !== undefined ) {
  82. var parts = url.split( '/' );
  83. parts.pop();
  84. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  85. }
  86. parseAsset();
  87. setUpConversion();
  88. images = parseLib( "library_images image", _Image, "image" );
  89. materials = parseLib( "library_materials material", Material, "material" );
  90. effects = parseLib( "library_effects effect", Effect, "effect" );
  91. geometries = parseLib( "library_geometries geometry", Geometry, "geometry" );
  92. cameras = parseLib( "library_cameras camera", Camera, "camera" );
  93. lights = parseLib( "library_lights light", Light, "light" );
  94. controllers = parseLib( "library_controllers controller", Controller, "controller" );
  95. animations = parseLib( "library_animations animation", Animation, "animation" );
  96. visualScenes = parseLib( "library_visual_scenes visual_scene", VisualScene, "visual_scene" );
  97. kinematicsModels = parseLib( "library_kinematics_models kinematics_model", KinematicsModel, "kinematics_model" );
  98. morphs = [];
  99. skins = [];
  100. visualScene = parseScene();
  101. scene = new THREE.Group();
  102. for ( var i = 0; i < visualScene.nodes.length; i ++ ) {
  103. scene.add( createSceneGraph( visualScene.nodes[ i ] ) );
  104. }
  105. // unit conversion
  106. scene.scale.multiplyScalar( colladaUnit );
  107. createAnimations();
  108. kinematicsModel = parseKinematicsModel();
  109. createKinematics();
  110. var result = {
  111. scene: scene,
  112. morphs: morphs,
  113. skins: skins,
  114. animations: animData,
  115. kinematics: kinematics,
  116. dae: {
  117. images: images,
  118. materials: materials,
  119. cameras: cameras,
  120. lights: lights,
  121. effects: effects,
  122. geometries: geometries,
  123. controllers: controllers,
  124. animations: animations,
  125. visualScenes: visualScenes,
  126. visualScene: visualScene,
  127. scene: visualScene,
  128. kinematicsModels: kinematicsModels,
  129. kinematicsModel: kinematicsModel
  130. }
  131. };
  132. if ( callBack ) {
  133. callBack( result );
  134. }
  135. return result;
  136. }
  137. function setPreferredShading ( shading ) {
  138. preferredShading = shading;
  139. }
  140. function parseAsset () {
  141. var elements = COLLADA.querySelectorAll('asset');
  142. var element = elements[0];
  143. if ( element && element.childNodes ) {
  144. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  145. var child = element.childNodes[ i ];
  146. switch ( child.nodeName ) {
  147. case 'unit':
  148. var meter = child.getAttribute( 'meter' );
  149. if ( meter ) {
  150. colladaUnit = parseFloat( meter );
  151. }
  152. break;
  153. case 'up_axis':
  154. colladaUp = child.textContent.charAt(0);
  155. break;
  156. }
  157. }
  158. }
  159. }
  160. function parseLib ( q, classSpec, prefix ) {
  161. var elements = COLLADA.querySelectorAll(q);
  162. var lib = {};
  163. var i = 0;
  164. var elementsLength = elements.length;
  165. for ( var j = 0; j < elementsLength; j ++ ) {
  166. var element = elements[j];
  167. var daeElement = ( new classSpec() ).parse( element );
  168. if ( !daeElement.id || daeElement.id.length === 0 ) daeElement.id = prefix + ( i ++ );
  169. lib[ daeElement.id ] = daeElement;
  170. }
  171. return lib;
  172. }
  173. function parseScene() {
  174. var sceneElement = COLLADA.querySelectorAll('scene instance_visual_scene')[0];
  175. if ( sceneElement ) {
  176. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  177. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  178. } else {
  179. return null;
  180. }
  181. }
  182. function parseKinematicsModel() {
  183. var kinematicsModelElement = COLLADA.querySelectorAll('instance_kinematics_model')[0];
  184. if ( kinematicsModelElement ) {
  185. var url = kinematicsModelElement.getAttribute( 'url' ).replace(/^#/, '');
  186. return kinematicsModels[ url.length > 0 ? url : 'kinematics_model0' ];
  187. } else {
  188. return null;
  189. }
  190. }
  191. function createAnimations() {
  192. animData = [];
  193. // fill in the keys
  194. recurseHierarchy( scene );
  195. }
  196. function recurseHierarchy( node ) {
  197. var n = visualScene.getChildById( node.colladaId, true ),
  198. newData = null;
  199. if ( n && n.keys ) {
  200. newData = {
  201. fps: 60,
  202. hierarchy: [ {
  203. node: n,
  204. keys: n.keys,
  205. sids: n.sids
  206. } ],
  207. node: node,
  208. name: 'animation_' + node.name,
  209. length: 0
  210. };
  211. animData.push(newData);
  212. for ( var i = 0, il = n.keys.length; i < il; i ++ ) {
  213. newData.length = Math.max( newData.length, n.keys[i].time );
  214. }
  215. } else {
  216. newData = {
  217. hierarchy: [ {
  218. keys: [],
  219. sids: []
  220. } ]
  221. }
  222. }
  223. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  224. var d = recurseHierarchy( node.children[i] );
  225. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  226. newData.hierarchy.push( {
  227. keys: [],
  228. sids: []
  229. } );
  230. }
  231. }
  232. return newData;
  233. }
  234. function calcAnimationBounds () {
  235. var start = 1000000;
  236. var end = -start;
  237. var frames = 0;
  238. var ID;
  239. for ( var id in animations ) {
  240. var animation = animations[ id ];
  241. ID = ID || animation.id;
  242. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  243. var sampler = animation.sampler[ i ];
  244. sampler.create();
  245. start = Math.min( start, sampler.startTime );
  246. end = Math.max( end, sampler.endTime );
  247. frames = Math.max( frames, sampler.input.length );
  248. }
  249. }
  250. return { start:start, end:end, frames:frames,ID:ID };
  251. }
  252. function createMorph ( geometry, ctrl ) {
  253. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  254. if ( !morphCtrl || !morphCtrl.morph ) {
  255. console.log("could not find morph controller!");
  256. return;
  257. }
  258. var morph = morphCtrl.morph;
  259. for ( var i = 0; i < morph.targets.length; i ++ ) {
  260. var target_id = morph.targets[ i ];
  261. var daeGeometry = geometries[ target_id ];
  262. if ( !daeGeometry.mesh ||
  263. !daeGeometry.mesh.primitives ||
  264. !daeGeometry.mesh.primitives.length ) {
  265. continue;
  266. }
  267. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  268. if ( target.vertices.length === geometry.vertices.length ) {
  269. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  270. }
  271. }
  272. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  273. }
  274. function createSkin ( geometry, ctrl, applyBindShape ) {
  275. var skinCtrl = controllers[ ctrl.url ];
  276. if ( !skinCtrl || !skinCtrl.skin ) {
  277. console.log( "could not find skin controller!" );
  278. return;
  279. }
  280. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  281. console.log( "could not find the skeleton for the skin!" );
  282. return;
  283. }
  284. var skin = skinCtrl.skin;
  285. var skeleton = visualScene.getChildById( ctrl.skeleton[ 0 ] );
  286. var hierarchy = [];
  287. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  288. var bones = [];
  289. geometry.skinWeights = [];
  290. geometry.skinIndices = [];
  291. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  292. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  293. /*
  294. geometry.animation = {
  295. name: 'take_001',
  296. fps: 30,
  297. length: 2,
  298. JIT: true,
  299. hierarchy: hierarchy
  300. };
  301. */
  302. if ( applyBindShape ) {
  303. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  304. geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
  305. }
  306. }
  307. }
  308. function setupSkeleton ( node, bones, frame, parent ) {
  309. node.world = node.world || new THREE.Matrix4();
  310. node.localworld = node.localworld || new THREE.Matrix4();
  311. node.world.copy( node.matrix );
  312. node.localworld.copy( node.matrix );
  313. if ( node.channels && node.channels.length ) {
  314. var channel = node.channels[ 0 ];
  315. var m = channel.sampler.output[ frame ];
  316. if ( m instanceof THREE.Matrix4 ) {
  317. node.world.copy( m );
  318. node.localworld.copy(m);
  319. if (frame === 0)
  320. node.matrix.copy(m);
  321. }
  322. }
  323. if ( parent ) {
  324. node.world.multiplyMatrices( parent, node.world );
  325. }
  326. bones.push( node );
  327. for ( var i = 0; i < node.nodes.length; i ++ ) {
  328. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  329. }
  330. }
  331. function setupSkinningMatrices ( bones, skin ) {
  332. // FIXME: this is dumb...
  333. for ( var i = 0; i < bones.length; i ++ ) {
  334. var bone = bones[ i ];
  335. var found = -1;
  336. if ( bone.type != 'JOINT' ) continue;
  337. for ( var j = 0; j < skin.joints.length; j ++ ) {
  338. if ( bone.sid === skin.joints[ j ] ) {
  339. found = j;
  340. break;
  341. }
  342. }
  343. if ( found >= 0 ) {
  344. var inv = skin.invBindMatrices[ found ];
  345. bone.invBindMatrix = inv;
  346. bone.skinningMatrix = new THREE.Matrix4();
  347. bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
  348. bone.animatrix = new THREE.Matrix4();
  349. bone.animatrix.copy(bone.localworld);
  350. bone.weights = [];
  351. for ( var j = 0; j < skin.weights.length; j ++ ) {
  352. for (var k = 0; k < skin.weights[ j ].length; k ++ ) {
  353. var w = skin.weights[ j ][ k ];
  354. if ( w.joint === found ) {
  355. bone.weights.push( w );
  356. }
  357. }
  358. }
  359. } else {
  360. console.warn( "ColladaLoader: Could not find joint '" + bone.sid + "'." );
  361. bone.skinningMatrix = new THREE.Matrix4();
  362. bone.weights = [];
  363. }
  364. }
  365. }
  366. //Walk the Collada tree and flatten the bones into a list, extract the position, quat and scale from the matrix
  367. function flattenSkeleton(skeleton) {
  368. var list = [];
  369. var walk = function(parentid, node, list) {
  370. var bone = {};
  371. bone.name = node.sid;
  372. bone.parent = parentid;
  373. bone.matrix = node.matrix;
  374. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  375. bone.matrix.decompose(data[0], data[1], data[2]);
  376. bone.pos = [ data[0].x,data[0].y,data[0].z ];
  377. bone.scl = [ data[2].x,data[2].y,data[2].z ];
  378. bone.rotq = [ data[1].x,data[1].y,data[1].z,data[1].w ];
  379. list.push(bone);
  380. for (var i in node.nodes) {
  381. walk(node.sid, node.nodes[i], list);
  382. }
  383. };
  384. walk(-1, skeleton, list);
  385. return list;
  386. }
  387. //Move the vertices into the pose that is proper for the start of the animation
  388. function skinToBindPose(geometry,skeleton,skinController) {
  389. var bones = [];
  390. setupSkeleton( skeleton, bones, -1 );
  391. setupSkinningMatrices( bones, skinController.skin );
  392. var v = new THREE.Vector3();
  393. var skinned = [];
  394. for (var i = 0; i < geometry.vertices.length; i ++) {
  395. skinned.push(new THREE.Vector3());
  396. }
  397. for ( i = 0; i < bones.length; i ++ ) {
  398. if ( bones[ i ].type != 'JOINT' ) continue;
  399. for ( var j = 0; j < bones[ i ].weights.length; j ++ ) {
  400. var w = bones[ i ].weights[ j ];
  401. var vidx = w.index;
  402. var weight = w.weight;
  403. var o = geometry.vertices[vidx];
  404. var s = skinned[vidx];
  405. v.x = o.x;
  406. v.y = o.y;
  407. v.z = o.z;
  408. v.applyMatrix4( bones[i].skinningMatrix );
  409. s.x += (v.x * weight);
  410. s.y += (v.y * weight);
  411. s.z += (v.z * weight);
  412. }
  413. }
  414. for (var i = 0; i < geometry.vertices.length; i ++) {
  415. geometry.vertices[i] = skinned[i];
  416. }
  417. }
  418. function applySkin ( geometry, instanceCtrl, frame ) {
  419. var skinController = controllers[ instanceCtrl.url ];
  420. frame = frame !== undefined ? frame : 40;
  421. if ( !skinController || !skinController.skin ) {
  422. console.log( 'ColladaLoader: Could not find skin controller.' );
  423. return;
  424. }
  425. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  426. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  427. return;
  428. }
  429. var animationBounds = calcAnimationBounds();
  430. var skeleton = visualScene.getChildById( instanceCtrl.skeleton[0], true ) || visualScene.getChildBySid( instanceCtrl.skeleton[0], true );
  431. //flatten the skeleton into a list of bones
  432. var bonelist = flattenSkeleton(skeleton);
  433. var joints = skinController.skin.joints;
  434. //sort that list so that the order reflects the order in the joint list
  435. var sortedbones = [];
  436. for (var i = 0; i < joints.length; i ++) {
  437. for (var j = 0; j < bonelist.length; j ++) {
  438. if (bonelist[j].name === joints[i]) {
  439. sortedbones[i] = bonelist[j];
  440. }
  441. }
  442. }
  443. //hook up the parents by index instead of name
  444. for (var i = 0; i < sortedbones.length; i ++) {
  445. for (var j = 0; j < sortedbones.length; j ++) {
  446. if (sortedbones[i].parent === sortedbones[j].name) {
  447. sortedbones[i].parent = j;
  448. }
  449. }
  450. }
  451. var i, j, w, vidx, weight;
  452. var v = new THREE.Vector3(), o, s;
  453. // move vertices to bind shape
  454. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  455. geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
  456. }
  457. var skinIndices = [];
  458. var skinWeights = [];
  459. var weights = skinController.skin.weights;
  460. // hook up the skin weights
  461. // TODO - this might be a good place to choose greatest 4 weights
  462. for ( var i =0; i < weights.length; i ++ ) {
  463. var indicies = new THREE.Vector4(weights[i][0] ? weights[i][0].joint : 0,weights[i][1] ? weights[i][1].joint : 0,weights[i][2] ? weights[i][2].joint : 0,weights[i][3] ? weights[i][3].joint : 0);
  464. var weight = new THREE.Vector4(weights[i][0] ? weights[i][0].weight : 0,weights[i][1] ? weights[i][1].weight : 0,weights[i][2] ? weights[i][2].weight : 0,weights[i][3] ? weights[i][3].weight : 0);
  465. skinIndices.push(indicies);
  466. skinWeights.push(weight);
  467. }
  468. geometry.skinIndices = skinIndices;
  469. geometry.skinWeights = skinWeights;
  470. geometry.bones = sortedbones;
  471. // process animation, or simply pose the rig if no animation
  472. //create an animation for the animated bones
  473. //NOTE: this has no effect when using morphtargets
  474. var animationdata = { "name":animationBounds.ID,"fps":30,"length":animationBounds.frames / 30,"hierarchy":[] };
  475. for (var j = 0; j < sortedbones.length; j ++) {
  476. animationdata.hierarchy.push({ parent:sortedbones[j].parent, name:sortedbones[j].name, keys:[] });
  477. }
  478. console.log( 'ColladaLoader:', animationBounds.ID + ' has ' + sortedbones.length + ' bones.' );
  479. skinToBindPose(geometry, skeleton, skinController);
  480. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  481. var bones = [];
  482. var skinned = [];
  483. // process the frame and setup the rig with a fresh
  484. // transform, possibly from the bone's animation channel(s)
  485. setupSkeleton( skeleton, bones, frame );
  486. setupSkinningMatrices( bones, skinController.skin );
  487. for (var i = 0; i < bones.length; i ++) {
  488. for (var j = 0; j < animationdata.hierarchy.length; j ++) {
  489. if (animationdata.hierarchy[j].name === bones[i].sid) {
  490. var key = {};
  491. key.time = (frame / 30);
  492. key.matrix = bones[i].animatrix;
  493. if (frame === 0)
  494. bones[i].matrix = key.matrix;
  495. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  496. key.matrix.decompose(data[0], data[1], data[2]);
  497. key.pos = [ data[0].x,data[0].y,data[0].z ];
  498. key.scl = [ data[2].x,data[2].y,data[2].z ];
  499. key.rot = data[1];
  500. animationdata.hierarchy[j].keys.push(key);
  501. }
  502. }
  503. }
  504. geometry.animation = animationdata;
  505. }
  506. }
  507. function createKinematics() {
  508. if ( kinematicsModel && kinematicsModel.joints.length === 0 ) {
  509. kinematics = undefined;
  510. return;
  511. }
  512. var jointMap = {};
  513. var _addToMap = function( jointIndex, parentVisualElement ) {
  514. var parentVisualElementId = parentVisualElement.getAttribute( 'id' );
  515. var colladaNode = visualScene.getChildById( parentVisualElementId, true );
  516. var joint = kinematicsModel.joints[ jointIndex ];
  517. scene.traverse(function( node ) {
  518. if ( node.colladaId == parentVisualElementId ) {
  519. jointMap[ jointIndex ] = {
  520. node: node,
  521. transforms: colladaNode.transforms,
  522. joint: joint,
  523. position: joint.zeroPosition
  524. };
  525. }
  526. });
  527. };
  528. kinematics = {
  529. joints: kinematicsModel && kinematicsModel.joints,
  530. getJointValue: function( jointIndex ) {
  531. var jointData = jointMap[ jointIndex ];
  532. if ( jointData ) {
  533. return jointData.position;
  534. } else {
  535. console.log( 'getJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  536. }
  537. },
  538. setJointValue: function( jointIndex, value ) {
  539. var jointData = jointMap[ jointIndex ];
  540. if ( jointData ) {
  541. var joint = jointData.joint;
  542. if ( value > joint.limits.max || value < joint.limits.min ) {
  543. console.log( 'setJointValue: joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ')' );
  544. } else if ( joint.static ) {
  545. console.log( 'setJointValue: joint ' + jointIndex + ' is static' );
  546. } else {
  547. var threejsNode = jointData.node;
  548. var axis = joint.axis;
  549. var transforms = jointData.transforms;
  550. var matrix = new THREE.Matrix4();
  551. for (i = 0; i < transforms.length; i ++ ) {
  552. var transform = transforms[ i ];
  553. // kinda ghetto joint detection
  554. if ( transform.sid && transform.sid.indexOf( 'joint' + jointIndex ) !== -1 ) {
  555. // apply actual joint value here
  556. switch ( joint.type ) {
  557. case 'revolute':
  558. matrix.multiply( m1.makeRotationAxis( axis, THREE.Math.degToRad(value) ) );
  559. break;
  560. case 'prismatic':
  561. matrix.multiply( m1.makeTranslation(axis.x * value, axis.y * value, axis.z * value ) );
  562. break;
  563. default:
  564. console.warn( 'setJointValue: unknown joint type: ' + joint.type );
  565. break;
  566. }
  567. } else {
  568. var m1 = new THREE.Matrix4();
  569. switch ( transform.type ) {
  570. case 'matrix':
  571. matrix.multiply( transform.obj );
  572. break;
  573. case 'translate':
  574. matrix.multiply( m1.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  575. break;
  576. case 'rotate':
  577. matrix.multiply( m1.makeRotationAxis( transform.obj, transform.angle ) );
  578. break;
  579. }
  580. }
  581. }
  582. // apply the matrix to the threejs node
  583. var elementsFloat32Arr = matrix.elements;
  584. var elements = Array.prototype.slice.call( elementsFloat32Arr );
  585. var elementsRowMajor = [
  586. elements[ 0 ],
  587. elements[ 4 ],
  588. elements[ 8 ],
  589. elements[ 12 ],
  590. elements[ 1 ],
  591. elements[ 5 ],
  592. elements[ 9 ],
  593. elements[ 13 ],
  594. elements[ 2 ],
  595. elements[ 6 ],
  596. elements[ 10 ],
  597. elements[ 14 ],
  598. elements[ 3 ],
  599. elements[ 7 ],
  600. elements[ 11 ],
  601. elements[ 15 ]
  602. ];
  603. threejsNode.matrix.set.apply( threejsNode.matrix, elementsRowMajor );
  604. threejsNode.matrix.decompose( threejsNode.position, threejsNode.quaternion, threejsNode.scale );
  605. }
  606. } else {
  607. console.log( 'setJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  608. }
  609. }
  610. };
  611. var element = COLLADA.querySelector('scene instance_kinematics_scene');
  612. if ( element ) {
  613. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  614. var child = element.childNodes[ i ];
  615. if ( child.nodeType != 1 ) continue;
  616. switch ( child.nodeName ) {
  617. case 'bind_joint_axis':
  618. var visualTarget = child.getAttribute( 'target' ).split( '/' ).pop();
  619. var axis = child.querySelector('axis param').textContent;
  620. var jointIndex = parseInt( axis.split( 'joint' ).pop().split( '.' )[0] );
  621. var visualTargetElement = COLLADA.querySelector( '[sid="' + visualTarget + '"]' );
  622. if ( visualTargetElement ) {
  623. var parentVisualElement = visualTargetElement.parentElement;
  624. _addToMap(jointIndex, parentVisualElement);
  625. }
  626. break;
  627. default:
  628. break;
  629. }
  630. }
  631. }
  632. }
  633. function createSceneGraph ( node, parent ) {
  634. var obj = new THREE.Object3D();
  635. var skinned = false;
  636. var skinController;
  637. var morphController;
  638. var i, j;
  639. // FIXME: controllers
  640. for ( i = 0; i < node.controllers.length; i ++ ) {
  641. var controller = controllers[ node.controllers[ i ].url ];
  642. switch ( controller.type ) {
  643. case 'skin':
  644. if ( geometries[ controller.skin.source ] ) {
  645. var inst_geom = new InstanceGeometry();
  646. inst_geom.url = controller.skin.source;
  647. inst_geom.instance_material = node.controllers[ i ].instance_material;
  648. node.geometries.push( inst_geom );
  649. skinned = true;
  650. skinController = node.controllers[ i ];
  651. } else if ( controllers[ controller.skin.source ] ) {
  652. // urgh: controller can be chained
  653. // handle the most basic case...
  654. var second = controllers[ controller.skin.source ];
  655. morphController = second;
  656. // skinController = node.controllers[i];
  657. if ( second.morph && geometries[ second.morph.source ] ) {
  658. var inst_geom = new InstanceGeometry();
  659. inst_geom.url = second.morph.source;
  660. inst_geom.instance_material = node.controllers[ i ].instance_material;
  661. node.geometries.push( inst_geom );
  662. }
  663. }
  664. break;
  665. case 'morph':
  666. if ( geometries[ controller.morph.source ] ) {
  667. var inst_geom = new InstanceGeometry();
  668. inst_geom.url = controller.morph.source;
  669. inst_geom.instance_material = node.controllers[ i ].instance_material;
  670. node.geometries.push( inst_geom );
  671. morphController = node.controllers[ i ];
  672. }
  673. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  674. default:
  675. break;
  676. }
  677. }
  678. // geometries
  679. var double_sided_materials = {};
  680. for ( i = 0; i < node.geometries.length; i ++ ) {
  681. var instance_geometry = node.geometries[i];
  682. var instance_materials = instance_geometry.instance_material;
  683. var geometry = geometries[ instance_geometry.url ];
  684. var used_materials = {};
  685. var used_materials_array = [];
  686. var num_materials = 0;
  687. var first_material;
  688. if ( geometry ) {
  689. if ( !geometry.mesh || !geometry.mesh.primitives )
  690. continue;
  691. if ( obj.name.length === 0 ) {
  692. obj.name = geometry.id;
  693. }
  694. // collect used fx for this geometry-instance
  695. if ( instance_materials ) {
  696. for ( j = 0; j < instance_materials.length; j ++ ) {
  697. var instance_material = instance_materials[ j ];
  698. var mat = materials[ instance_material.target ];
  699. var effect_id = mat.instance_effect.url;
  700. var shader = effects[ effect_id ].shader;
  701. var material3js = shader.material;
  702. if ( geometry.doubleSided ) {
  703. if ( !( instance_material.symbol in double_sided_materials ) ) {
  704. var _copied_material = material3js.clone();
  705. _copied_material.side = THREE.DoubleSide;
  706. double_sided_materials[ instance_material.symbol ] = _copied_material;
  707. }
  708. material3js = double_sided_materials[ instance_material.symbol ];
  709. }
  710. material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
  711. used_materials[ instance_material.symbol ] = num_materials;
  712. used_materials_array.push( material3js );
  713. first_material = material3js;
  714. first_material.name = mat.name === null || mat.name === '' ? mat.id : mat.name;
  715. num_materials ++;
  716. }
  717. }
  718. var mesh;
  719. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
  720. var geom = geometry.mesh.geometry3js;
  721. if ( num_materials > 1 ) {
  722. material = new THREE.MeshFaceMaterial( used_materials_array );
  723. }
  724. if ( skinController !== undefined ) {
  725. applySkin( geom, skinController );
  726. if ( geom.morphTargets.length > 0 ) {
  727. material.morphTargets = true;
  728. material.skinning = false;
  729. } else {
  730. material.morphTargets = false;
  731. material.skinning = true;
  732. }
  733. mesh = new THREE.SkinnedMesh( geom, material, false );
  734. //mesh.skeleton = skinController.skeleton;
  735. //mesh.skinController = controllers[ skinController.url ];
  736. //mesh.skinInstanceController = skinController;
  737. mesh.name = 'skin_' + skins.length;
  738. //mesh.animationHandle.setKey(0);
  739. skins.push( mesh );
  740. } else if ( morphController !== undefined ) {
  741. createMorph( geom, morphController );
  742. material.morphTargets = true;
  743. mesh = new THREE.Mesh( geom, material );
  744. mesh.name = 'morph_' + morphs.length;
  745. morphs.push( mesh );
  746. } else {
  747. if ( geom.isLineStrip === true ) {
  748. mesh = new THREE.Line( geom );
  749. } else {
  750. mesh = new THREE.Mesh( geom, material );
  751. }
  752. }
  753. obj.add(mesh);
  754. }
  755. }
  756. for ( i = 0; i < node.cameras.length; i ++ ) {
  757. var instance_camera = node.cameras[i];
  758. var cparams = cameras[instance_camera.url];
  759. var cam = new THREE.PerspectiveCamera(cparams.yfov, parseFloat(cparams.aspect_ratio),
  760. parseFloat(cparams.znear), parseFloat(cparams.zfar));
  761. obj.add(cam);
  762. }
  763. for ( i = 0; i < node.lights.length; i ++ ) {
  764. var light = null;
  765. var instance_light = node.lights[i];
  766. var lparams = lights[instance_light.url];
  767. if ( lparams && lparams.technique ) {
  768. var color = lparams.color.getHex();
  769. var intensity = lparams.intensity;
  770. var distance = lparams.distance;
  771. var angle = lparams.falloff_angle;
  772. var exponent; // Intentionally undefined, don't know what this is yet
  773. switch ( lparams.technique ) {
  774. case 'directional':
  775. light = new THREE.DirectionalLight( color, intensity, distance );
  776. light.position.set(0, 0, 1);
  777. break;
  778. case 'point':
  779. light = new THREE.PointLight( color, intensity, distance );
  780. break;
  781. case 'spot':
  782. light = new THREE.SpotLight( color, intensity, distance, angle, exponent );
  783. light.position.set(0, 0, 1);
  784. break;
  785. case 'ambient':
  786. light = new THREE.AmbientLight( color );
  787. break;
  788. }
  789. }
  790. if (light) {
  791. obj.add(light);
  792. }
  793. }
  794. obj.name = node.name || node.id || "";
  795. obj.colladaId = node.id || "";
  796. obj.layer = node.layer || "";
  797. obj.matrix = node.matrix;
  798. obj.matrix.decompose( obj.position, obj.quaternion, obj.scale );
  799. if ( options.centerGeometry && obj.geometry ) {
  800. var delta = obj.geometry.center();
  801. delta.multiply( obj.scale );
  802. delta.applyQuaternion( obj.quaternion );
  803. obj.position.sub( delta );
  804. }
  805. for ( i = 0; i < node.nodes.length; i ++ ) {
  806. obj.add( createSceneGraph( node.nodes[i], node ) );
  807. }
  808. return obj;
  809. }
  810. function getJointId( skin, id ) {
  811. for ( var i = 0; i < skin.joints.length; i ++ ) {
  812. if ( skin.joints[ i ] === id ) {
  813. return i;
  814. }
  815. }
  816. }
  817. function getLibraryNode( id ) {
  818. var nodes = COLLADA.querySelectorAll('library_nodes node');
  819. for ( var i = 0; i < nodes.length; i++ ) {
  820. var attObj = nodes[i].attributes.getNamedItem('id');
  821. if ( attObj && attObj.value === id ) {
  822. return nodes[i];
  823. }
  824. }
  825. return undefined;
  826. }
  827. function getChannelsForNode ( node ) {
  828. var channels = [];
  829. var startTime = 1000000;
  830. var endTime = -1000000;
  831. for ( var id in animations ) {
  832. var animation = animations[id];
  833. for ( var i = 0; i < animation.channel.length; i ++ ) {
  834. var channel = animation.channel[i];
  835. var sampler = animation.sampler[i];
  836. var id = channel.target.split('/')[0];
  837. if ( id == node.id ) {
  838. sampler.create();
  839. channel.sampler = sampler;
  840. startTime = Math.min(startTime, sampler.startTime);
  841. endTime = Math.max(endTime, sampler.endTime);
  842. channels.push(channel);
  843. }
  844. }
  845. }
  846. if ( channels.length ) {
  847. node.startTime = startTime;
  848. node.endTime = endTime;
  849. }
  850. return channels;
  851. }
  852. function calcFrameDuration( node ) {
  853. var minT = 10000000;
  854. for ( var i = 0; i < node.channels.length; i ++ ) {
  855. var sampler = node.channels[i].sampler;
  856. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  857. var t0 = sampler.input[ j ];
  858. var t1 = sampler.input[ j + 1 ];
  859. minT = Math.min( minT, t1 - t0 );
  860. }
  861. }
  862. return minT;
  863. }
  864. function calcMatrixAt( node, t ) {
  865. var animated = {};
  866. var i, j;
  867. for ( i = 0; i < node.channels.length; i ++ ) {
  868. var channel = node.channels[ i ];
  869. animated[ channel.sid ] = channel;
  870. }
  871. var matrix = new THREE.Matrix4();
  872. for ( i = 0; i < node.transforms.length; i ++ ) {
  873. var transform = node.transforms[ i ];
  874. var channel = animated[ transform.sid ];
  875. if ( channel !== undefined ) {
  876. var sampler = channel.sampler;
  877. var value;
  878. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  879. if ( sampler.input[ j + 1 ] > t ) {
  880. value = sampler.output[ j ];
  881. //console.log(value.flatten)
  882. break;
  883. }
  884. }
  885. if ( value !== undefined ) {
  886. if ( value instanceof THREE.Matrix4 ) {
  887. matrix.multiplyMatrices( matrix, value );
  888. } else {
  889. // FIXME: handle other types
  890. matrix.multiplyMatrices( matrix, transform.matrix );
  891. }
  892. } else {
  893. matrix.multiplyMatrices( matrix, transform.matrix );
  894. }
  895. } else {
  896. matrix.multiplyMatrices( matrix, transform.matrix );
  897. }
  898. }
  899. return matrix;
  900. }
  901. function bakeAnimations ( node ) {
  902. if ( node.channels && node.channels.length ) {
  903. var keys = [],
  904. sids = [];
  905. for ( var i = 0, il = node.channels.length; i < il; i ++ ) {
  906. var channel = node.channels[i],
  907. fullSid = channel.fullSid,
  908. sampler = channel.sampler,
  909. input = sampler.input,
  910. transform = node.getTransformBySid( channel.sid ),
  911. member;
  912. if ( channel.arrIndices ) {
  913. member = [];
  914. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j ++ ) {
  915. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  916. }
  917. } else {
  918. member = getConvertedMember( channel.member );
  919. }
  920. if ( transform ) {
  921. if ( sids.indexOf( fullSid ) === -1 ) {
  922. sids.push( fullSid );
  923. }
  924. for ( var j = 0, jl = input.length; j < jl; j ++ ) {
  925. var time = input[j],
  926. data = sampler.getData( transform.type, j, member ),
  927. key = findKey( keys, time );
  928. if ( !key ) {
  929. key = new Key( time );
  930. var timeNdx = findTimeNdx( keys, time );
  931. keys.splice( timeNdx === -1 ? keys.length : timeNdx, 0, key );
  932. }
  933. key.addTarget( fullSid, transform, member, data );
  934. }
  935. } else {
  936. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  937. }
  938. }
  939. // post process
  940. for ( var i = 0; i < sids.length; i ++ ) {
  941. var sid = sids[ i ];
  942. for ( var j = 0; j < keys.length; j ++ ) {
  943. var key = keys[ j ];
  944. if ( !key.hasTarget( sid ) ) {
  945. interpolateKeys( keys, key, j, sid );
  946. }
  947. }
  948. }
  949. node.keys = keys;
  950. node.sids = sids;
  951. }
  952. }
  953. function findKey ( keys, time) {
  954. var retVal = null;
  955. for ( var i = 0, il = keys.length; i < il && retVal === null; i ++ ) {
  956. var key = keys[i];
  957. if ( key.time === time ) {
  958. retVal = key;
  959. } else if ( key.time > time ) {
  960. break;
  961. }
  962. }
  963. return retVal;
  964. }
  965. function findTimeNdx ( keys, time) {
  966. var ndx = -1;
  967. for ( var i = 0, il = keys.length; i < il && ndx === -1; i ++ ) {
  968. var key = keys[i];
  969. if ( key.time >= time ) {
  970. ndx = i;
  971. }
  972. }
  973. return ndx;
  974. }
  975. function interpolateKeys ( keys, key, ndx, fullSid ) {
  976. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx - 1 : 0 ),
  977. nextKey = getNextKeyWith( keys, fullSid, ndx + 1 );
  978. if ( prevKey && nextKey ) {
  979. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  980. prevTarget = prevKey.getTarget( fullSid ),
  981. nextData = nextKey.getTarget( fullSid ).data,
  982. prevData = prevTarget.data,
  983. data;
  984. if ( prevTarget.type === 'matrix' ) {
  985. data = prevData;
  986. } else if ( prevData.length ) {
  987. data = [];
  988. for ( var i = 0; i < prevData.length; ++ i ) {
  989. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  990. }
  991. } else {
  992. data = prevData + ( nextData - prevData ) * scale;
  993. }
  994. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  995. }
  996. }
  997. // Get next key with given sid
  998. function getNextKeyWith( keys, fullSid, ndx ) {
  999. for ( ; ndx < keys.length; ndx ++ ) {
  1000. var key = keys[ ndx ];
  1001. if ( key.hasTarget( fullSid ) ) {
  1002. return key;
  1003. }
  1004. }
  1005. return null;
  1006. }
  1007. // Get previous key with given sid
  1008. function getPrevKeyWith( keys, fullSid, ndx ) {
  1009. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  1010. for ( ; ndx >= 0; ndx -- ) {
  1011. var key = keys[ ndx ];
  1012. if ( key.hasTarget( fullSid ) ) {
  1013. return key;
  1014. }
  1015. }
  1016. return null;
  1017. }
  1018. function _Image() {
  1019. this.id = "";
  1020. this.init_from = "";
  1021. }
  1022. _Image.prototype.parse = function(element) {
  1023. this.id = element.getAttribute('id');
  1024. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1025. var child = element.childNodes[ i ];
  1026. if ( child.nodeName === 'init_from' ) {
  1027. this.init_from = child.textContent;
  1028. }
  1029. }
  1030. return this;
  1031. };
  1032. function Controller() {
  1033. this.id = "";
  1034. this.name = "";
  1035. this.type = "";
  1036. this.skin = null;
  1037. this.morph = null;
  1038. }
  1039. Controller.prototype.parse = function( element ) {
  1040. this.id = element.getAttribute('id');
  1041. this.name = element.getAttribute('name');
  1042. this.type = "none";
  1043. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1044. var child = element.childNodes[ i ];
  1045. switch ( child.nodeName ) {
  1046. case 'skin':
  1047. this.skin = (new Skin()).parse(child);
  1048. this.type = child.nodeName;
  1049. break;
  1050. case 'morph':
  1051. this.morph = (new Morph()).parse(child);
  1052. this.type = child.nodeName;
  1053. break;
  1054. default:
  1055. break;
  1056. }
  1057. }
  1058. return this;
  1059. };
  1060. function Morph() {
  1061. this.method = null;
  1062. this.source = null;
  1063. this.targets = null;
  1064. this.weights = null;
  1065. }
  1066. Morph.prototype.parse = function( element ) {
  1067. var sources = {};
  1068. var inputs = [];
  1069. var i;
  1070. this.method = element.getAttribute( 'method' );
  1071. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  1072. for ( i = 0; i < element.childNodes.length; i ++ ) {
  1073. var child = element.childNodes[ i ];
  1074. if ( child.nodeType != 1 ) continue;
  1075. switch ( child.nodeName ) {
  1076. case 'source':
  1077. var source = ( new Source() ).parse( child );
  1078. sources[ source.id ] = source;
  1079. break;
  1080. case 'targets':
  1081. inputs = this.parseInputs( child );
  1082. break;
  1083. default:
  1084. console.log( child.nodeName );
  1085. break;
  1086. }
  1087. }
  1088. for ( i = 0; i < inputs.length; i ++ ) {
  1089. var input = inputs[ i ];
  1090. var source = sources[ input.source ];
  1091. switch ( input.semantic ) {
  1092. case 'MORPH_TARGET':
  1093. this.targets = source.read();
  1094. break;
  1095. case 'MORPH_WEIGHT':
  1096. this.weights = source.read();
  1097. break;
  1098. default:
  1099. break;
  1100. }
  1101. }
  1102. return this;
  1103. };
  1104. Morph.prototype.parseInputs = function(element) {
  1105. var inputs = [];
  1106. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1107. var child = element.childNodes[i];
  1108. if ( child.nodeType != 1) continue;
  1109. switch ( child.nodeName ) {
  1110. case 'input':
  1111. inputs.push( (new Input()).parse(child) );
  1112. break;
  1113. default:
  1114. break;
  1115. }
  1116. }
  1117. return inputs;
  1118. };
  1119. function Skin() {
  1120. this.source = "";
  1121. this.bindShapeMatrix = null;
  1122. this.invBindMatrices = [];
  1123. this.joints = [];
  1124. this.weights = [];
  1125. }
  1126. Skin.prototype.parse = function( element ) {
  1127. var sources = {};
  1128. var joints, weights;
  1129. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  1130. this.invBindMatrices = [];
  1131. this.joints = [];
  1132. this.weights = [];
  1133. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1134. var child = element.childNodes[i];
  1135. if ( child.nodeType != 1 ) continue;
  1136. switch ( child.nodeName ) {
  1137. case 'bind_shape_matrix':
  1138. var f = _floats(child.textContent);
  1139. this.bindShapeMatrix = getConvertedMat4( f );
  1140. break;
  1141. case 'source':
  1142. var src = new Source().parse(child);
  1143. sources[ src.id ] = src;
  1144. break;
  1145. case 'joints':
  1146. joints = child;
  1147. break;
  1148. case 'vertex_weights':
  1149. weights = child;
  1150. break;
  1151. default:
  1152. console.log( child.nodeName );
  1153. break;
  1154. }
  1155. }
  1156. this.parseJoints( joints, sources );
  1157. this.parseWeights( weights, sources );
  1158. return this;
  1159. };
  1160. Skin.prototype.parseJoints = function ( element, sources ) {
  1161. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1162. var child = element.childNodes[ i ];
  1163. if ( child.nodeType != 1 ) continue;
  1164. switch ( child.nodeName ) {
  1165. case 'input':
  1166. var input = ( new Input() ).parse( child );
  1167. var source = sources[ input.source ];
  1168. if ( input.semantic === 'JOINT' ) {
  1169. this.joints = source.read();
  1170. } else if ( input.semantic === 'INV_BIND_MATRIX' ) {
  1171. this.invBindMatrices = source.read();
  1172. }
  1173. break;
  1174. default:
  1175. break;
  1176. }
  1177. }
  1178. };
  1179. Skin.prototype.parseWeights = function ( element, sources ) {
  1180. var v, vcount, inputs = [];
  1181. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1182. var child = element.childNodes[ i ];
  1183. if ( child.nodeType != 1 ) continue;
  1184. switch ( child.nodeName ) {
  1185. case 'input':
  1186. inputs.push( ( new Input() ).parse( child ) );
  1187. break;
  1188. case 'v':
  1189. v = _ints( child.textContent );
  1190. break;
  1191. case 'vcount':
  1192. vcount = _ints( child.textContent );
  1193. break;
  1194. default:
  1195. break;
  1196. }
  1197. }
  1198. var index = 0;
  1199. for ( var i = 0; i < vcount.length; i ++ ) {
  1200. var numBones = vcount[i];
  1201. var vertex_weights = [];
  1202. for ( var j = 0; j < numBones; j ++ ) {
  1203. var influence = {};
  1204. for ( var k = 0; k < inputs.length; k ++ ) {
  1205. var input = inputs[ k ];
  1206. var value = v[ index + input.offset ];
  1207. switch ( input.semantic ) {
  1208. case 'JOINT':
  1209. influence.joint = value;//this.joints[value];
  1210. break;
  1211. case 'WEIGHT':
  1212. influence.weight = sources[ input.source ].data[ value ];
  1213. break;
  1214. default:
  1215. break;
  1216. }
  1217. }
  1218. vertex_weights.push( influence );
  1219. index += inputs.length;
  1220. }
  1221. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  1222. vertex_weights[ j ].index = i;
  1223. }
  1224. this.weights.push( vertex_weights );
  1225. }
  1226. };
  1227. function VisualScene () {
  1228. this.id = "";
  1229. this.name = "";
  1230. this.nodes = [];
  1231. this.scene = new THREE.Group();
  1232. }
  1233. VisualScene.prototype.getChildById = function( id, recursive ) {
  1234. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1235. var node = this.nodes[ i ].getChildById( id, recursive );
  1236. if ( node ) {
  1237. return node;
  1238. }
  1239. }
  1240. return null;
  1241. };
  1242. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  1243. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1244. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  1245. if ( node ) {
  1246. return node;
  1247. }
  1248. }
  1249. return null;
  1250. };
  1251. VisualScene.prototype.parse = function( element ) {
  1252. this.id = element.getAttribute( 'id' );
  1253. this.name = element.getAttribute( 'name' );
  1254. this.nodes = [];
  1255. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1256. var child = element.childNodes[ i ];
  1257. if ( child.nodeType != 1 ) continue;
  1258. switch ( child.nodeName ) {
  1259. case 'node':
  1260. this.nodes.push( ( new Node() ).parse( child ) );
  1261. break;
  1262. default:
  1263. break;
  1264. }
  1265. }
  1266. return this;
  1267. };
  1268. function Node() {
  1269. this.id = "";
  1270. this.name = "";
  1271. this.sid = "";
  1272. this.nodes = [];
  1273. this.controllers = [];
  1274. this.transforms = [];
  1275. this.geometries = [];
  1276. this.channels = [];
  1277. this.matrix = new THREE.Matrix4();
  1278. }
  1279. Node.prototype.getChannelForTransform = function( transformSid ) {
  1280. for ( var i = 0; i < this.channels.length; i ++ ) {
  1281. var channel = this.channels[i];
  1282. var parts = channel.target.split('/');
  1283. var id = parts.shift();
  1284. var sid = parts.shift();
  1285. var dotSyntax = (sid.indexOf(".") >= 0);
  1286. var arrSyntax = (sid.indexOf("(") >= 0);
  1287. var arrIndices;
  1288. var member;
  1289. if ( dotSyntax ) {
  1290. parts = sid.split(".");
  1291. sid = parts.shift();
  1292. member = parts.shift();
  1293. } else if ( arrSyntax ) {
  1294. arrIndices = sid.split("(");
  1295. sid = arrIndices.shift();
  1296. for ( var j = 0; j < arrIndices.length; j ++ ) {
  1297. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  1298. }
  1299. }
  1300. if ( sid === transformSid ) {
  1301. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  1302. return channel;
  1303. }
  1304. }
  1305. return null;
  1306. };
  1307. Node.prototype.getChildById = function ( id, recursive ) {
  1308. if ( this.id === id ) {
  1309. return this;
  1310. }
  1311. if ( recursive ) {
  1312. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1313. var n = this.nodes[ i ].getChildById( id, recursive );
  1314. if ( n ) {
  1315. return n;
  1316. }
  1317. }
  1318. }
  1319. return null;
  1320. };
  1321. Node.prototype.getChildBySid = function ( sid, recursive ) {
  1322. if ( this.sid === sid ) {
  1323. return this;
  1324. }
  1325. if ( recursive ) {
  1326. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1327. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  1328. if ( n ) {
  1329. return n;
  1330. }
  1331. }
  1332. }
  1333. return null;
  1334. };
  1335. Node.prototype.getTransformBySid = function ( sid ) {
  1336. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1337. if ( this.transforms[ i ].sid === sid ) return this.transforms[ i ];
  1338. }
  1339. return null;
  1340. };
  1341. Node.prototype.parse = function( element ) {
  1342. var url;
  1343. this.id = element.getAttribute('id');
  1344. this.sid = element.getAttribute('sid');
  1345. this.name = element.getAttribute('name');
  1346. this.type = element.getAttribute('type');
  1347. this.layer = element.getAttribute('layer');
  1348. this.type = this.type === 'JOINT' ? this.type : 'NODE';
  1349. this.nodes = [];
  1350. this.transforms = [];
  1351. this.geometries = [];
  1352. this.cameras = [];
  1353. this.lights = [];
  1354. this.controllers = [];
  1355. this.matrix = new THREE.Matrix4();
  1356. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1357. var child = element.childNodes[ i ];
  1358. if ( child.nodeType != 1 ) continue;
  1359. switch ( child.nodeName ) {
  1360. case 'node':
  1361. this.nodes.push( ( new Node() ).parse( child ) );
  1362. break;
  1363. case 'instance_camera':
  1364. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  1365. break;
  1366. case 'instance_controller':
  1367. this.controllers.push( ( new InstanceController() ).parse( child ) );
  1368. break;
  1369. case 'instance_geometry':
  1370. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  1371. break;
  1372. case 'instance_light':
  1373. this.lights.push( ( new InstanceLight() ).parse( child ) );
  1374. break;
  1375. case 'instance_node':
  1376. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  1377. var iNode = getLibraryNode( url );
  1378. if ( iNode ) {
  1379. this.nodes.push( ( new Node() ).parse( iNode )) ;
  1380. }
  1381. break;
  1382. case 'rotate':
  1383. case 'translate':
  1384. case 'scale':
  1385. case 'matrix':
  1386. case 'lookat':
  1387. case 'skew':
  1388. this.transforms.push( ( new Transform() ).parse( child ) );
  1389. break;
  1390. case 'extra':
  1391. break;
  1392. default:
  1393. console.log( child.nodeName );
  1394. break;
  1395. }
  1396. }
  1397. this.channels = getChannelsForNode( this );
  1398. bakeAnimations( this );
  1399. this.updateMatrix();
  1400. return this;
  1401. };
  1402. Node.prototype.updateMatrix = function () {
  1403. this.matrix.identity();
  1404. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1405. this.transforms[ i ].apply( this.matrix );
  1406. }
  1407. };
  1408. function Transform () {
  1409. this.sid = "";
  1410. this.type = "";
  1411. this.data = [];
  1412. this.obj = null;
  1413. }
  1414. Transform.prototype.parse = function ( element ) {
  1415. this.sid = element.getAttribute( 'sid' );
  1416. this.type = element.nodeName;
  1417. this.data = _floats( element.textContent );
  1418. this.convert();
  1419. return this;
  1420. };
  1421. Transform.prototype.convert = function () {
  1422. switch ( this.type ) {
  1423. case 'matrix':
  1424. this.obj = getConvertedMat4( this.data );
  1425. break;
  1426. case 'rotate':
  1427. this.angle = THREE.Math.degToRad( this.data[3] );
  1428. case 'translate':
  1429. fixCoords( this.data, -1 );
  1430. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1431. break;
  1432. case 'scale':
  1433. fixCoords( this.data, 1 );
  1434. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1435. break;
  1436. default:
  1437. console.log( 'Can not convert Transform of type ' + this.type );
  1438. break;
  1439. }
  1440. };
  1441. Transform.prototype.apply = function () {
  1442. var m1 = new THREE.Matrix4();
  1443. return function ( matrix ) {
  1444. switch ( this.type ) {
  1445. case 'matrix':
  1446. matrix.multiply( this.obj );
  1447. break;
  1448. case 'translate':
  1449. matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
  1450. break;
  1451. case 'rotate':
  1452. matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
  1453. break;
  1454. case 'scale':
  1455. matrix.scale( this.obj );
  1456. break;
  1457. }
  1458. };
  1459. }();
  1460. Transform.prototype.update = function ( data, member ) {
  1461. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  1462. switch ( this.type ) {
  1463. case 'matrix':
  1464. if ( ! member ) {
  1465. this.obj.copy( data );
  1466. } else if ( member.length === 1 ) {
  1467. switch ( member[ 0 ] ) {
  1468. case 0:
  1469. this.obj.n11 = data[ 0 ];
  1470. this.obj.n21 = data[ 1 ];
  1471. this.obj.n31 = data[ 2 ];
  1472. this.obj.n41 = data[ 3 ];
  1473. break;
  1474. case 1:
  1475. this.obj.n12 = data[ 0 ];
  1476. this.obj.n22 = data[ 1 ];
  1477. this.obj.n32 = data[ 2 ];
  1478. this.obj.n42 = data[ 3 ];
  1479. break;
  1480. case 2:
  1481. this.obj.n13 = data[ 0 ];
  1482. this.obj.n23 = data[ 1 ];
  1483. this.obj.n33 = data[ 2 ];
  1484. this.obj.n43 = data[ 3 ];
  1485. break;
  1486. case 3:
  1487. this.obj.n14 = data[ 0 ];
  1488. this.obj.n24 = data[ 1 ];
  1489. this.obj.n34 = data[ 2 ];
  1490. this.obj.n44 = data[ 3 ];
  1491. break;
  1492. }
  1493. } else if ( member.length === 2 ) {
  1494. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  1495. this.obj[ propName ] = data;
  1496. } else {
  1497. console.log('Incorrect addressing of matrix in transform.');
  1498. }
  1499. break;
  1500. case 'translate':
  1501. case 'scale':
  1502. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1503. member = members[ member[ 0 ] ];
  1504. }
  1505. switch ( member ) {
  1506. case 'X':
  1507. this.obj.x = data;
  1508. break;
  1509. case 'Y':
  1510. this.obj.y = data;
  1511. break;
  1512. case 'Z':
  1513. this.obj.z = data;
  1514. break;
  1515. default:
  1516. this.obj.x = data[ 0 ];
  1517. this.obj.y = data[ 1 ];
  1518. this.obj.z = data[ 2 ];
  1519. break;
  1520. }
  1521. break;
  1522. case 'rotate':
  1523. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1524. member = members[ member[ 0 ] ];
  1525. }
  1526. switch ( member ) {
  1527. case 'X':
  1528. this.obj.x = data;
  1529. break;
  1530. case 'Y':
  1531. this.obj.y = data;
  1532. break;
  1533. case 'Z':
  1534. this.obj.z = data;
  1535. break;
  1536. case 'ANGLE':
  1537. this.angle = THREE.Math.degToRad( data );
  1538. break;
  1539. default:
  1540. this.obj.x = data[ 0 ];
  1541. this.obj.y = data[ 1 ];
  1542. this.obj.z = data[ 2 ];
  1543. this.angle = THREE.Math.degToRad( data[ 3 ] );
  1544. break;
  1545. }
  1546. break;
  1547. }
  1548. };
  1549. function InstanceController() {
  1550. this.url = "";
  1551. this.skeleton = [];
  1552. this.instance_material = [];
  1553. }
  1554. InstanceController.prototype.parse = function ( element ) {
  1555. this.url = element.getAttribute('url').replace(/^#/, '');
  1556. this.skeleton = [];
  1557. this.instance_material = [];
  1558. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1559. var child = element.childNodes[ i ];
  1560. if ( child.nodeType !== 1 ) continue;
  1561. switch ( child.nodeName ) {
  1562. case 'skeleton':
  1563. this.skeleton.push( child.textContent.replace(/^#/, '') );
  1564. break;
  1565. case 'bind_material':
  1566. var instances = child.querySelectorAll('instance_material');
  1567. for ( var j = 0; j < instances.length; j ++ ) {
  1568. var instance = instances[j];
  1569. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1570. }
  1571. break;
  1572. case 'extra':
  1573. break;
  1574. default:
  1575. break;
  1576. }
  1577. }
  1578. return this;
  1579. };
  1580. function InstanceMaterial () {
  1581. this.symbol = "";
  1582. this.target = "";
  1583. }
  1584. InstanceMaterial.prototype.parse = function ( element ) {
  1585. this.symbol = element.getAttribute('symbol');
  1586. this.target = element.getAttribute('target').replace(/^#/, '');
  1587. return this;
  1588. };
  1589. function InstanceGeometry() {
  1590. this.url = "";
  1591. this.instance_material = [];
  1592. }
  1593. InstanceGeometry.prototype.parse = function ( element ) {
  1594. this.url = element.getAttribute('url').replace(/^#/, '');
  1595. this.instance_material = [];
  1596. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1597. var child = element.childNodes[i];
  1598. if ( child.nodeType != 1 ) continue;
  1599. if ( child.nodeName === 'bind_material' ) {
  1600. var instances = child.querySelectorAll('instance_material');
  1601. for ( var j = 0; j < instances.length; j ++ ) {
  1602. var instance = instances[j];
  1603. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1604. }
  1605. break;
  1606. }
  1607. }
  1608. return this;
  1609. };
  1610. function Geometry() {
  1611. this.id = "";
  1612. this.mesh = null;
  1613. }
  1614. Geometry.prototype.parse = function ( element ) {
  1615. this.id = element.getAttribute('id');
  1616. extractDoubleSided( this, element );
  1617. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1618. var child = element.childNodes[i];
  1619. switch ( child.nodeName ) {
  1620. case 'mesh':
  1621. this.mesh = (new Mesh(this)).parse(child);
  1622. break;
  1623. case 'extra':
  1624. // console.log( child );
  1625. break;
  1626. default:
  1627. break;
  1628. }
  1629. }
  1630. return this;
  1631. };
  1632. function Mesh( geometry ) {
  1633. this.geometry = geometry.id;
  1634. this.primitives = [];
  1635. this.vertices = null;
  1636. this.geometry3js = null;
  1637. }
  1638. Mesh.prototype.parse = function ( element ) {
  1639. this.primitives = [];
  1640. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1641. var child = element.childNodes[ i ];
  1642. switch ( child.nodeName ) {
  1643. case 'source':
  1644. _source( child );
  1645. break;
  1646. case 'vertices':
  1647. this.vertices = ( new Vertices() ).parse( child );
  1648. break;
  1649. case 'linestrips':
  1650. this.primitives.push( ( new LineStrips().parse( child ) ) );
  1651. break;
  1652. case 'triangles':
  1653. this.primitives.push( ( new Triangles().parse( child ) ) );
  1654. break;
  1655. case 'polygons':
  1656. this.primitives.push( ( new Polygons().parse( child ) ) );
  1657. break;
  1658. case 'polylist':
  1659. this.primitives.push( ( new Polylist().parse( child ) ) );
  1660. break;
  1661. default:
  1662. break;
  1663. }
  1664. }
  1665. this.geometry3js = new THREE.Geometry();
  1666. if ( this.vertices === null ) {
  1667. // TODO (mrdoob): Study case when this is null (carrier.dae)
  1668. return this;
  1669. }
  1670. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  1671. for ( var i = 0; i < vertexData.length; i += 3 ) {
  1672. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  1673. }
  1674. for ( var i = 0; i < this.primitives.length; i ++ ) {
  1675. var primitive = this.primitives[ i ];
  1676. primitive.setVertices( this.vertices );
  1677. this.handlePrimitive( primitive, this.geometry3js );
  1678. }
  1679. if ( this.geometry3js.calcNormals ) {
  1680. this.geometry3js.computeVertexNormals();
  1681. delete this.geometry3js.calcNormals;
  1682. }
  1683. return this;
  1684. };
  1685. Mesh.prototype.handlePrimitive = function ( primitive, geom ) {
  1686. if ( primitive instanceof LineStrips ) {
  1687. // TODO: Handle indices. Maybe easier with BufferGeometry?
  1688. geom.isLineStrip = true;
  1689. return;
  1690. }
  1691. var j, k, pList = primitive.p, inputs = primitive.inputs;
  1692. var input, index, idx32;
  1693. var source, numParams;
  1694. var vcIndex = 0, vcount = 3, maxOffset = 0;
  1695. var texture_sets = [];
  1696. for ( j = 0; j < inputs.length; j ++ ) {
  1697. input = inputs[ j ];
  1698. var offset = input.offset + 1;
  1699. maxOffset = (maxOffset < offset) ? offset : maxOffset;
  1700. switch ( input.semantic ) {
  1701. case 'TEXCOORD':
  1702. texture_sets.push( input.set );
  1703. break;
  1704. }
  1705. }
  1706. for ( var pCount = 0; pCount < pList.length; ++ pCount ) {
  1707. var p = pList[ pCount ], i = 0;
  1708. while ( i < p.length ) {
  1709. var vs = [];
  1710. var ns = [];
  1711. var ts = null;
  1712. var cs = [];
  1713. if ( primitive.vcount ) {
  1714. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  1715. } else {
  1716. vcount = p.length / maxOffset;
  1717. }
  1718. for ( j = 0; j < vcount; j ++ ) {
  1719. for ( k = 0; k < inputs.length; k ++ ) {
  1720. input = inputs[ k ];
  1721. source = sources[ input.source ];
  1722. index = p[ i + ( j * maxOffset ) + input.offset ];
  1723. numParams = source.accessor.params.length;
  1724. idx32 = index * numParams;
  1725. switch ( input.semantic ) {
  1726. case 'VERTEX':
  1727. vs.push( index );
  1728. break;
  1729. case 'NORMAL':
  1730. ns.push( getConvertedVec3( source.data, idx32 ) );
  1731. break;
  1732. case 'TEXCOORD':
  1733. ts = ts || { };
  1734. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  1735. // invert the V
  1736. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  1737. break;
  1738. case 'COLOR':
  1739. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1740. break;
  1741. default:
  1742. break;
  1743. }
  1744. }
  1745. }
  1746. if ( ns.length === 0 ) {
  1747. // check the vertices inputs
  1748. input = this.vertices.input.NORMAL;
  1749. if ( input ) {
  1750. source = sources[ input.source ];
  1751. numParams = source.accessor.params.length;
  1752. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1753. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  1754. }
  1755. } else {
  1756. geom.calcNormals = true;
  1757. }
  1758. }
  1759. if ( !ts ) {
  1760. ts = { };
  1761. // check the vertices inputs
  1762. input = this.vertices.input.TEXCOORD;
  1763. if ( input ) {
  1764. texture_sets.push( input.set );
  1765. source = sources[ input.source ];
  1766. numParams = source.accessor.params.length;
  1767. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1768. idx32 = vs[ ndx ] * numParams;
  1769. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  1770. // invert the V
  1771. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  1772. }
  1773. }
  1774. }
  1775. if ( cs.length === 0 ) {
  1776. // check the vertices inputs
  1777. input = this.vertices.input.COLOR;
  1778. if ( input ) {
  1779. source = sources[ input.source ];
  1780. numParams = source.accessor.params.length;
  1781. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1782. idx32 = vs[ ndx ] * numParams;
  1783. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1784. }
  1785. }
  1786. }
  1787. var face = null, faces = [], uv, uvArr;
  1788. if ( vcount === 3 ) {
  1789. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  1790. } else if ( vcount === 4 ) {
  1791. faces.push( new THREE.Face3( vs[0], vs[1], vs[3], [ ns[0].clone(), ns[1].clone(), ns[3].clone() ], cs.length ? [ cs[0], cs[1], cs[3] ] : new THREE.Color() ) );
  1792. faces.push( new THREE.Face3( vs[1], vs[2], vs[3], [ ns[1].clone(), ns[2].clone(), ns[3].clone() ], cs.length ? [ cs[1], cs[2], cs[3] ] : new THREE.Color() ) );
  1793. } else if ( vcount > 4 && options.subdivideFaces ) {
  1794. var clr = cs.length ? cs : new THREE.Color(),
  1795. vec1, vec2, vec3, v1, v2, norm;
  1796. // subdivide into multiple Face3s
  1797. for ( k = 1; k < vcount - 1; ) {
  1798. faces.push( new THREE.Face3( vs[0], vs[k], vs[k + 1], [ ns[0].clone(), ns[k ++].clone(), ns[k].clone() ], clr ) );
  1799. }
  1800. }
  1801. if ( faces.length ) {
  1802. for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
  1803. face = faces[ndx];
  1804. face.daeMaterial = primitive.material;
  1805. geom.faces.push( face );
  1806. for ( k = 0; k < texture_sets.length; k ++ ) {
  1807. uv = ts[ texture_sets[k] ];
  1808. if ( vcount > 4 ) {
  1809. // Grab the right UVs for the vertices in this face
  1810. uvArr = [ uv[0], uv[ndx + 1], uv[ndx + 2] ];
  1811. } else if ( vcount === 4 ) {
  1812. if ( ndx === 0 ) {
  1813. uvArr = [ uv[0], uv[1], uv[3] ];
  1814. } else {
  1815. uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ];
  1816. }
  1817. } else {
  1818. uvArr = [ uv[0], uv[1], uv[2] ];
  1819. }
  1820. if ( geom.faceVertexUvs[k] === undefined ) {
  1821. geom.faceVertexUvs[k] = [];
  1822. }
  1823. geom.faceVertexUvs[k].push( uvArr );
  1824. }
  1825. }
  1826. } else {
  1827. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  1828. }
  1829. i += maxOffset * vcount;
  1830. }
  1831. }
  1832. };
  1833. function Polygons () {
  1834. this.material = "";
  1835. this.count = 0;
  1836. this.inputs = [];
  1837. this.vcount = null;
  1838. this.p = [];
  1839. this.geometry = new THREE.Geometry();
  1840. }
  1841. Polygons.prototype.setVertices = function ( vertices ) {
  1842. for ( var i = 0; i < this.inputs.length; i ++ ) {
  1843. if ( this.inputs[ i ].source === vertices.id ) {
  1844. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  1845. }
  1846. }
  1847. };
  1848. Polygons.prototype.parse = function ( element ) {
  1849. this.material = element.getAttribute( 'material' );
  1850. this.count = _attr_as_int( element, 'count', 0 );
  1851. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1852. var child = element.childNodes[ i ];
  1853. switch ( child.nodeName ) {
  1854. case 'input':
  1855. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  1856. break;
  1857. case 'vcount':
  1858. this.vcount = _ints( child.textContent );
  1859. break;
  1860. case 'p':
  1861. this.p.push( _ints( child.textContent ) );
  1862. break;
  1863. case 'ph':
  1864. console.warn( 'polygon holes not yet supported!' );
  1865. break;
  1866. default:
  1867. break;
  1868. }
  1869. }
  1870. return this;
  1871. };
  1872. function Polylist () {
  1873. Polygons.call( this );
  1874. this.vcount = [];
  1875. }
  1876. Polylist.prototype = Object.create( Polygons.prototype );
  1877. Polylist.prototype.constructor = Polylist;
  1878. function LineStrips() {
  1879. Polygons.call( this );
  1880. this.vcount = 1;
  1881. }
  1882. LineStrips.prototype = Object.create( Polygons.prototype );
  1883. LineStrips.prototype.constructor = LineStrips;
  1884. function Triangles () {
  1885. Polygons.call( this );
  1886. this.vcount = 3;
  1887. }
  1888. Triangles.prototype = Object.create( Polygons.prototype );
  1889. Triangles.prototype.constructor = Triangles;
  1890. function Accessor() {
  1891. this.source = "";
  1892. this.count = 0;
  1893. this.stride = 0;
  1894. this.params = [];
  1895. }
  1896. Accessor.prototype.parse = function ( element ) {
  1897. this.params = [];
  1898. this.source = element.getAttribute( 'source' );
  1899. this.count = _attr_as_int( element, 'count', 0 );
  1900. this.stride = _attr_as_int( element, 'stride', 0 );
  1901. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1902. var child = element.childNodes[ i ];
  1903. if ( child.nodeName === 'param' ) {
  1904. var param = {};
  1905. param[ 'name' ] = child.getAttribute( 'name' );
  1906. param[ 'type' ] = child.getAttribute( 'type' );
  1907. this.params.push( param );
  1908. }
  1909. }
  1910. return this;
  1911. };
  1912. function Vertices() {
  1913. this.input = {};
  1914. }
  1915. Vertices.prototype.parse = function ( element ) {
  1916. this.id = element.getAttribute('id');
  1917. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1918. if ( element.childNodes[i].nodeName === 'input' ) {
  1919. var input = ( new Input() ).parse( element.childNodes[ i ] );
  1920. this.input[ input.semantic ] = input;
  1921. }
  1922. }
  1923. return this;
  1924. };
  1925. function Input () {
  1926. this.semantic = "";
  1927. this.offset = 0;
  1928. this.source = "";
  1929. this.set = 0;
  1930. }
  1931. Input.prototype.parse = function ( element ) {
  1932. this.semantic = element.getAttribute('semantic');
  1933. this.source = element.getAttribute('source').replace(/^#/, '');
  1934. this.set = _attr_as_int(element, 'set', -1);
  1935. this.offset = _attr_as_int(element, 'offset', 0);
  1936. if ( this.semantic === 'TEXCOORD' && this.set < 0 ) {
  1937. this.set = 0;
  1938. }
  1939. return this;
  1940. };
  1941. function Source ( id ) {
  1942. this.id = id;
  1943. this.type = null;
  1944. }
  1945. Source.prototype.parse = function ( element ) {
  1946. this.id = element.getAttribute( 'id' );
  1947. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1948. var child = element.childNodes[i];
  1949. switch ( child.nodeName ) {
  1950. case 'bool_array':
  1951. this.data = _bools( child.textContent );
  1952. this.type = child.nodeName;
  1953. break;
  1954. case 'float_array':
  1955. this.data = _floats( child.textContent );
  1956. this.type = child.nodeName;
  1957. break;
  1958. case 'int_array':
  1959. this.data = _ints( child.textContent );
  1960. this.type = child.nodeName;
  1961. break;
  1962. case 'IDREF_array':
  1963. case 'Name_array':
  1964. this.data = _strings( child.textContent );
  1965. this.type = child.nodeName;
  1966. break;
  1967. case 'technique_common':
  1968. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  1969. if ( child.childNodes[ j ].nodeName === 'accessor' ) {
  1970. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  1971. break;
  1972. }
  1973. }
  1974. break;
  1975. default:
  1976. // console.log(child.nodeName);
  1977. break;
  1978. }
  1979. }
  1980. return this;
  1981. };
  1982. Source.prototype.read = function () {
  1983. var result = [];
  1984. //for (var i = 0; i < this.accessor.params.length; i++) {
  1985. var param = this.accessor.params[ 0 ];
  1986. //console.log(param.name + " " + param.type);
  1987. switch ( param.type ) {
  1988. case 'IDREF':
  1989. case 'Name': case 'name':
  1990. case 'float':
  1991. return this.data;
  1992. case 'float4x4':
  1993. for ( var j = 0; j < this.data.length; j += 16 ) {
  1994. var s = this.data.slice( j, j + 16 );
  1995. var m = getConvertedMat4( s );
  1996. result.push( m );
  1997. }
  1998. break;
  1999. default:
  2000. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  2001. break;
  2002. }
  2003. //}
  2004. return result;
  2005. };
  2006. function Material () {
  2007. this.id = "";
  2008. this.name = "";
  2009. this.instance_effect = null;
  2010. }
  2011. Material.prototype.parse = function ( element ) {
  2012. this.id = element.getAttribute( 'id' );
  2013. this.name = element.getAttribute( 'name' );
  2014. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2015. if ( element.childNodes[ i ].nodeName === 'instance_effect' ) {
  2016. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  2017. break;
  2018. }
  2019. }
  2020. return this;
  2021. };
  2022. function ColorOrTexture () {
  2023. this.color = new THREE.Color();
  2024. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  2025. this.color.a = 1.0;
  2026. this.texture = null;
  2027. this.texcoord = null;
  2028. this.texOpts = null;
  2029. }
  2030. ColorOrTexture.prototype.isColor = function () {
  2031. return ( this.texture === null );
  2032. };
  2033. ColorOrTexture.prototype.isTexture = function () {
  2034. return ( this.texture != null );
  2035. };
  2036. ColorOrTexture.prototype.parse = function ( element ) {
  2037. if (element.nodeName === 'transparent') {
  2038. this.opaque = element.getAttribute('opaque');
  2039. }
  2040. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2041. var child = element.childNodes[ i ];
  2042. if ( child.nodeType != 1 ) continue;
  2043. switch ( child.nodeName ) {
  2044. case 'color':
  2045. var rgba = _floats( child.textContent );
  2046. this.color = new THREE.Color();
  2047. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2048. this.color.a = rgba[3];
  2049. break;
  2050. case 'texture':
  2051. this.texture = child.getAttribute('texture');
  2052. this.texcoord = child.getAttribute('texcoord');
  2053. // Defaults from:
  2054. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  2055. this.texOpts = {
  2056. offsetU: 0,
  2057. offsetV: 0,
  2058. repeatU: 1,
  2059. repeatV: 1,
  2060. wrapU: 1,
  2061. wrapV: 1
  2062. };
  2063. this.parseTexture( child );
  2064. break;
  2065. default:
  2066. break;
  2067. }
  2068. }
  2069. return this;
  2070. };
  2071. ColorOrTexture.prototype.parseTexture = function ( element ) {
  2072. if ( ! element.childNodes ) return this;
  2073. // This should be supported by Maya, 3dsMax, and MotionBuilder
  2074. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  2075. element = element.childNodes[1];
  2076. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  2077. element = element.childNodes[1];
  2078. }
  2079. }
  2080. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2081. var child = element.childNodes[ i ];
  2082. switch ( child.nodeName ) {
  2083. case 'offsetU':
  2084. case 'offsetV':
  2085. case 'repeatU':
  2086. case 'repeatV':
  2087. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  2088. break;
  2089. case 'wrapU':
  2090. case 'wrapV':
  2091. // some dae have a value of true which becomes NaN via parseInt
  2092. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  2093. this.texOpts[ child.nodeName ] = 1;
  2094. } else {
  2095. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  2096. }
  2097. break;
  2098. default:
  2099. this.texOpts[ child.nodeName ] = child.textContent;
  2100. break;
  2101. }
  2102. }
  2103. return this;
  2104. };
  2105. function Shader ( type, effect ) {
  2106. this.type = type;
  2107. this.effect = effect;
  2108. this.material = null;
  2109. }
  2110. Shader.prototype.parse = function ( element ) {
  2111. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2112. var child = element.childNodes[ i ];
  2113. if ( child.nodeType != 1 ) continue;
  2114. switch ( child.nodeName ) {
  2115. case 'emission':
  2116. case 'diffuse':
  2117. case 'specular':
  2118. case 'transparent':
  2119. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  2120. break;
  2121. case 'bump':
  2122. // If 'bumptype' is 'heightfield', create a 'bump' property
  2123. // Else if 'bumptype' is 'normalmap', create a 'normal' property
  2124. // (Default to 'bump')
  2125. var bumpType = child.getAttribute( 'bumptype' );
  2126. if ( bumpType ) {
  2127. if ( bumpType.toLowerCase() === "heightfield" ) {
  2128. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2129. } else if ( bumpType.toLowerCase() === "normalmap" ) {
  2130. this[ 'normal' ] = ( new ColorOrTexture() ).parse( child );
  2131. } else {
  2132. console.error( "Shader.prototype.parse: Invalid value for attribute 'bumptype' (" + bumpType + ") - valid bumptypes are 'HEIGHTFIELD' and 'NORMALMAP' - defaulting to 'HEIGHTFIELD'" );
  2133. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2134. }
  2135. } else {
  2136. console.warn( "Shader.prototype.parse: Attribute 'bumptype' missing from bump node - defaulting to 'HEIGHTFIELD'" );
  2137. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2138. }
  2139. break;
  2140. case 'shininess':
  2141. case 'reflectivity':
  2142. case 'index_of_refraction':
  2143. case 'transparency':
  2144. var f = child.querySelectorAll('float');
  2145. if ( f.length > 0 )
  2146. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  2147. break;
  2148. default:
  2149. break;
  2150. }
  2151. }
  2152. this.create();
  2153. return this;
  2154. };
  2155. Shader.prototype.create = function() {
  2156. var props = {};
  2157. var transparent = false;
  2158. if (this['transparency'] !== undefined && this['transparent'] !== undefined) {
  2159. // convert transparent color RBG to average value
  2160. var transparentColor = this['transparent'];
  2161. var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency;
  2162. if (transparencyLevel > 0) {
  2163. transparent = true;
  2164. props[ 'transparent' ] = true;
  2165. props[ 'opacity' ] = 1 - transparencyLevel;
  2166. }
  2167. }
  2168. var keys = {
  2169. 'diffuse':'map',
  2170. 'ambient':'lightMap',
  2171. 'specular':'specularMap',
  2172. 'emission':'emissionMap',
  2173. 'bump':'bumpMap',
  2174. 'normal':'normalMap'
  2175. };
  2176. for ( var prop in this ) {
  2177. switch ( prop ) {
  2178. case 'ambient':
  2179. case 'emission':
  2180. case 'diffuse':
  2181. case 'specular':
  2182. case 'bump':
  2183. case 'normal':
  2184. var cot = this[ prop ];
  2185. if ( cot instanceof ColorOrTexture ) {
  2186. if ( cot.isTexture() ) {
  2187. var samplerId = cot.texture;
  2188. var surfaceId = this.effect.sampler[samplerId];
  2189. if ( surfaceId !== undefined && surfaceId.source !== undefined ) {
  2190. var surface = this.effect.surface[surfaceId.source];
  2191. if ( surface !== undefined ) {
  2192. var image = images[ surface.init_from ];
  2193. if ( image ) {
  2194. var url = baseUrl + image.init_from;
  2195. var texture;
  2196. var loader = THREE.Loader.Handlers.get( url );
  2197. if ( loader !== null ) {
  2198. texture = loader.load( url );
  2199. } else {
  2200. texture = new THREE.Texture();
  2201. loadTextureImage( texture, url );
  2202. }
  2203. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2204. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  2205. texture.offset.x = cot.texOpts.offsetU;
  2206. texture.offset.y = cot.texOpts.offsetV;
  2207. texture.repeat.x = cot.texOpts.repeatU;
  2208. texture.repeat.y = cot.texOpts.repeatV;
  2209. props[keys[prop]] = texture;
  2210. // Texture with baked lighting?
  2211. if (prop === 'emission') props['emissive'] = 0xffffff;
  2212. }
  2213. }
  2214. }
  2215. } else if ( prop === 'diffuse' || !transparent ) {
  2216. if ( prop === 'emission' ) {
  2217. props[ 'emissive' ] = cot.color.getHex();
  2218. } else {
  2219. props[ prop ] = cot.color.getHex();
  2220. }
  2221. }
  2222. }
  2223. break;
  2224. case 'shininess':
  2225. props[ prop ] = this[ prop ];
  2226. break;
  2227. case 'reflectivity':
  2228. props[ prop ] = this[ prop ];
  2229. if ( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
  2230. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  2231. break;
  2232. case 'index_of_refraction':
  2233. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  2234. if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
  2235. break;
  2236. case 'transparency':
  2237. // gets figured out up top
  2238. break;
  2239. default:
  2240. break;
  2241. }
  2242. }
  2243. props[ 'shading' ] = preferredShading;
  2244. props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
  2245. switch ( this.type ) {
  2246. case 'constant':
  2247. if (props.emissive != undefined) props.color = props.emissive;
  2248. this.material = new THREE.MeshBasicMaterial( props );
  2249. break;
  2250. case 'phong':
  2251. case 'blinn':
  2252. if (props.diffuse != undefined) props.color = props.diffuse;
  2253. this.material = new THREE.MeshPhongMaterial( props );
  2254. break;
  2255. case 'lambert':
  2256. default:
  2257. if (props.diffuse != undefined) props.color = props.diffuse;
  2258. this.material = new THREE.MeshLambertMaterial( props );
  2259. break;
  2260. }
  2261. return this.material;
  2262. };
  2263. function Surface ( effect ) {
  2264. this.effect = effect;
  2265. this.init_from = null;
  2266. this.format = null;
  2267. }
  2268. Surface.prototype.parse = function ( element ) {
  2269. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2270. var child = element.childNodes[ i ];
  2271. if ( child.nodeType != 1 ) continue;
  2272. switch ( child.nodeName ) {
  2273. case 'init_from':
  2274. this.init_from = child.textContent;
  2275. break;
  2276. case 'format':
  2277. this.format = child.textContent;
  2278. break;
  2279. default:
  2280. console.log( "unhandled Surface prop: " + child.nodeName );
  2281. break;
  2282. }
  2283. }
  2284. return this;
  2285. };
  2286. function Sampler2D ( effect ) {
  2287. this.effect = effect;
  2288. this.source = null;
  2289. this.wrap_s = null;
  2290. this.wrap_t = null;
  2291. this.minfilter = null;
  2292. this.magfilter = null;
  2293. this.mipfilter = null;
  2294. }
  2295. Sampler2D.prototype.parse = function ( element ) {
  2296. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2297. var child = element.childNodes[ i ];
  2298. if ( child.nodeType != 1 ) continue;
  2299. switch ( child.nodeName ) {
  2300. case 'source':
  2301. this.source = child.textContent;
  2302. break;
  2303. case 'minfilter':
  2304. this.minfilter = child.textContent;
  2305. break;
  2306. case 'magfilter':
  2307. this.magfilter = child.textContent;
  2308. break;
  2309. case 'mipfilter':
  2310. this.mipfilter = child.textContent;
  2311. break;
  2312. case 'wrap_s':
  2313. this.wrap_s = child.textContent;
  2314. break;
  2315. case 'wrap_t':
  2316. this.wrap_t = child.textContent;
  2317. break;
  2318. default:
  2319. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  2320. break;
  2321. }
  2322. }
  2323. return this;
  2324. };
  2325. function Effect () {
  2326. this.id = "";
  2327. this.name = "";
  2328. this.shader = null;
  2329. this.surface = {};
  2330. this.sampler = {};
  2331. }
  2332. Effect.prototype.create = function () {
  2333. if ( this.shader === null ) {
  2334. return null;
  2335. }
  2336. };
  2337. Effect.prototype.parse = function ( element ) {
  2338. this.id = element.getAttribute( 'id' );
  2339. this.name = element.getAttribute( 'name' );
  2340. extractDoubleSided( this, element );
  2341. this.shader = null;
  2342. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2343. var child = element.childNodes[ i ];
  2344. if ( child.nodeType != 1 ) continue;
  2345. switch ( child.nodeName ) {
  2346. case 'profile_COMMON':
  2347. this.parseTechnique( this.parseProfileCOMMON( child ) );
  2348. break;
  2349. default:
  2350. break;
  2351. }
  2352. }
  2353. return this;
  2354. };
  2355. Effect.prototype.parseNewparam = function ( element ) {
  2356. var sid = element.getAttribute( 'sid' );
  2357. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2358. var child = element.childNodes[ i ];
  2359. if ( child.nodeType != 1 ) continue;
  2360. switch ( child.nodeName ) {
  2361. case 'surface':
  2362. this.surface[sid] = ( new Surface( this ) ).parse( child );
  2363. break;
  2364. case 'sampler2D':
  2365. this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
  2366. break;
  2367. case 'extra':
  2368. break;
  2369. default:
  2370. console.log( child.nodeName );
  2371. break;
  2372. }
  2373. }
  2374. };
  2375. Effect.prototype.parseProfileCOMMON = function ( element ) {
  2376. var technique;
  2377. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2378. var child = element.childNodes[ i ];
  2379. if ( child.nodeType != 1 ) continue;
  2380. switch ( child.nodeName ) {
  2381. case 'profile_COMMON':
  2382. this.parseProfileCOMMON( child );
  2383. break;
  2384. case 'technique':
  2385. technique = child;
  2386. break;
  2387. case 'newparam':
  2388. this.parseNewparam( child );
  2389. break;
  2390. case 'image':
  2391. var _image = ( new _Image() ).parse( child );
  2392. images[ _image.id ] = _image;
  2393. break;
  2394. case 'extra':
  2395. break;
  2396. default:
  2397. console.log( child.nodeName );
  2398. break;
  2399. }
  2400. }
  2401. return technique;
  2402. };
  2403. Effect.prototype.parseTechnique = function ( element ) {
  2404. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2405. var child = element.childNodes[i];
  2406. if ( child.nodeType != 1 ) continue;
  2407. switch ( child.nodeName ) {
  2408. case 'constant':
  2409. case 'lambert':
  2410. case 'blinn':
  2411. case 'phong':
  2412. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  2413. break;
  2414. case 'extra':
  2415. this.parseExtra(child);
  2416. break;
  2417. default:
  2418. break;
  2419. }
  2420. }
  2421. };
  2422. Effect.prototype.parseExtra = function ( element ) {
  2423. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2424. var child = element.childNodes[i];
  2425. if ( child.nodeType != 1 ) continue;
  2426. switch ( child.nodeName ) {
  2427. case 'technique':
  2428. this.parseExtraTechnique( child );
  2429. break;
  2430. default:
  2431. break;
  2432. }
  2433. }
  2434. };
  2435. Effect.prototype.parseExtraTechnique = function ( element ) {
  2436. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2437. var child = element.childNodes[i];
  2438. if ( child.nodeType != 1 ) continue;
  2439. switch ( child.nodeName ) {
  2440. case 'bump':
  2441. this.shader.parse( element );
  2442. break;
  2443. default:
  2444. break;
  2445. }
  2446. }
  2447. };
  2448. function InstanceEffect () {
  2449. this.url = "";
  2450. }
  2451. InstanceEffect.prototype.parse = function ( element ) {
  2452. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  2453. return this;
  2454. };
  2455. function Animation() {
  2456. this.id = "";
  2457. this.name = "";
  2458. this.source = {};
  2459. this.sampler = [];
  2460. this.channel = [];
  2461. }
  2462. Animation.prototype.parse = function ( element ) {
  2463. this.id = element.getAttribute( 'id' );
  2464. this.name = element.getAttribute( 'name' );
  2465. this.source = {};
  2466. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2467. var child = element.childNodes[ i ];
  2468. if ( child.nodeType != 1 ) continue;
  2469. switch ( child.nodeName ) {
  2470. case 'animation':
  2471. var anim = ( new Animation() ).parse( child );
  2472. for ( var src in anim.source ) {
  2473. this.source[ src ] = anim.source[ src ];
  2474. }
  2475. for ( var j = 0; j < anim.channel.length; j ++ ) {
  2476. this.channel.push( anim.channel[ j ] );
  2477. this.sampler.push( anim.sampler[ j ] );
  2478. }
  2479. break;
  2480. case 'source':
  2481. var src = ( new Source() ).parse( child );
  2482. this.source[ src.id ] = src;
  2483. break;
  2484. case 'sampler':
  2485. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  2486. break;
  2487. case 'channel':
  2488. this.channel.push( ( new Channel( this ) ).parse( child ) );
  2489. break;
  2490. default:
  2491. break;
  2492. }
  2493. }
  2494. return this;
  2495. };
  2496. function Channel( animation ) {
  2497. this.animation = animation;
  2498. this.source = "";
  2499. this.target = "";
  2500. this.fullSid = null;
  2501. this.sid = null;
  2502. this.dotSyntax = null;
  2503. this.arrSyntax = null;
  2504. this.arrIndices = null;
  2505. this.member = null;
  2506. }
  2507. Channel.prototype.parse = function ( element ) {
  2508. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  2509. this.target = element.getAttribute( 'target' );
  2510. var parts = this.target.split( '/' );
  2511. var id = parts.shift();
  2512. var sid = parts.shift();
  2513. var dotSyntax = ( sid.indexOf(".") >= 0 );
  2514. var arrSyntax = ( sid.indexOf("(") >= 0 );
  2515. if ( dotSyntax ) {
  2516. parts = sid.split(".");
  2517. this.sid = parts.shift();
  2518. this.member = parts.shift();
  2519. } else if ( arrSyntax ) {
  2520. var arrIndices = sid.split("(");
  2521. this.sid = arrIndices.shift();
  2522. for (var j = 0; j < arrIndices.length; j ++ ) {
  2523. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  2524. }
  2525. this.arrIndices = arrIndices;
  2526. } else {
  2527. this.sid = sid;
  2528. }
  2529. this.fullSid = sid;
  2530. this.dotSyntax = dotSyntax;
  2531. this.arrSyntax = arrSyntax;
  2532. return this;
  2533. };
  2534. function Sampler ( animation ) {
  2535. this.id = "";
  2536. this.animation = animation;
  2537. this.inputs = [];
  2538. this.input = null;
  2539. this.output = null;
  2540. this.strideOut = null;
  2541. this.interpolation = null;
  2542. this.startTime = null;
  2543. this.endTime = null;
  2544. this.duration = 0;
  2545. }
  2546. Sampler.prototype.parse = function ( element ) {
  2547. this.id = element.getAttribute( 'id' );
  2548. this.inputs = [];
  2549. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2550. var child = element.childNodes[ i ];
  2551. if ( child.nodeType != 1 ) continue;
  2552. switch ( child.nodeName ) {
  2553. case 'input':
  2554. this.inputs.push( (new Input()).parse( child ) );
  2555. break;
  2556. default:
  2557. break;
  2558. }
  2559. }
  2560. return this;
  2561. };
  2562. Sampler.prototype.create = function () {
  2563. for ( var i = 0; i < this.inputs.length; i ++ ) {
  2564. var input = this.inputs[ i ];
  2565. var source = this.animation.source[ input.source ];
  2566. switch ( input.semantic ) {
  2567. case 'INPUT':
  2568. this.input = source.read();
  2569. break;
  2570. case 'OUTPUT':
  2571. this.output = source.read();
  2572. this.strideOut = source.accessor.stride;
  2573. break;
  2574. case 'INTERPOLATION':
  2575. this.interpolation = source.read();
  2576. break;
  2577. case 'IN_TANGENT':
  2578. break;
  2579. case 'OUT_TANGENT':
  2580. break;
  2581. default:
  2582. console.log(input.semantic);
  2583. break;
  2584. }
  2585. }
  2586. this.startTime = 0;
  2587. this.endTime = 0;
  2588. this.duration = 0;
  2589. if ( this.input.length ) {
  2590. this.startTime = 100000000;
  2591. this.endTime = -100000000;
  2592. for ( var i = 0; i < this.input.length; i ++ ) {
  2593. this.startTime = Math.min( this.startTime, this.input[ i ] );
  2594. this.endTime = Math.max( this.endTime, this.input[ i ] );
  2595. }
  2596. this.duration = this.endTime - this.startTime;
  2597. }
  2598. };
  2599. Sampler.prototype.getData = function ( type, ndx, member ) {
  2600. var data;
  2601. if ( type === 'matrix' && this.strideOut === 16 ) {
  2602. data = this.output[ ndx ];
  2603. } else if ( this.strideOut > 1 ) {
  2604. data = [];
  2605. ndx *= this.strideOut;
  2606. for ( var i = 0; i < this.strideOut; ++ i ) {
  2607. data[ i ] = this.output[ ndx + i ];
  2608. }
  2609. if ( this.strideOut === 3 ) {
  2610. switch ( type ) {
  2611. case 'rotate':
  2612. case 'translate':
  2613. fixCoords( data, -1 );
  2614. break;
  2615. case 'scale':
  2616. fixCoords( data, 1 );
  2617. break;
  2618. }
  2619. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  2620. fixCoords( data, -1 );
  2621. }
  2622. } else {
  2623. data = this.output[ ndx ];
  2624. if ( member && type === 'translate' ) {
  2625. data = getConvertedTranslation( member, data );
  2626. }
  2627. }
  2628. return data;
  2629. };
  2630. function Key ( time ) {
  2631. this.targets = [];
  2632. this.time = time;
  2633. }
  2634. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  2635. this.targets.push( {
  2636. sid: fullSid,
  2637. member: member,
  2638. transform: transform,
  2639. data: data
  2640. } );
  2641. };
  2642. Key.prototype.apply = function ( opt_sid ) {
  2643. for ( var i = 0; i < this.targets.length; ++ i ) {
  2644. var target = this.targets[ i ];
  2645. if ( !opt_sid || target.sid === opt_sid ) {
  2646. target.transform.update( target.data, target.member );
  2647. }
  2648. }
  2649. };
  2650. Key.prototype.getTarget = function ( fullSid ) {
  2651. for ( var i = 0; i < this.targets.length; ++ i ) {
  2652. if ( this.targets[ i ].sid === fullSid ) {
  2653. return this.targets[ i ];
  2654. }
  2655. }
  2656. return null;
  2657. };
  2658. Key.prototype.hasTarget = function ( fullSid ) {
  2659. for ( var i = 0; i < this.targets.length; ++ i ) {
  2660. if ( this.targets[ i ].sid === fullSid ) {
  2661. return true;
  2662. }
  2663. }
  2664. return false;
  2665. };
  2666. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  2667. Key.prototype.interpolate = function ( nextKey, time ) {
  2668. for ( var i = 0, l = this.targets.length; i < l; i ++ ) {
  2669. var target = this.targets[ i ],
  2670. nextTarget = nextKey.getTarget( target.sid ),
  2671. data;
  2672. if ( target.transform.type !== 'matrix' && nextTarget ) {
  2673. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  2674. nextData = nextTarget.data,
  2675. prevData = target.data;
  2676. if ( scale < 0 ) scale = 0;
  2677. if ( scale > 1 ) scale = 1;
  2678. if ( prevData.length ) {
  2679. data = [];
  2680. for ( var j = 0; j < prevData.length; ++ j ) {
  2681. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  2682. }
  2683. } else {
  2684. data = prevData + ( nextData - prevData ) * scale;
  2685. }
  2686. } else {
  2687. data = target.data;
  2688. }
  2689. target.transform.update( data, target.member );
  2690. }
  2691. };
  2692. // Camera
  2693. function Camera() {
  2694. this.id = "";
  2695. this.name = "";
  2696. this.technique = "";
  2697. }
  2698. Camera.prototype.parse = function ( element ) {
  2699. this.id = element.getAttribute( 'id' );
  2700. this.name = element.getAttribute( 'name' );
  2701. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2702. var child = element.childNodes[ i ];
  2703. if ( child.nodeType != 1 ) continue;
  2704. switch ( child.nodeName ) {
  2705. case 'optics':
  2706. this.parseOptics( child );
  2707. break;
  2708. default:
  2709. break;
  2710. }
  2711. }
  2712. return this;
  2713. };
  2714. Camera.prototype.parseOptics = function ( element ) {
  2715. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2716. if ( element.childNodes[ i ].nodeName === 'technique_common' ) {
  2717. var technique = element.childNodes[ i ];
  2718. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  2719. this.technique = technique.childNodes[ j ].nodeName;
  2720. if ( this.technique === 'perspective' ) {
  2721. var perspective = technique.childNodes[ j ];
  2722. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  2723. var param = perspective.childNodes[ k ];
  2724. switch ( param.nodeName ) {
  2725. case 'yfov':
  2726. this.yfov = param.textContent;
  2727. break;
  2728. case 'xfov':
  2729. this.xfov = param.textContent;
  2730. break;
  2731. case 'znear':
  2732. this.znear = param.textContent;
  2733. break;
  2734. case 'zfar':
  2735. this.zfar = param.textContent;
  2736. break;
  2737. case 'aspect_ratio':
  2738. this.aspect_ratio = param.textContent;
  2739. break;
  2740. }
  2741. }
  2742. } else if ( this.technique === 'orthographic' ) {
  2743. var orthographic = technique.childNodes[ j ];
  2744. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  2745. var param = orthographic.childNodes[ k ];
  2746. switch ( param.nodeName ) {
  2747. case 'xmag':
  2748. this.xmag = param.textContent;
  2749. break;
  2750. case 'ymag':
  2751. this.ymag = param.textContent;
  2752. break;
  2753. case 'znear':
  2754. this.znear = param.textContent;
  2755. break;
  2756. case 'zfar':
  2757. this.zfar = param.textContent;
  2758. break;
  2759. case 'aspect_ratio':
  2760. this.aspect_ratio = param.textContent;
  2761. break;
  2762. }
  2763. }
  2764. }
  2765. }
  2766. }
  2767. }
  2768. return this;
  2769. };
  2770. function InstanceCamera() {
  2771. this.url = "";
  2772. }
  2773. InstanceCamera.prototype.parse = function ( element ) {
  2774. this.url = element.getAttribute('url').replace(/^#/, '');
  2775. return this;
  2776. };
  2777. // Light
  2778. function Light() {
  2779. this.id = "";
  2780. this.name = "";
  2781. this.technique = "";
  2782. }
  2783. Light.prototype.parse = function ( element ) {
  2784. this.id = element.getAttribute( 'id' );
  2785. this.name = element.getAttribute( 'name' );
  2786. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2787. var child = element.childNodes[ i ];
  2788. if ( child.nodeType != 1 ) continue;
  2789. switch ( child.nodeName ) {
  2790. case 'technique_common':
  2791. this.parseCommon( child );
  2792. break;
  2793. case 'technique':
  2794. this.parseTechnique( child );
  2795. break;
  2796. default:
  2797. break;
  2798. }
  2799. }
  2800. return this;
  2801. };
  2802. Light.prototype.parseCommon = function ( element ) {
  2803. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2804. switch ( element.childNodes[ i ].nodeName ) {
  2805. case 'directional':
  2806. case 'point':
  2807. case 'spot':
  2808. case 'ambient':
  2809. this.technique = element.childNodes[ i ].nodeName;
  2810. var light = element.childNodes[ i ];
  2811. for ( var j = 0; j < light.childNodes.length; j ++ ) {
  2812. var child = light.childNodes[j];
  2813. switch ( child.nodeName ) {
  2814. case 'color':
  2815. var rgba = _floats( child.textContent );
  2816. this.color = new THREE.Color(0);
  2817. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2818. this.color.a = rgba[3];
  2819. break;
  2820. case 'falloff_angle':
  2821. this.falloff_angle = parseFloat( child.textContent );
  2822. break;
  2823. case 'quadratic_attenuation':
  2824. var f = parseFloat( child.textContent );
  2825. this.distance = f ? Math.sqrt( 1 / f ) : 0;
  2826. }
  2827. }
  2828. }
  2829. }
  2830. return this;
  2831. };
  2832. Light.prototype.parseTechnique = function ( element ) {
  2833. this.profile = element.getAttribute( 'profile' );
  2834. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2835. var child = element.childNodes[ i ];
  2836. switch ( child.nodeName ) {
  2837. case 'intensity':
  2838. this.intensity = parseFloat(child.textContent);
  2839. break;
  2840. }
  2841. }
  2842. return this;
  2843. };
  2844. function InstanceLight() {
  2845. this.url = "";
  2846. }
  2847. InstanceLight.prototype.parse = function ( element ) {
  2848. this.url = element.getAttribute('url').replace(/^#/, '');
  2849. return this;
  2850. };
  2851. function KinematicsModel( ) {
  2852. this.id = '';
  2853. this.name = '';
  2854. this.joints = [];
  2855. this.links = [];
  2856. }
  2857. KinematicsModel.prototype.parse = function( element ) {
  2858. this.id = element.getAttribute('id');
  2859. this.name = element.getAttribute('name');
  2860. this.joints = [];
  2861. this.links = [];
  2862. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2863. var child = element.childNodes[ i ];
  2864. if ( child.nodeType != 1 ) continue;
  2865. switch ( child.nodeName ) {
  2866. case 'technique_common':
  2867. this.parseCommon(child);
  2868. break;
  2869. default:
  2870. break;
  2871. }
  2872. }
  2873. return this;
  2874. };
  2875. KinematicsModel.prototype.parseCommon = function( element ) {
  2876. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2877. var child = element.childNodes[ i ];
  2878. if ( child.nodeType != 1 ) continue;
  2879. switch ( element.childNodes[ i ].nodeName ) {
  2880. case 'joint':
  2881. this.joints.push( (new Joint()).parse(child) );
  2882. break;
  2883. case 'link':
  2884. this.links.push( (new Link()).parse(child) );
  2885. break;
  2886. default:
  2887. break;
  2888. }
  2889. }
  2890. return this;
  2891. };
  2892. function Joint( ) {
  2893. this.sid = '';
  2894. this.name = '';
  2895. this.axis = new THREE.Vector3();
  2896. this.limits = {
  2897. min: 0,
  2898. max: 0
  2899. };
  2900. this.type = '';
  2901. this.static = false;
  2902. this.zeroPosition = 0.0;
  2903. this.middlePosition = 0.0;
  2904. }
  2905. Joint.prototype.parse = function( element ) {
  2906. this.sid = element.getAttribute('sid');
  2907. this.name = element.getAttribute('name');
  2908. this.axis = new THREE.Vector3();
  2909. this.limits = {
  2910. min: 0,
  2911. max: 0
  2912. };
  2913. this.type = '';
  2914. this.static = false;
  2915. this.zeroPosition = 0.0;
  2916. this.middlePosition = 0.0;
  2917. var axisElement = element.querySelector('axis');
  2918. var _axis = _floats(axisElement.textContent);
  2919. this.axis = getConvertedVec3(_axis, 0);
  2920. var min = element.querySelector('limits min') ? parseFloat(element.querySelector('limits min').textContent) : -360;
  2921. var max = element.querySelector('limits max') ? parseFloat(element.querySelector('limits max').textContent) : 360;
  2922. this.limits = {
  2923. min: min,
  2924. max: max
  2925. };
  2926. var jointTypes = [ 'prismatic', 'revolute' ];
  2927. for (var i = 0; i < jointTypes.length; i ++ ) {
  2928. var type = jointTypes[ i ];
  2929. var jointElement = element.querySelector(type);
  2930. if ( jointElement ) {
  2931. this.type = type;
  2932. }
  2933. }
  2934. // if the min is equal to or somehow greater than the max, consider the joint static
  2935. if ( this.limits.min >= this.limits.max ) {
  2936. this.static = true;
  2937. }
  2938. this.middlePosition = (this.limits.min + this.limits.max) / 2.0;
  2939. return this;
  2940. };
  2941. function Link( ) {
  2942. this.sid = '';
  2943. this.name = '';
  2944. this.transforms = [];
  2945. this.attachments = [];
  2946. }
  2947. Link.prototype.parse = function( element ) {
  2948. this.sid = element.getAttribute('sid');
  2949. this.name = element.getAttribute('name');
  2950. this.transforms = [];
  2951. this.attachments = [];
  2952. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2953. var child = element.childNodes[ i ];
  2954. if ( child.nodeType != 1 ) continue;
  2955. switch ( child.nodeName ) {
  2956. case 'attachment_full':
  2957. this.attachments.push( (new Attachment()).parse(child) );
  2958. break;
  2959. case 'rotate':
  2960. case 'translate':
  2961. case 'matrix':
  2962. this.transforms.push( (new Transform()).parse(child) );
  2963. break;
  2964. default:
  2965. break;
  2966. }
  2967. }
  2968. return this;
  2969. };
  2970. function Attachment( ) {
  2971. this.joint = '';
  2972. this.transforms = [];
  2973. this.links = [];
  2974. }
  2975. Attachment.prototype.parse = function( element ) {
  2976. this.joint = element.getAttribute('joint').split('/').pop();
  2977. this.links = [];
  2978. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2979. var child = element.childNodes[ i ];
  2980. if ( child.nodeType != 1 ) continue;
  2981. switch ( child.nodeName ) {
  2982. case 'link':
  2983. this.links.push( (new Link()).parse(child) );
  2984. break;
  2985. case 'rotate':
  2986. case 'translate':
  2987. case 'matrix':
  2988. this.transforms.push( (new Transform()).parse(child) );
  2989. break;
  2990. default:
  2991. break;
  2992. }
  2993. }
  2994. return this;
  2995. };
  2996. function _source( element ) {
  2997. var id = element.getAttribute( 'id' );
  2998. if ( sources[ id ] != undefined ) {
  2999. return sources[ id ];
  3000. }
  3001. sources[ id ] = ( new Source(id )).parse( element );
  3002. return sources[ id ];
  3003. }
  3004. function _nsResolver( nsPrefix ) {
  3005. if ( nsPrefix === "dae" ) {
  3006. return "http://www.collada.org/2005/11/COLLADASchema";
  3007. }
  3008. return null;
  3009. }
  3010. function _bools( str ) {
  3011. var raw = _strings( str );
  3012. var data = [];
  3013. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3014. data.push( (raw[i] === 'true' || raw[i] === '1') ? true : false );
  3015. }
  3016. return data;
  3017. }
  3018. function _floats( str ) {
  3019. var raw = _strings(str);
  3020. var data = [];
  3021. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3022. data.push( parseFloat( raw[ i ] ) );
  3023. }
  3024. return data;
  3025. }
  3026. function _ints( str ) {
  3027. var raw = _strings( str );
  3028. var data = [];
  3029. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3030. data.push( parseInt( raw[ i ], 10 ) );
  3031. }
  3032. return data;
  3033. }
  3034. function _strings( str ) {
  3035. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  3036. }
  3037. function _trimString( str ) {
  3038. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  3039. }
  3040. function _attr_as_float( element, name, defaultValue ) {
  3041. if ( element.hasAttribute( name ) ) {
  3042. return parseFloat( element.getAttribute( name ) );
  3043. } else {
  3044. return defaultValue;
  3045. }
  3046. }
  3047. function _attr_as_int( element, name, defaultValue ) {
  3048. if ( element.hasAttribute( name ) ) {
  3049. return parseInt( element.getAttribute( name ), 10) ;
  3050. } else {
  3051. return defaultValue;
  3052. }
  3053. }
  3054. function _attr_as_string( element, name, defaultValue ) {
  3055. if ( element.hasAttribute( name ) ) {
  3056. return element.getAttribute( name );
  3057. } else {
  3058. return defaultValue;
  3059. }
  3060. }
  3061. function _format_float( f, num ) {
  3062. if ( f === undefined ) {
  3063. var s = '0.';
  3064. while ( s.length < num + 2 ) {
  3065. s += '0';
  3066. }
  3067. return s;
  3068. }
  3069. num = num || 2;
  3070. var parts = f.toString().split( '.' );
  3071. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  3072. while ( parts[ 1 ].length < num ) {
  3073. parts[ 1 ] += '0';
  3074. }
  3075. return parts.join( '.' );
  3076. }
  3077. function loadTextureImage ( texture, url ) {
  3078. var loader = new THREE.ImageLoader();
  3079. loader.load( url, function ( image ) {
  3080. texture.image = image;
  3081. texture.needsUpdate = true;
  3082. } );
  3083. }
  3084. function extractDoubleSided( obj, element ) {
  3085. obj.doubleSided = false;
  3086. var node = element.querySelectorAll('extra double_sided')[0];
  3087. if ( node ) {
  3088. if ( node && parseInt( node.textContent, 10 ) === 1 ) {
  3089. obj.doubleSided = true;
  3090. }
  3091. }
  3092. }
  3093. // Up axis conversion
  3094. function setUpConversion() {
  3095. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3096. upConversion = null;
  3097. } else {
  3098. switch ( colladaUp ) {
  3099. case 'X':
  3100. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  3101. break;
  3102. case 'Y':
  3103. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  3104. break;
  3105. case 'Z':
  3106. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  3107. break;
  3108. }
  3109. }
  3110. }
  3111. function fixCoords( data, sign ) {
  3112. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3113. return;
  3114. }
  3115. switch ( upConversion ) {
  3116. case 'XtoY':
  3117. var tmp = data[ 0 ];
  3118. data[ 0 ] = sign * data[ 1 ];
  3119. data[ 1 ] = tmp;
  3120. break;
  3121. case 'XtoZ':
  3122. var tmp = data[ 2 ];
  3123. data[ 2 ] = data[ 1 ];
  3124. data[ 1 ] = data[ 0 ];
  3125. data[ 0 ] = tmp;
  3126. break;
  3127. case 'YtoX':
  3128. var tmp = data[ 0 ];
  3129. data[ 0 ] = data[ 1 ];
  3130. data[ 1 ] = sign * tmp;
  3131. break;
  3132. case 'YtoZ':
  3133. var tmp = data[ 1 ];
  3134. data[ 1 ] = sign * data[ 2 ];
  3135. data[ 2 ] = tmp;
  3136. break;
  3137. case 'ZtoX':
  3138. var tmp = data[ 0 ];
  3139. data[ 0 ] = data[ 1 ];
  3140. data[ 1 ] = data[ 2 ];
  3141. data[ 2 ] = tmp;
  3142. break;
  3143. case 'ZtoY':
  3144. var tmp = data[ 1 ];
  3145. data[ 1 ] = data[ 2 ];
  3146. data[ 2 ] = sign * tmp;
  3147. break;
  3148. }
  3149. }
  3150. function getConvertedTranslation( axis, data ) {
  3151. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3152. return data;
  3153. }
  3154. switch ( axis ) {
  3155. case 'X':
  3156. data = upConversion === 'XtoY' ? data * -1 : data;
  3157. break;
  3158. case 'Y':
  3159. data = upConversion === 'YtoZ' || upConversion === 'YtoX' ? data * -1 : data;
  3160. break;
  3161. case 'Z':
  3162. data = upConversion === 'ZtoY' ? data * -1 : data ;
  3163. break;
  3164. default:
  3165. break;
  3166. }
  3167. return data;
  3168. }
  3169. function getConvertedVec3( data, offset ) {
  3170. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  3171. fixCoords( arr, -1 );
  3172. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  3173. }
  3174. function getConvertedMat4( data ) {
  3175. if ( options.convertUpAxis ) {
  3176. // First fix rotation and scale
  3177. // Columns first
  3178. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  3179. fixCoords( arr, -1 );
  3180. data[ 0 ] = arr[ 0 ];
  3181. data[ 4 ] = arr[ 1 ];
  3182. data[ 8 ] = arr[ 2 ];
  3183. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  3184. fixCoords( arr, -1 );
  3185. data[ 1 ] = arr[ 0 ];
  3186. data[ 5 ] = arr[ 1 ];
  3187. data[ 9 ] = arr[ 2 ];
  3188. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  3189. fixCoords( arr, -1 );
  3190. data[ 2 ] = arr[ 0 ];
  3191. data[ 6 ] = arr[ 1 ];
  3192. data[ 10 ] = arr[ 2 ];
  3193. // Rows second
  3194. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  3195. fixCoords( arr, -1 );
  3196. data[ 0 ] = arr[ 0 ];
  3197. data[ 1 ] = arr[ 1 ];
  3198. data[ 2 ] = arr[ 2 ];
  3199. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  3200. fixCoords( arr, -1 );
  3201. data[ 4 ] = arr[ 0 ];
  3202. data[ 5 ] = arr[ 1 ];
  3203. data[ 6 ] = arr[ 2 ];
  3204. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  3205. fixCoords( arr, -1 );
  3206. data[ 8 ] = arr[ 0 ];
  3207. data[ 9 ] = arr[ 1 ];
  3208. data[ 10 ] = arr[ 2 ];
  3209. // Now fix translation
  3210. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  3211. fixCoords( arr, -1 );
  3212. data[ 3 ] = arr[ 0 ];
  3213. data[ 7 ] = arr[ 1 ];
  3214. data[ 11 ] = arr[ 2 ];
  3215. }
  3216. return new THREE.Matrix4().set(
  3217. data[0], data[1], data[2], data[3],
  3218. data[4], data[5], data[6], data[7],
  3219. data[8], data[9], data[10], data[11],
  3220. data[12], data[13], data[14], data[15]
  3221. );
  3222. }
  3223. function getConvertedIndex( index ) {
  3224. if ( index > -1 && index < 3 ) {
  3225. var members = [ 'X', 'Y', 'Z' ],
  3226. indices = { X: 0, Y: 1, Z: 2 };
  3227. index = getConvertedMember( members[ index ] );
  3228. index = indices[ index ];
  3229. }
  3230. return index;
  3231. }
  3232. function getConvertedMember( member ) {
  3233. if ( options.convertUpAxis ) {
  3234. switch ( member ) {
  3235. case 'X':
  3236. switch ( upConversion ) {
  3237. case 'XtoY':
  3238. case 'XtoZ':
  3239. case 'YtoX':
  3240. member = 'Y';
  3241. break;
  3242. case 'ZtoX':
  3243. member = 'Z';
  3244. break;
  3245. }
  3246. break;
  3247. case 'Y':
  3248. switch ( upConversion ) {
  3249. case 'XtoY':
  3250. case 'YtoX':
  3251. case 'ZtoX':
  3252. member = 'X';
  3253. break;
  3254. case 'XtoZ':
  3255. case 'YtoZ':
  3256. case 'ZtoY':
  3257. member = 'Z';
  3258. break;
  3259. }
  3260. break;
  3261. case 'Z':
  3262. switch ( upConversion ) {
  3263. case 'XtoZ':
  3264. member = 'X';
  3265. break;
  3266. case 'YtoZ':
  3267. case 'ZtoX':
  3268. case 'ZtoY':
  3269. member = 'Y';
  3270. break;
  3271. }
  3272. break;
  3273. }
  3274. }
  3275. return member;
  3276. }
  3277. return {
  3278. load: load,
  3279. parse: parse,
  3280. setPreferredShading: setPreferredShading,
  3281. applySkin: applySkin,
  3282. geometries : geometries,
  3283. options: options
  3284. };
  3285. };