ColladaLoader.js 98 KB

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