ColladaLoader.js 98 KB

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