ColladaLoader.js 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548
  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. var skinController = controllers[ instanceCtrl.url ];
  426. frame = frame !== undefined ? frame : 40;
  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. var member;
  1299. if ( dotSyntax ) {
  1300. parts = sid.split(".");
  1301. sid = parts.shift();
  1302. member = parts.shift();
  1303. } else if ( arrSyntax ) {
  1304. arrIndices = sid.split("(");
  1305. sid = arrIndices.shift();
  1306. for ( var j = 0; j < arrIndices.length; j ++ ) {
  1307. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  1308. }
  1309. }
  1310. if ( sid === transformSid ) {
  1311. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  1312. return channel;
  1313. }
  1314. }
  1315. return null;
  1316. };
  1317. Node.prototype.getChildById = function ( id, recursive ) {
  1318. if ( this.id === id ) {
  1319. return this;
  1320. }
  1321. if ( recursive ) {
  1322. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1323. var n = this.nodes[ i ].getChildById( id, recursive );
  1324. if ( n ) {
  1325. return n;
  1326. }
  1327. }
  1328. }
  1329. return null;
  1330. };
  1331. Node.prototype.getChildBySid = function ( sid, recursive ) {
  1332. if ( this.sid === sid ) {
  1333. return this;
  1334. }
  1335. if ( recursive ) {
  1336. for ( var i = 0; i < this.nodes.length; i ++ ) {
  1337. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  1338. if ( n ) {
  1339. return n;
  1340. }
  1341. }
  1342. }
  1343. return null;
  1344. };
  1345. Node.prototype.getTransformBySid = function ( sid ) {
  1346. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1347. if ( this.transforms[ i ].sid === sid ) return this.transforms[ i ];
  1348. }
  1349. return null;
  1350. };
  1351. Node.prototype.parse = function( element ) {
  1352. var url;
  1353. this.id = element.getAttribute('id');
  1354. this.sid = element.getAttribute('sid');
  1355. this.name = element.getAttribute('name');
  1356. this.type = element.getAttribute('type');
  1357. this.layer = element.getAttribute('layer');
  1358. this.type = this.type === 'JOINT' ? this.type : 'NODE';
  1359. this.nodes = [];
  1360. this.transforms = [];
  1361. this.geometries = [];
  1362. this.cameras = [];
  1363. this.lights = [];
  1364. this.controllers = [];
  1365. this.matrix = new THREE.Matrix4();
  1366. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1367. var child = element.childNodes[ i ];
  1368. if ( child.nodeType != 1 ) continue;
  1369. switch ( child.nodeName ) {
  1370. case 'node':
  1371. this.nodes.push( ( new Node() ).parse( child ) );
  1372. break;
  1373. case 'instance_camera':
  1374. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  1375. break;
  1376. case 'instance_controller':
  1377. this.controllers.push( ( new InstanceController() ).parse( child ) );
  1378. break;
  1379. case 'instance_geometry':
  1380. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  1381. break;
  1382. case 'instance_light':
  1383. this.lights.push( ( new InstanceLight() ).parse( child ) );
  1384. break;
  1385. case 'instance_node':
  1386. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  1387. var iNode = getLibraryNode( url );
  1388. if ( iNode ) {
  1389. this.nodes.push( ( new Node() ).parse( iNode )) ;
  1390. }
  1391. break;
  1392. case 'rotate':
  1393. case 'translate':
  1394. case 'scale':
  1395. case 'matrix':
  1396. case 'lookat':
  1397. case 'skew':
  1398. this.transforms.push( ( new Transform() ).parse( child ) );
  1399. break;
  1400. case 'extra':
  1401. break;
  1402. default:
  1403. console.log( child.nodeName );
  1404. break;
  1405. }
  1406. }
  1407. this.channels = getChannelsForNode( this );
  1408. bakeAnimations( this );
  1409. this.updateMatrix();
  1410. return this;
  1411. };
  1412. Node.prototype.updateMatrix = function () {
  1413. this.matrix.identity();
  1414. for ( var i = 0; i < this.transforms.length; i ++ ) {
  1415. this.transforms[ i ].apply( this.matrix );
  1416. }
  1417. };
  1418. function Transform () {
  1419. this.sid = "";
  1420. this.type = "";
  1421. this.data = [];
  1422. this.obj = null;
  1423. }
  1424. Transform.prototype.parse = function ( element ) {
  1425. this.sid = element.getAttribute( 'sid' );
  1426. this.type = element.nodeName;
  1427. this.data = _floats( element.textContent );
  1428. this.convert();
  1429. return this;
  1430. };
  1431. Transform.prototype.convert = function () {
  1432. switch ( this.type ) {
  1433. case 'matrix':
  1434. this.obj = getConvertedMat4( this.data );
  1435. break;
  1436. case 'rotate':
  1437. this.angle = THREE.Math.degToRad( this.data[3] );
  1438. case 'translate':
  1439. fixCoords( this.data, -1 );
  1440. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1441. break;
  1442. case 'scale':
  1443. fixCoords( this.data, 1 );
  1444. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  1445. break;
  1446. default:
  1447. console.log( 'Can not convert Transform of type ' + this.type );
  1448. break;
  1449. }
  1450. };
  1451. Transform.prototype.apply = function () {
  1452. var m1 = new THREE.Matrix4();
  1453. return function ( matrix ) {
  1454. switch ( this.type ) {
  1455. case 'matrix':
  1456. matrix.multiply( this.obj );
  1457. break;
  1458. case 'translate':
  1459. matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
  1460. break;
  1461. case 'rotate':
  1462. matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
  1463. break;
  1464. case 'scale':
  1465. matrix.scale( this.obj );
  1466. break;
  1467. }
  1468. };
  1469. }();
  1470. Transform.prototype.update = function ( data, member ) {
  1471. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  1472. switch ( this.type ) {
  1473. case 'matrix':
  1474. if ( ! member ) {
  1475. this.obj.copy( data );
  1476. } else if ( member.length === 1 ) {
  1477. switch ( member[ 0 ] ) {
  1478. case 0:
  1479. this.obj.n11 = data[ 0 ];
  1480. this.obj.n21 = data[ 1 ];
  1481. this.obj.n31 = data[ 2 ];
  1482. this.obj.n41 = data[ 3 ];
  1483. break;
  1484. case 1:
  1485. this.obj.n12 = data[ 0 ];
  1486. this.obj.n22 = data[ 1 ];
  1487. this.obj.n32 = data[ 2 ];
  1488. this.obj.n42 = data[ 3 ];
  1489. break;
  1490. case 2:
  1491. this.obj.n13 = data[ 0 ];
  1492. this.obj.n23 = data[ 1 ];
  1493. this.obj.n33 = data[ 2 ];
  1494. this.obj.n43 = data[ 3 ];
  1495. break;
  1496. case 3:
  1497. this.obj.n14 = data[ 0 ];
  1498. this.obj.n24 = data[ 1 ];
  1499. this.obj.n34 = data[ 2 ];
  1500. this.obj.n44 = data[ 3 ];
  1501. break;
  1502. }
  1503. } else if ( member.length === 2 ) {
  1504. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  1505. this.obj[ propName ] = data;
  1506. } else {
  1507. console.log('Incorrect addressing of matrix in transform.');
  1508. }
  1509. break;
  1510. case 'translate':
  1511. case 'scale':
  1512. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1513. member = members[ member[ 0 ] ];
  1514. }
  1515. switch ( member ) {
  1516. case 'X':
  1517. this.obj.x = data;
  1518. break;
  1519. case 'Y':
  1520. this.obj.y = data;
  1521. break;
  1522. case 'Z':
  1523. this.obj.z = data;
  1524. break;
  1525. default:
  1526. this.obj.x = data[ 0 ];
  1527. this.obj.y = data[ 1 ];
  1528. this.obj.z = data[ 2 ];
  1529. break;
  1530. }
  1531. break;
  1532. case 'rotate':
  1533. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  1534. member = members[ member[ 0 ] ];
  1535. }
  1536. switch ( member ) {
  1537. case 'X':
  1538. this.obj.x = data;
  1539. break;
  1540. case 'Y':
  1541. this.obj.y = data;
  1542. break;
  1543. case 'Z':
  1544. this.obj.z = data;
  1545. break;
  1546. case 'ANGLE':
  1547. this.angle = THREE.Math.degToRad( data );
  1548. break;
  1549. default:
  1550. this.obj.x = data[ 0 ];
  1551. this.obj.y = data[ 1 ];
  1552. this.obj.z = data[ 2 ];
  1553. this.angle = THREE.Math.degToRad( data[ 3 ] );
  1554. break;
  1555. }
  1556. break;
  1557. }
  1558. };
  1559. function InstanceController() {
  1560. this.url = "";
  1561. this.skeleton = [];
  1562. this.instance_material = [];
  1563. }
  1564. InstanceController.prototype.parse = function ( element ) {
  1565. this.url = element.getAttribute('url').replace(/^#/, '');
  1566. this.skeleton = [];
  1567. this.instance_material = [];
  1568. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1569. var child = element.childNodes[ i ];
  1570. if ( child.nodeType !== 1 ) continue;
  1571. switch ( child.nodeName ) {
  1572. case 'skeleton':
  1573. this.skeleton.push( child.textContent.replace(/^#/, '') );
  1574. break;
  1575. case 'bind_material':
  1576. var instances = child.querySelectorAll('instance_material');
  1577. for ( var j = 0; j < instances.length; j ++ ) {
  1578. var instance = instances[j];
  1579. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1580. }
  1581. break;
  1582. case 'extra':
  1583. break;
  1584. default:
  1585. break;
  1586. }
  1587. }
  1588. return this;
  1589. };
  1590. function InstanceMaterial () {
  1591. this.symbol = "";
  1592. this.target = "";
  1593. }
  1594. InstanceMaterial.prototype.parse = function ( element ) {
  1595. this.symbol = element.getAttribute('symbol');
  1596. this.target = element.getAttribute('target').replace(/^#/, '');
  1597. return this;
  1598. };
  1599. function InstanceGeometry() {
  1600. this.url = "";
  1601. this.instance_material = [];
  1602. }
  1603. InstanceGeometry.prototype.parse = function ( element ) {
  1604. this.url = element.getAttribute('url').replace(/^#/, '');
  1605. this.instance_material = [];
  1606. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1607. var child = element.childNodes[i];
  1608. if ( child.nodeType != 1 ) continue;
  1609. if ( child.nodeName === 'bind_material' ) {
  1610. var instances = child.querySelectorAll('instance_material');
  1611. for ( var j = 0; j < instances.length; j ++ ) {
  1612. var instance = instances[j];
  1613. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  1614. }
  1615. break;
  1616. }
  1617. }
  1618. return this;
  1619. };
  1620. function Geometry() {
  1621. this.id = "";
  1622. this.mesh = null;
  1623. }
  1624. Geometry.prototype.parse = function ( element ) {
  1625. this.id = element.getAttribute('id');
  1626. extractDoubleSided( this, element );
  1627. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1628. var child = element.childNodes[i];
  1629. switch ( child.nodeName ) {
  1630. case 'mesh':
  1631. this.mesh = (new Mesh(this)).parse(child);
  1632. break;
  1633. case 'extra':
  1634. // console.log( child );
  1635. break;
  1636. default:
  1637. break;
  1638. }
  1639. }
  1640. return this;
  1641. };
  1642. function Mesh( geometry ) {
  1643. this.geometry = geometry.id;
  1644. this.primitives = [];
  1645. this.vertices = null;
  1646. this.geometry3js = null;
  1647. }
  1648. Mesh.prototype.parse = function ( element ) {
  1649. this.primitives = [];
  1650. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1651. var child = element.childNodes[ i ];
  1652. switch ( child.nodeName ) {
  1653. case 'source':
  1654. _source( child );
  1655. break;
  1656. case 'vertices':
  1657. this.vertices = ( new Vertices() ).parse( child );
  1658. break;
  1659. case 'linestrips':
  1660. this.primitives.push( ( new LineStrips().parse( child ) ) );
  1661. break;
  1662. case 'triangles':
  1663. this.primitives.push( ( new Triangles().parse( child ) ) );
  1664. break;
  1665. case 'polygons':
  1666. this.primitives.push( ( new Polygons().parse( child ) ) );
  1667. break;
  1668. case 'polylist':
  1669. this.primitives.push( ( new Polylist().parse( child ) ) );
  1670. break;
  1671. default:
  1672. break;
  1673. }
  1674. }
  1675. this.geometry3js = new THREE.Geometry();
  1676. if ( this.vertices === null ) {
  1677. // TODO (mrdoob): Study case when this is null (carrier.dae)
  1678. return this;
  1679. }
  1680. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  1681. for ( var i = 0; i < vertexData.length; i += 3 ) {
  1682. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  1683. }
  1684. for ( var i = 0; i < this.primitives.length; i ++ ) {
  1685. var primitive = this.primitives[ i ];
  1686. primitive.setVertices( this.vertices );
  1687. this.handlePrimitive( primitive, this.geometry3js );
  1688. }
  1689. if ( this.geometry3js.calcNormals ) {
  1690. this.geometry3js.computeVertexNormals();
  1691. delete this.geometry3js.calcNormals;
  1692. }
  1693. return this;
  1694. };
  1695. Mesh.prototype.handlePrimitive = function ( primitive, geom ) {
  1696. if ( primitive instanceof LineStrips ) {
  1697. // TODO: Handle indices. Maybe easier with BufferGeometry?
  1698. geom.isLineStrip = true;
  1699. return;
  1700. }
  1701. var j, k, pList = primitive.p, inputs = primitive.inputs;
  1702. var input, index, idx32;
  1703. var source, numParams;
  1704. var vcIndex = 0, vcount = 3, maxOffset = 0;
  1705. var texture_sets = [];
  1706. for ( j = 0; j < inputs.length; j ++ ) {
  1707. input = inputs[ j ];
  1708. var offset = input.offset + 1;
  1709. maxOffset = (maxOffset < offset) ? offset : maxOffset;
  1710. switch ( input.semantic ) {
  1711. case 'TEXCOORD':
  1712. texture_sets.push( input.set );
  1713. break;
  1714. }
  1715. }
  1716. for ( var pCount = 0; pCount < pList.length; ++ pCount ) {
  1717. var p = pList[ pCount ], i = 0;
  1718. while ( i < p.length ) {
  1719. var vs = [];
  1720. var ns = [];
  1721. var ts = null;
  1722. var cs = [];
  1723. if ( primitive.vcount ) {
  1724. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  1725. } else {
  1726. vcount = p.length / maxOffset;
  1727. }
  1728. for ( j = 0; j < vcount; j ++ ) {
  1729. for ( k = 0; k < inputs.length; k ++ ) {
  1730. input = inputs[ k ];
  1731. source = sources[ input.source ];
  1732. index = p[ i + ( j * maxOffset ) + input.offset ];
  1733. numParams = source.accessor.params.length;
  1734. idx32 = index * numParams;
  1735. switch ( input.semantic ) {
  1736. case 'VERTEX':
  1737. vs.push( index );
  1738. break;
  1739. case 'NORMAL':
  1740. ns.push( getConvertedVec3( source.data, idx32 ) );
  1741. break;
  1742. case 'TEXCOORD':
  1743. ts = ts || { };
  1744. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  1745. // invert the V
  1746. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  1747. break;
  1748. case 'COLOR':
  1749. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1750. break;
  1751. default:
  1752. break;
  1753. }
  1754. }
  1755. }
  1756. if ( ns.length === 0 ) {
  1757. // check the vertices inputs
  1758. input = this.vertices.input.NORMAL;
  1759. if ( input ) {
  1760. source = sources[ input.source ];
  1761. numParams = source.accessor.params.length;
  1762. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1763. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  1764. }
  1765. } else {
  1766. geom.calcNormals = true;
  1767. }
  1768. }
  1769. if ( !ts ) {
  1770. ts = { };
  1771. // check the vertices inputs
  1772. input = this.vertices.input.TEXCOORD;
  1773. if ( input ) {
  1774. texture_sets.push( input.set );
  1775. source = sources[ input.source ];
  1776. numParams = source.accessor.params.length;
  1777. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1778. idx32 = vs[ ndx ] * numParams;
  1779. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  1780. // invert the V
  1781. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  1782. }
  1783. }
  1784. }
  1785. if ( cs.length === 0 ) {
  1786. // check the vertices inputs
  1787. input = this.vertices.input.COLOR;
  1788. if ( input ) {
  1789. source = sources[ input.source ];
  1790. numParams = source.accessor.params.length;
  1791. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  1792. idx32 = vs[ ndx ] * numParams;
  1793. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  1794. }
  1795. }
  1796. }
  1797. var face = null, faces = [], uv, uvArr;
  1798. if ( vcount === 3 ) {
  1799. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  1800. } else if ( vcount === 4 ) {
  1801. 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() ) );
  1802. 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() ) );
  1803. } else if ( vcount > 4 && options.subdivideFaces ) {
  1804. var clr = cs.length ? cs : new THREE.Color(),
  1805. vec1, vec2, vec3, v1, v2, norm;
  1806. // subdivide into multiple Face3s
  1807. for ( k = 1; k < vcount - 1; ) {
  1808. faces.push( new THREE.Face3( vs[0], vs[k], vs[k + 1], ns.length ? [ ns[0].clone(), ns[k ++].clone(), ns[k].clone() ] : [], clr ) );
  1809. }
  1810. }
  1811. if ( faces.length ) {
  1812. for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
  1813. face = faces[ndx];
  1814. face.daeMaterial = primitive.material;
  1815. geom.faces.push( face );
  1816. for ( k = 0; k < texture_sets.length; k ++ ) {
  1817. uv = ts[ texture_sets[k] ];
  1818. if ( vcount > 4 ) {
  1819. // Grab the right UVs for the vertices in this face
  1820. uvArr = [ uv[0], uv[ndx + 1], uv[ndx + 2] ];
  1821. } else if ( vcount === 4 ) {
  1822. if ( ndx === 0 ) {
  1823. uvArr = [ uv[0], uv[1], uv[3] ];
  1824. } else {
  1825. uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ];
  1826. }
  1827. } else {
  1828. uvArr = [ uv[0], uv[1], uv[2] ];
  1829. }
  1830. if ( geom.faceVertexUvs[k] === undefined ) {
  1831. geom.faceVertexUvs[k] = [];
  1832. }
  1833. geom.faceVertexUvs[k].push( uvArr );
  1834. }
  1835. }
  1836. } else {
  1837. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  1838. }
  1839. i += maxOffset * vcount;
  1840. }
  1841. }
  1842. };
  1843. function Polygons () {
  1844. this.material = "";
  1845. this.count = 0;
  1846. this.inputs = [];
  1847. this.vcount = null;
  1848. this.p = [];
  1849. this.geometry = new THREE.Geometry();
  1850. }
  1851. Polygons.prototype.setVertices = function ( vertices ) {
  1852. for ( var i = 0; i < this.inputs.length; i ++ ) {
  1853. if ( this.inputs[ i ].source === vertices.id ) {
  1854. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  1855. }
  1856. }
  1857. };
  1858. Polygons.prototype.parse = function ( element ) {
  1859. this.material = element.getAttribute( 'material' );
  1860. this.count = _attr_as_int( element, 'count', 0 );
  1861. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1862. var child = element.childNodes[ i ];
  1863. switch ( child.nodeName ) {
  1864. case 'input':
  1865. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  1866. break;
  1867. case 'vcount':
  1868. this.vcount = _ints( child.textContent );
  1869. break;
  1870. case 'p':
  1871. this.p.push( _ints( child.textContent ) );
  1872. break;
  1873. case 'ph':
  1874. console.warn( 'polygon holes not yet supported!' );
  1875. break;
  1876. default:
  1877. break;
  1878. }
  1879. }
  1880. return this;
  1881. };
  1882. function Polylist () {
  1883. Polygons.call( this );
  1884. this.vcount = [];
  1885. }
  1886. Polylist.prototype = Object.create( Polygons.prototype );
  1887. Polylist.prototype.constructor = Polylist;
  1888. function LineStrips() {
  1889. Polygons.call( this );
  1890. this.vcount = 1;
  1891. }
  1892. LineStrips.prototype = Object.create( Polygons.prototype );
  1893. LineStrips.prototype.constructor = LineStrips;
  1894. function Triangles () {
  1895. Polygons.call( this );
  1896. this.vcount = 3;
  1897. }
  1898. Triangles.prototype = Object.create( Polygons.prototype );
  1899. Triangles.prototype.constructor = Triangles;
  1900. function Accessor() {
  1901. this.source = "";
  1902. this.count = 0;
  1903. this.stride = 0;
  1904. this.params = [];
  1905. }
  1906. Accessor.prototype.parse = function ( element ) {
  1907. this.params = [];
  1908. this.source = element.getAttribute( 'source' );
  1909. this.count = _attr_as_int( element, 'count', 0 );
  1910. this.stride = _attr_as_int( element, 'stride', 0 );
  1911. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1912. var child = element.childNodes[ i ];
  1913. if ( child.nodeName === 'param' ) {
  1914. var param = {};
  1915. param[ 'name' ] = child.getAttribute( 'name' );
  1916. param[ 'type' ] = child.getAttribute( 'type' );
  1917. this.params.push( param );
  1918. }
  1919. }
  1920. return this;
  1921. };
  1922. function Vertices() {
  1923. this.input = {};
  1924. }
  1925. Vertices.prototype.parse = function ( element ) {
  1926. this.id = element.getAttribute('id');
  1927. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1928. if ( element.childNodes[i].nodeName === 'input' ) {
  1929. var input = ( new Input() ).parse( element.childNodes[ i ] );
  1930. this.input[ input.semantic ] = input;
  1931. }
  1932. }
  1933. return this;
  1934. };
  1935. function Input () {
  1936. this.semantic = "";
  1937. this.offset = 0;
  1938. this.source = "";
  1939. this.set = 0;
  1940. }
  1941. Input.prototype.parse = function ( element ) {
  1942. this.semantic = element.getAttribute('semantic');
  1943. this.source = element.getAttribute('source').replace(/^#/, '');
  1944. this.set = _attr_as_int(element, 'set', -1);
  1945. this.offset = _attr_as_int(element, 'offset', 0);
  1946. if ( this.semantic === 'TEXCOORD' && this.set < 0 ) {
  1947. this.set = 0;
  1948. }
  1949. return this;
  1950. };
  1951. function Source ( id ) {
  1952. this.id = id;
  1953. this.type = null;
  1954. }
  1955. Source.prototype.parse = function ( element ) {
  1956. this.id = element.getAttribute( 'id' );
  1957. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  1958. var child = element.childNodes[i];
  1959. switch ( child.nodeName ) {
  1960. case 'bool_array':
  1961. this.data = _bools( child.textContent );
  1962. this.type = child.nodeName;
  1963. break;
  1964. case 'float_array':
  1965. this.data = _floats( child.textContent );
  1966. this.type = child.nodeName;
  1967. break;
  1968. case 'int_array':
  1969. this.data = _ints( child.textContent );
  1970. this.type = child.nodeName;
  1971. break;
  1972. case 'IDREF_array':
  1973. case 'Name_array':
  1974. this.data = _strings( child.textContent );
  1975. this.type = child.nodeName;
  1976. break;
  1977. case 'technique_common':
  1978. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  1979. if ( child.childNodes[ j ].nodeName === 'accessor' ) {
  1980. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  1981. break;
  1982. }
  1983. }
  1984. break;
  1985. default:
  1986. // console.log(child.nodeName);
  1987. break;
  1988. }
  1989. }
  1990. return this;
  1991. };
  1992. Source.prototype.read = function () {
  1993. var result = [];
  1994. //for (var i = 0; i < this.accessor.params.length; i++) {
  1995. var param = this.accessor.params[ 0 ];
  1996. //console.log(param.name + " " + param.type);
  1997. switch ( param.type ) {
  1998. case 'IDREF':
  1999. case 'Name': case 'name':
  2000. case 'float':
  2001. return this.data;
  2002. case 'float4x4':
  2003. for ( var j = 0; j < this.data.length; j += 16 ) {
  2004. var s = this.data.slice( j, j + 16 );
  2005. var m = getConvertedMat4( s );
  2006. result.push( m );
  2007. }
  2008. break;
  2009. default:
  2010. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  2011. break;
  2012. }
  2013. //}
  2014. return result;
  2015. };
  2016. function Material () {
  2017. this.id = "";
  2018. this.name = "";
  2019. this.instance_effect = null;
  2020. }
  2021. Material.prototype.parse = function ( element ) {
  2022. this.id = element.getAttribute( 'id' );
  2023. this.name = element.getAttribute( 'name' );
  2024. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2025. if ( element.childNodes[ i ].nodeName === 'instance_effect' ) {
  2026. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  2027. break;
  2028. }
  2029. }
  2030. return this;
  2031. };
  2032. function ColorOrTexture () {
  2033. this.color = new THREE.Color();
  2034. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  2035. this.color.a = 1.0;
  2036. this.texture = null;
  2037. this.texcoord = null;
  2038. this.texOpts = null;
  2039. }
  2040. ColorOrTexture.prototype.isColor = function () {
  2041. return ( this.texture === null );
  2042. };
  2043. ColorOrTexture.prototype.isTexture = function () {
  2044. return ( this.texture != null );
  2045. };
  2046. ColorOrTexture.prototype.parse = function ( element ) {
  2047. if (element.nodeName === 'transparent') {
  2048. this.opaque = element.getAttribute('opaque');
  2049. }
  2050. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2051. var child = element.childNodes[ i ];
  2052. if ( child.nodeType != 1 ) continue;
  2053. switch ( child.nodeName ) {
  2054. case 'color':
  2055. var rgba = _floats( child.textContent );
  2056. this.color = new THREE.Color();
  2057. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2058. this.color.a = rgba[3];
  2059. break;
  2060. case 'texture':
  2061. this.texture = child.getAttribute('texture');
  2062. this.texcoord = child.getAttribute('texcoord');
  2063. // Defaults from:
  2064. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  2065. this.texOpts = {
  2066. offsetU: 0,
  2067. offsetV: 0,
  2068. repeatU: 1,
  2069. repeatV: 1,
  2070. wrapU: 1,
  2071. wrapV: 1
  2072. };
  2073. this.parseTexture( child );
  2074. break;
  2075. default:
  2076. break;
  2077. }
  2078. }
  2079. return this;
  2080. };
  2081. ColorOrTexture.prototype.parseTexture = function ( element ) {
  2082. if ( ! element.childNodes ) return this;
  2083. // This should be supported by Maya, 3dsMax, and MotionBuilder
  2084. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  2085. element = element.childNodes[1];
  2086. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  2087. element = element.childNodes[1];
  2088. }
  2089. }
  2090. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2091. var child = element.childNodes[ i ];
  2092. switch ( child.nodeName ) {
  2093. case 'offsetU':
  2094. case 'offsetV':
  2095. case 'repeatU':
  2096. case 'repeatV':
  2097. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  2098. break;
  2099. case 'wrapU':
  2100. case 'wrapV':
  2101. // some dae have a value of true which becomes NaN via parseInt
  2102. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  2103. this.texOpts[ child.nodeName ] = 1;
  2104. } else {
  2105. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  2106. }
  2107. break;
  2108. default:
  2109. this.texOpts[ child.nodeName ] = child.textContent;
  2110. break;
  2111. }
  2112. }
  2113. return this;
  2114. };
  2115. function Shader ( type, effect ) {
  2116. this.type = type;
  2117. this.effect = effect;
  2118. this.material = null;
  2119. }
  2120. Shader.prototype.parse = function ( element ) {
  2121. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2122. var child = element.childNodes[ i ];
  2123. if ( child.nodeType != 1 ) continue;
  2124. switch ( child.nodeName ) {
  2125. case 'emission':
  2126. case 'diffuse':
  2127. case 'specular':
  2128. case 'transparent':
  2129. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  2130. break;
  2131. case 'bump':
  2132. // If 'bumptype' is 'heightfield', create a 'bump' property
  2133. // Else if 'bumptype' is 'normalmap', create a 'normal' property
  2134. // (Default to 'bump')
  2135. var bumpType = child.getAttribute( 'bumptype' );
  2136. if ( bumpType ) {
  2137. if ( bumpType.toLowerCase() === "heightfield" ) {
  2138. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2139. } else if ( bumpType.toLowerCase() === "normalmap" ) {
  2140. this[ 'normal' ] = ( new ColorOrTexture() ).parse( child );
  2141. } else {
  2142. console.error( "Shader.prototype.parse: Invalid value for attribute 'bumptype' (" + bumpType + ") - valid bumptypes are 'HEIGHTFIELD' and 'NORMALMAP' - defaulting to 'HEIGHTFIELD'" );
  2143. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2144. }
  2145. } else {
  2146. console.warn( "Shader.prototype.parse: Attribute 'bumptype' missing from bump node - defaulting to 'HEIGHTFIELD'" );
  2147. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  2148. }
  2149. break;
  2150. case 'shininess':
  2151. case 'reflectivity':
  2152. case 'index_of_refraction':
  2153. case 'transparency':
  2154. var f = child.querySelectorAll('float');
  2155. if ( f.length > 0 )
  2156. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  2157. break;
  2158. default:
  2159. break;
  2160. }
  2161. }
  2162. this.create();
  2163. return this;
  2164. };
  2165. Shader.prototype.create = function() {
  2166. var props = {};
  2167. var transparent = false;
  2168. if (this['transparency'] !== undefined && this['transparent'] !== undefined) {
  2169. // convert transparent color RBG to average value
  2170. var transparentColor = this['transparent'];
  2171. var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency;
  2172. if (transparencyLevel > 0) {
  2173. transparent = true;
  2174. props[ 'transparent' ] = true;
  2175. props[ 'opacity' ] = 1 - transparencyLevel;
  2176. }
  2177. }
  2178. var keys = {
  2179. 'diffuse':'map',
  2180. 'ambient':'lightMap',
  2181. 'specular':'specularMap',
  2182. 'emission':'emissionMap',
  2183. 'bump':'bumpMap',
  2184. 'normal':'normalMap'
  2185. };
  2186. for ( var prop in this ) {
  2187. switch ( prop ) {
  2188. case 'ambient':
  2189. case 'emission':
  2190. case 'diffuse':
  2191. case 'specular':
  2192. case 'bump':
  2193. case 'normal':
  2194. var cot = this[ prop ];
  2195. if ( cot instanceof ColorOrTexture ) {
  2196. if ( cot.isTexture() ) {
  2197. var samplerId = cot.texture;
  2198. var sampler = this.effect.sampler[samplerId];
  2199. if ( sampler !== undefined && sampler.source !== undefined ) {
  2200. var surface = this.effect.surface[sampler.source];
  2201. if ( surface !== undefined ) {
  2202. var image = images[ surface.init_from ];
  2203. if ( image ) {
  2204. var url = baseUrl + image.init_from;
  2205. var texture;
  2206. var loader = THREE.Loader.Handlers.get( url );
  2207. if ( loader !== null ) {
  2208. texture = loader.load( url );
  2209. } else {
  2210. texture = new THREE.Texture();
  2211. loadTextureImage( texture, url );
  2212. }
  2213. if ( sampler.wrap_s === "MIRROR" ) {
  2214. texture.wrapS = THREE.MirroredRepeatWrapping;
  2215. } else if ( sampler.wrap_s === "WRAP" || cot.texOpts.wrapU ) {
  2216. texture.wrapS = THREE.RepeatWrapping;
  2217. } else {
  2218. texture.wrapS = THREE.ClampToEdgeWrapping;
  2219. }
  2220. if ( sampler.wrap_t === "MIRROR" ) {
  2221. texture.wrapT = THREE.MirroredRepeatWrapping;
  2222. } else if ( sampler.wrap_t === "WRAP" || cot.texOpts.wrapV ) {
  2223. texture.wrapT = THREE.RepeatWrapping;
  2224. } else {
  2225. texture.wrapT = THREE.ClampToEdgeWrapping;
  2226. }
  2227. texture.offset.x = cot.texOpts.offsetU;
  2228. texture.offset.y = cot.texOpts.offsetV;
  2229. texture.repeat.x = cot.texOpts.repeatU;
  2230. texture.repeat.y = cot.texOpts.repeatV;
  2231. props[keys[prop]] = texture;
  2232. // Texture with baked lighting?
  2233. if (prop === 'emission') props['emissive'] = 0xffffff;
  2234. }
  2235. }
  2236. }
  2237. } else if ( prop === 'diffuse' || !transparent ) {
  2238. if ( prop === 'emission' ) {
  2239. props[ 'emissive' ] = cot.color.getHex();
  2240. } else {
  2241. props[ prop ] = cot.color.getHex();
  2242. }
  2243. }
  2244. }
  2245. break;
  2246. case 'shininess':
  2247. props[ prop ] = this[ prop ];
  2248. break;
  2249. case 'reflectivity':
  2250. props[ prop ] = this[ prop ];
  2251. if ( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
  2252. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  2253. break;
  2254. case 'index_of_refraction':
  2255. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  2256. if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
  2257. break;
  2258. case 'transparency':
  2259. // gets figured out up top
  2260. break;
  2261. default:
  2262. break;
  2263. }
  2264. }
  2265. props[ 'shading' ] = preferredShading;
  2266. props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
  2267. if ( props.diffuse !== undefined ) {
  2268. props.color = props.diffuse;
  2269. delete props.diffuse;
  2270. }
  2271. switch ( this.type ) {
  2272. case 'constant':
  2273. if (props.emissive != undefined) props.color = props.emissive;
  2274. this.material = new THREE.MeshBasicMaterial( props );
  2275. break;
  2276. case 'phong':
  2277. case 'blinn':
  2278. this.material = new THREE.MeshPhongMaterial( props );
  2279. break;
  2280. case 'lambert':
  2281. default:
  2282. this.material = new THREE.MeshLambertMaterial( props );
  2283. break;
  2284. }
  2285. return this.material;
  2286. };
  2287. function Surface ( effect ) {
  2288. this.effect = effect;
  2289. this.init_from = null;
  2290. this.format = null;
  2291. }
  2292. Surface.prototype.parse = function ( element ) {
  2293. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2294. var child = element.childNodes[ i ];
  2295. if ( child.nodeType != 1 ) continue;
  2296. switch ( child.nodeName ) {
  2297. case 'init_from':
  2298. this.init_from = child.textContent;
  2299. break;
  2300. case 'format':
  2301. this.format = child.textContent;
  2302. break;
  2303. default:
  2304. console.log( "unhandled Surface prop: " + child.nodeName );
  2305. break;
  2306. }
  2307. }
  2308. return this;
  2309. };
  2310. function Sampler2D ( effect ) {
  2311. this.effect = effect;
  2312. this.source = null;
  2313. this.wrap_s = null;
  2314. this.wrap_t = null;
  2315. this.minfilter = null;
  2316. this.magfilter = null;
  2317. this.mipfilter = null;
  2318. }
  2319. Sampler2D.prototype.parse = function ( element ) {
  2320. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2321. var child = element.childNodes[ i ];
  2322. if ( child.nodeType != 1 ) continue;
  2323. switch ( child.nodeName ) {
  2324. case 'source':
  2325. this.source = child.textContent;
  2326. break;
  2327. case 'minfilter':
  2328. this.minfilter = child.textContent;
  2329. break;
  2330. case 'magfilter':
  2331. this.magfilter = child.textContent;
  2332. break;
  2333. case 'mipfilter':
  2334. this.mipfilter = child.textContent;
  2335. break;
  2336. case 'wrap_s':
  2337. this.wrap_s = child.textContent;
  2338. break;
  2339. case 'wrap_t':
  2340. this.wrap_t = child.textContent;
  2341. break;
  2342. default:
  2343. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  2344. break;
  2345. }
  2346. }
  2347. return this;
  2348. };
  2349. function Effect () {
  2350. this.id = "";
  2351. this.name = "";
  2352. this.shader = null;
  2353. this.surface = {};
  2354. this.sampler = {};
  2355. }
  2356. Effect.prototype.create = function () {
  2357. if ( this.shader === null ) {
  2358. return null;
  2359. }
  2360. };
  2361. Effect.prototype.parse = function ( element ) {
  2362. this.id = element.getAttribute( 'id' );
  2363. this.name = element.getAttribute( 'name' );
  2364. extractDoubleSided( this, element );
  2365. this.shader = null;
  2366. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2367. var child = element.childNodes[ i ];
  2368. if ( child.nodeType != 1 ) continue;
  2369. switch ( child.nodeName ) {
  2370. case 'profile_COMMON':
  2371. this.parseTechnique( this.parseProfileCOMMON( child ) );
  2372. break;
  2373. default:
  2374. break;
  2375. }
  2376. }
  2377. return this;
  2378. };
  2379. Effect.prototype.parseNewparam = function ( element ) {
  2380. var sid = element.getAttribute( 'sid' );
  2381. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2382. var child = element.childNodes[ i ];
  2383. if ( child.nodeType != 1 ) continue;
  2384. switch ( child.nodeName ) {
  2385. case 'surface':
  2386. this.surface[sid] = ( new Surface( this ) ).parse( child );
  2387. break;
  2388. case 'sampler2D':
  2389. this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
  2390. break;
  2391. case 'extra':
  2392. break;
  2393. default:
  2394. console.log( child.nodeName );
  2395. break;
  2396. }
  2397. }
  2398. };
  2399. Effect.prototype.parseProfileCOMMON = function ( element ) {
  2400. var technique;
  2401. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2402. var child = element.childNodes[ i ];
  2403. if ( child.nodeType != 1 ) continue;
  2404. switch ( child.nodeName ) {
  2405. case 'profile_COMMON':
  2406. this.parseProfileCOMMON( child );
  2407. break;
  2408. case 'technique':
  2409. technique = child;
  2410. break;
  2411. case 'newparam':
  2412. this.parseNewparam( child );
  2413. break;
  2414. case 'image':
  2415. var _image = ( new _Image() ).parse( child );
  2416. images[ _image.id ] = _image;
  2417. break;
  2418. case 'extra':
  2419. break;
  2420. default:
  2421. console.log( child.nodeName );
  2422. break;
  2423. }
  2424. }
  2425. return technique;
  2426. };
  2427. Effect.prototype.parseTechnique = function ( element ) {
  2428. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2429. var child = element.childNodes[i];
  2430. if ( child.nodeType != 1 ) continue;
  2431. switch ( child.nodeName ) {
  2432. case 'constant':
  2433. case 'lambert':
  2434. case 'blinn':
  2435. case 'phong':
  2436. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  2437. break;
  2438. case 'extra':
  2439. this.parseExtra(child);
  2440. break;
  2441. default:
  2442. break;
  2443. }
  2444. }
  2445. };
  2446. Effect.prototype.parseExtra = function ( element ) {
  2447. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2448. var child = element.childNodes[i];
  2449. if ( child.nodeType != 1 ) continue;
  2450. switch ( child.nodeName ) {
  2451. case 'technique':
  2452. this.parseExtraTechnique( child );
  2453. break;
  2454. default:
  2455. break;
  2456. }
  2457. }
  2458. };
  2459. Effect.prototype.parseExtraTechnique = function ( element ) {
  2460. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2461. var child = element.childNodes[i];
  2462. if ( child.nodeType != 1 ) continue;
  2463. switch ( child.nodeName ) {
  2464. case 'bump':
  2465. this.shader.parse( element );
  2466. break;
  2467. default:
  2468. break;
  2469. }
  2470. }
  2471. };
  2472. function InstanceEffect () {
  2473. this.url = "";
  2474. }
  2475. InstanceEffect.prototype.parse = function ( element ) {
  2476. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  2477. return this;
  2478. };
  2479. function Animation() {
  2480. this.id = "";
  2481. this.name = "";
  2482. this.source = {};
  2483. this.sampler = [];
  2484. this.channel = [];
  2485. }
  2486. Animation.prototype.parse = function ( element ) {
  2487. this.id = element.getAttribute( 'id' );
  2488. this.name = element.getAttribute( 'name' );
  2489. this.source = {};
  2490. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2491. var child = element.childNodes[ i ];
  2492. if ( child.nodeType != 1 ) continue;
  2493. switch ( child.nodeName ) {
  2494. case 'animation':
  2495. var anim = ( new Animation() ).parse( child );
  2496. for ( var src in anim.source ) {
  2497. this.source[ src ] = anim.source[ src ];
  2498. }
  2499. for ( var j = 0; j < anim.channel.length; j ++ ) {
  2500. this.channel.push( anim.channel[ j ] );
  2501. this.sampler.push( anim.sampler[ j ] );
  2502. }
  2503. break;
  2504. case 'source':
  2505. var src = ( new Source() ).parse( child );
  2506. this.source[ src.id ] = src;
  2507. break;
  2508. case 'sampler':
  2509. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  2510. break;
  2511. case 'channel':
  2512. this.channel.push( ( new Channel( this ) ).parse( child ) );
  2513. break;
  2514. default:
  2515. break;
  2516. }
  2517. }
  2518. return this;
  2519. };
  2520. function Channel( animation ) {
  2521. this.animation = animation;
  2522. this.source = "";
  2523. this.target = "";
  2524. this.fullSid = null;
  2525. this.sid = null;
  2526. this.dotSyntax = null;
  2527. this.arrSyntax = null;
  2528. this.arrIndices = null;
  2529. this.member = null;
  2530. }
  2531. Channel.prototype.parse = function ( element ) {
  2532. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  2533. this.target = element.getAttribute( 'target' );
  2534. var parts = this.target.split( '/' );
  2535. var id = parts.shift();
  2536. var sid = parts.shift();
  2537. var dotSyntax = ( sid.indexOf(".") >= 0 );
  2538. var arrSyntax = ( sid.indexOf("(") >= 0 );
  2539. if ( dotSyntax ) {
  2540. parts = sid.split(".");
  2541. this.sid = parts.shift();
  2542. this.member = parts.shift();
  2543. } else if ( arrSyntax ) {
  2544. var arrIndices = sid.split("(");
  2545. this.sid = arrIndices.shift();
  2546. for (var j = 0; j < arrIndices.length; j ++ ) {
  2547. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  2548. }
  2549. this.arrIndices = arrIndices;
  2550. } else {
  2551. this.sid = sid;
  2552. }
  2553. this.fullSid = sid;
  2554. this.dotSyntax = dotSyntax;
  2555. this.arrSyntax = arrSyntax;
  2556. return this;
  2557. };
  2558. function Sampler ( animation ) {
  2559. this.id = "";
  2560. this.animation = animation;
  2561. this.inputs = [];
  2562. this.input = null;
  2563. this.output = null;
  2564. this.strideOut = null;
  2565. this.interpolation = null;
  2566. this.startTime = null;
  2567. this.endTime = null;
  2568. this.duration = 0;
  2569. }
  2570. Sampler.prototype.parse = function ( element ) {
  2571. this.id = element.getAttribute( 'id' );
  2572. this.inputs = [];
  2573. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2574. var child = element.childNodes[ i ];
  2575. if ( child.nodeType != 1 ) continue;
  2576. switch ( child.nodeName ) {
  2577. case 'input':
  2578. this.inputs.push( (new Input()).parse( child ) );
  2579. break;
  2580. default:
  2581. break;
  2582. }
  2583. }
  2584. return this;
  2585. };
  2586. Sampler.prototype.create = function () {
  2587. for ( var i = 0; i < this.inputs.length; i ++ ) {
  2588. var input = this.inputs[ i ];
  2589. var source = this.animation.source[ input.source ];
  2590. switch ( input.semantic ) {
  2591. case 'INPUT':
  2592. this.input = source.read();
  2593. break;
  2594. case 'OUTPUT':
  2595. this.output = source.read();
  2596. this.strideOut = source.accessor.stride;
  2597. break;
  2598. case 'INTERPOLATION':
  2599. this.interpolation = source.read();
  2600. break;
  2601. case 'IN_TANGENT':
  2602. break;
  2603. case 'OUT_TANGENT':
  2604. break;
  2605. default:
  2606. console.log(input.semantic);
  2607. break;
  2608. }
  2609. }
  2610. this.startTime = 0;
  2611. this.endTime = 0;
  2612. this.duration = 0;
  2613. if ( this.input.length ) {
  2614. this.startTime = 100000000;
  2615. this.endTime = -100000000;
  2616. for ( var i = 0; i < this.input.length; i ++ ) {
  2617. this.startTime = Math.min( this.startTime, this.input[ i ] );
  2618. this.endTime = Math.max( this.endTime, this.input[ i ] );
  2619. }
  2620. this.duration = this.endTime - this.startTime;
  2621. }
  2622. };
  2623. Sampler.prototype.getData = function ( type, ndx, member ) {
  2624. var data;
  2625. if ( type === 'matrix' && this.strideOut === 16 ) {
  2626. data = this.output[ ndx ];
  2627. } else if ( this.strideOut > 1 ) {
  2628. data = [];
  2629. ndx *= this.strideOut;
  2630. for ( var i = 0; i < this.strideOut; ++ i ) {
  2631. data[ i ] = this.output[ ndx + i ];
  2632. }
  2633. if ( this.strideOut === 3 ) {
  2634. switch ( type ) {
  2635. case 'rotate':
  2636. case 'translate':
  2637. fixCoords( data, -1 );
  2638. break;
  2639. case 'scale':
  2640. fixCoords( data, 1 );
  2641. break;
  2642. }
  2643. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  2644. fixCoords( data, -1 );
  2645. }
  2646. } else {
  2647. data = this.output[ ndx ];
  2648. if ( member && type === 'translate' ) {
  2649. data = getConvertedTranslation( member, data );
  2650. }
  2651. }
  2652. return data;
  2653. };
  2654. function Key ( time ) {
  2655. this.targets = [];
  2656. this.time = time;
  2657. }
  2658. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  2659. this.targets.push( {
  2660. sid: fullSid,
  2661. member: member,
  2662. transform: transform,
  2663. data: data
  2664. } );
  2665. };
  2666. Key.prototype.apply = function ( opt_sid ) {
  2667. for ( var i = 0; i < this.targets.length; ++ i ) {
  2668. var target = this.targets[ i ];
  2669. if ( !opt_sid || target.sid === opt_sid ) {
  2670. target.transform.update( target.data, target.member );
  2671. }
  2672. }
  2673. };
  2674. Key.prototype.getTarget = function ( fullSid ) {
  2675. for ( var i = 0; i < this.targets.length; ++ i ) {
  2676. if ( this.targets[ i ].sid === fullSid ) {
  2677. return this.targets[ i ];
  2678. }
  2679. }
  2680. return null;
  2681. };
  2682. Key.prototype.hasTarget = function ( fullSid ) {
  2683. for ( var i = 0; i < this.targets.length; ++ i ) {
  2684. if ( this.targets[ i ].sid === fullSid ) {
  2685. return true;
  2686. }
  2687. }
  2688. return false;
  2689. };
  2690. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  2691. Key.prototype.interpolate = function ( nextKey, time ) {
  2692. for ( var i = 0, l = this.targets.length; i < l; i ++ ) {
  2693. var target = this.targets[ i ],
  2694. nextTarget = nextKey.getTarget( target.sid ),
  2695. data;
  2696. if ( target.transform.type !== 'matrix' && nextTarget ) {
  2697. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  2698. nextData = nextTarget.data,
  2699. prevData = target.data;
  2700. if ( scale < 0 ) scale = 0;
  2701. if ( scale > 1 ) scale = 1;
  2702. if ( prevData.length ) {
  2703. data = [];
  2704. for ( var j = 0; j < prevData.length; ++ j ) {
  2705. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  2706. }
  2707. } else {
  2708. data = prevData + ( nextData - prevData ) * scale;
  2709. }
  2710. } else {
  2711. data = target.data;
  2712. }
  2713. target.transform.update( data, target.member );
  2714. }
  2715. };
  2716. // Camera
  2717. function Camera() {
  2718. this.id = "";
  2719. this.name = "";
  2720. this.technique = "";
  2721. }
  2722. Camera.prototype.parse = function ( element ) {
  2723. this.id = element.getAttribute( 'id' );
  2724. this.name = element.getAttribute( 'name' );
  2725. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2726. var child = element.childNodes[ i ];
  2727. if ( child.nodeType != 1 ) continue;
  2728. switch ( child.nodeName ) {
  2729. case 'optics':
  2730. this.parseOptics( child );
  2731. break;
  2732. default:
  2733. break;
  2734. }
  2735. }
  2736. return this;
  2737. };
  2738. Camera.prototype.parseOptics = function ( element ) {
  2739. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2740. if ( element.childNodes[ i ].nodeName === 'technique_common' ) {
  2741. var technique = element.childNodes[ i ];
  2742. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  2743. this.technique = technique.childNodes[ j ].nodeName;
  2744. if ( this.technique === 'perspective' ) {
  2745. var perspective = technique.childNodes[ j ];
  2746. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  2747. var param = perspective.childNodes[ k ];
  2748. switch ( param.nodeName ) {
  2749. case 'yfov':
  2750. this.yfov = param.textContent;
  2751. break;
  2752. case 'xfov':
  2753. this.xfov = param.textContent;
  2754. break;
  2755. case 'znear':
  2756. this.znear = param.textContent;
  2757. break;
  2758. case 'zfar':
  2759. this.zfar = param.textContent;
  2760. break;
  2761. case 'aspect_ratio':
  2762. this.aspect_ratio = param.textContent;
  2763. break;
  2764. }
  2765. }
  2766. } else if ( this.technique === 'orthographic' ) {
  2767. var orthographic = technique.childNodes[ j ];
  2768. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  2769. var param = orthographic.childNodes[ k ];
  2770. switch ( param.nodeName ) {
  2771. case 'xmag':
  2772. this.xmag = param.textContent;
  2773. break;
  2774. case 'ymag':
  2775. this.ymag = param.textContent;
  2776. break;
  2777. case 'znear':
  2778. this.znear = param.textContent;
  2779. break;
  2780. case 'zfar':
  2781. this.zfar = param.textContent;
  2782. break;
  2783. case 'aspect_ratio':
  2784. this.aspect_ratio = param.textContent;
  2785. break;
  2786. }
  2787. }
  2788. }
  2789. }
  2790. }
  2791. }
  2792. return this;
  2793. };
  2794. function InstanceCamera() {
  2795. this.url = "";
  2796. }
  2797. InstanceCamera.prototype.parse = function ( element ) {
  2798. this.url = element.getAttribute('url').replace(/^#/, '');
  2799. return this;
  2800. };
  2801. // Light
  2802. function Light() {
  2803. this.id = "";
  2804. this.name = "";
  2805. this.technique = "";
  2806. }
  2807. Light.prototype.parse = function ( element ) {
  2808. this.id = element.getAttribute( 'id' );
  2809. this.name = element.getAttribute( 'name' );
  2810. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2811. var child = element.childNodes[ i ];
  2812. if ( child.nodeType != 1 ) continue;
  2813. switch ( child.nodeName ) {
  2814. case 'technique_common':
  2815. this.parseCommon( child );
  2816. break;
  2817. case 'technique':
  2818. this.parseTechnique( child );
  2819. break;
  2820. default:
  2821. break;
  2822. }
  2823. }
  2824. return this;
  2825. };
  2826. Light.prototype.parseCommon = function ( element ) {
  2827. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2828. switch ( element.childNodes[ i ].nodeName ) {
  2829. case 'directional':
  2830. case 'point':
  2831. case 'spot':
  2832. case 'ambient':
  2833. this.technique = element.childNodes[ i ].nodeName;
  2834. var light = element.childNodes[ i ];
  2835. for ( var j = 0; j < light.childNodes.length; j ++ ) {
  2836. var child = light.childNodes[j];
  2837. switch ( child.nodeName ) {
  2838. case 'color':
  2839. var rgba = _floats( child.textContent );
  2840. this.color = new THREE.Color(0);
  2841. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  2842. this.color.a = rgba[3];
  2843. break;
  2844. case 'falloff_angle':
  2845. this.falloff_angle = parseFloat( child.textContent );
  2846. break;
  2847. case 'quadratic_attenuation':
  2848. var f = parseFloat( child.textContent );
  2849. this.distance = f ? Math.sqrt( 1 / f ) : 0;
  2850. }
  2851. }
  2852. }
  2853. }
  2854. return this;
  2855. };
  2856. Light.prototype.parseTechnique = function ( element ) {
  2857. this.profile = element.getAttribute( 'profile' );
  2858. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  2859. var child = element.childNodes[ i ];
  2860. switch ( child.nodeName ) {
  2861. case 'intensity':
  2862. this.intensity = parseFloat(child.textContent);
  2863. break;
  2864. }
  2865. }
  2866. return this;
  2867. };
  2868. function InstanceLight() {
  2869. this.url = "";
  2870. }
  2871. InstanceLight.prototype.parse = function ( element ) {
  2872. this.url = element.getAttribute('url').replace(/^#/, '');
  2873. return this;
  2874. };
  2875. function KinematicsModel( ) {
  2876. this.id = '';
  2877. this.name = '';
  2878. this.joints = [];
  2879. this.links = [];
  2880. }
  2881. KinematicsModel.prototype.parse = function( element ) {
  2882. this.id = element.getAttribute('id');
  2883. this.name = element.getAttribute('name');
  2884. this.joints = [];
  2885. this.links = [];
  2886. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2887. var child = element.childNodes[ i ];
  2888. if ( child.nodeType != 1 ) continue;
  2889. switch ( child.nodeName ) {
  2890. case 'technique_common':
  2891. this.parseCommon(child);
  2892. break;
  2893. default:
  2894. break;
  2895. }
  2896. }
  2897. return this;
  2898. };
  2899. KinematicsModel.prototype.parseCommon = function( element ) {
  2900. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2901. var child = element.childNodes[ i ];
  2902. if ( child.nodeType != 1 ) continue;
  2903. switch ( element.childNodes[ i ].nodeName ) {
  2904. case 'joint':
  2905. this.joints.push( (new Joint()).parse(child) );
  2906. break;
  2907. case 'link':
  2908. this.links.push( (new Link()).parse(child) );
  2909. break;
  2910. default:
  2911. break;
  2912. }
  2913. }
  2914. return this;
  2915. };
  2916. function Joint( ) {
  2917. this.sid = '';
  2918. this.name = '';
  2919. this.axis = new THREE.Vector3();
  2920. this.limits = {
  2921. min: 0,
  2922. max: 0
  2923. };
  2924. this.type = '';
  2925. this.static = false;
  2926. this.zeroPosition = 0.0;
  2927. this.middlePosition = 0.0;
  2928. }
  2929. Joint.prototype.parse = function( element ) {
  2930. this.sid = element.getAttribute('sid');
  2931. this.name = element.getAttribute('name');
  2932. this.axis = new THREE.Vector3();
  2933. this.limits = {
  2934. min: 0,
  2935. max: 0
  2936. };
  2937. this.type = '';
  2938. this.static = false;
  2939. this.zeroPosition = 0.0;
  2940. this.middlePosition = 0.0;
  2941. var axisElement = element.querySelector('axis');
  2942. var _axis = _floats(axisElement.textContent);
  2943. this.axis = getConvertedVec3(_axis, 0);
  2944. var min = element.querySelector('limits min') ? parseFloat(element.querySelector('limits min').textContent) : -360;
  2945. var max = element.querySelector('limits max') ? parseFloat(element.querySelector('limits max').textContent) : 360;
  2946. this.limits = {
  2947. min: min,
  2948. max: max
  2949. };
  2950. var jointTypes = [ 'prismatic', 'revolute' ];
  2951. for (var i = 0; i < jointTypes.length; i ++ ) {
  2952. var type = jointTypes[ i ];
  2953. var jointElement = element.querySelector(type);
  2954. if ( jointElement ) {
  2955. this.type = type;
  2956. }
  2957. }
  2958. // if the min is equal to or somehow greater than the max, consider the joint static
  2959. if ( this.limits.min >= this.limits.max ) {
  2960. this.static = true;
  2961. }
  2962. this.middlePosition = (this.limits.min + this.limits.max) / 2.0;
  2963. return this;
  2964. };
  2965. function Link( ) {
  2966. this.sid = '';
  2967. this.name = '';
  2968. this.transforms = [];
  2969. this.attachments = [];
  2970. }
  2971. Link.prototype.parse = function( element ) {
  2972. this.sid = element.getAttribute('sid');
  2973. this.name = element.getAttribute('name');
  2974. this.transforms = [];
  2975. this.attachments = [];
  2976. for (var i = 0; i < element.childNodes.length; i ++ ) {
  2977. var child = element.childNodes[ i ];
  2978. if ( child.nodeType != 1 ) continue;
  2979. switch ( child.nodeName ) {
  2980. case 'attachment_full':
  2981. this.attachments.push( (new Attachment()).parse(child) );
  2982. break;
  2983. case 'rotate':
  2984. case 'translate':
  2985. case 'matrix':
  2986. this.transforms.push( (new Transform()).parse(child) );
  2987. break;
  2988. default:
  2989. break;
  2990. }
  2991. }
  2992. return this;
  2993. };
  2994. function Attachment( ) {
  2995. this.joint = '';
  2996. this.transforms = [];
  2997. this.links = [];
  2998. }
  2999. Attachment.prototype.parse = function( element ) {
  3000. this.joint = element.getAttribute('joint').split('/').pop();
  3001. this.links = [];
  3002. for (var i = 0; i < element.childNodes.length; i ++ ) {
  3003. var child = element.childNodes[ i ];
  3004. if ( child.nodeType != 1 ) continue;
  3005. switch ( child.nodeName ) {
  3006. case 'link':
  3007. this.links.push( (new Link()).parse(child) );
  3008. break;
  3009. case 'rotate':
  3010. case 'translate':
  3011. case 'matrix':
  3012. this.transforms.push( (new Transform()).parse(child) );
  3013. break;
  3014. default:
  3015. break;
  3016. }
  3017. }
  3018. return this;
  3019. };
  3020. function _source( element ) {
  3021. var id = element.getAttribute( 'id' );
  3022. if ( sources[ id ] != undefined ) {
  3023. return sources[ id ];
  3024. }
  3025. sources[ id ] = ( new Source(id )).parse( element );
  3026. return sources[ id ];
  3027. }
  3028. function _nsResolver( nsPrefix ) {
  3029. if ( nsPrefix === "dae" ) {
  3030. return "http://www.collada.org/2005/11/COLLADASchema";
  3031. }
  3032. return null;
  3033. }
  3034. function _bools( str ) {
  3035. var raw = _strings( str );
  3036. var data = [];
  3037. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3038. data.push( (raw[i] === 'true' || raw[i] === '1') ? true : false );
  3039. }
  3040. return data;
  3041. }
  3042. function _floats( str ) {
  3043. var raw = _strings(str);
  3044. var data = [];
  3045. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3046. data.push( parseFloat( raw[ i ] ) );
  3047. }
  3048. return data;
  3049. }
  3050. function _ints( str ) {
  3051. var raw = _strings( str );
  3052. var data = [];
  3053. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  3054. data.push( parseInt( raw[ i ], 10 ) );
  3055. }
  3056. return data;
  3057. }
  3058. function _strings( str ) {
  3059. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  3060. }
  3061. function _trimString( str ) {
  3062. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  3063. }
  3064. function _attr_as_float( element, name, defaultValue ) {
  3065. if ( element.hasAttribute( name ) ) {
  3066. return parseFloat( element.getAttribute( name ) );
  3067. } else {
  3068. return defaultValue;
  3069. }
  3070. }
  3071. function _attr_as_int( element, name, defaultValue ) {
  3072. if ( element.hasAttribute( name ) ) {
  3073. return parseInt( element.getAttribute( name ), 10) ;
  3074. } else {
  3075. return defaultValue;
  3076. }
  3077. }
  3078. function _attr_as_string( element, name, defaultValue ) {
  3079. if ( element.hasAttribute( name ) ) {
  3080. return element.getAttribute( name );
  3081. } else {
  3082. return defaultValue;
  3083. }
  3084. }
  3085. function _format_float( f, num ) {
  3086. if ( f === undefined ) {
  3087. var s = '0.';
  3088. while ( s.length < num + 2 ) {
  3089. s += '0';
  3090. }
  3091. return s;
  3092. }
  3093. num = num || 2;
  3094. var parts = f.toString().split( '.' );
  3095. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  3096. while ( parts[ 1 ].length < num ) {
  3097. parts[ 1 ] += '0';
  3098. }
  3099. return parts.join( '.' );
  3100. }
  3101. function loadTextureImage ( texture, url ) {
  3102. var loader = new THREE.ImageLoader();
  3103. loader.load( url, function ( image ) {
  3104. texture.image = image;
  3105. texture.needsUpdate = true;
  3106. } );
  3107. }
  3108. function extractDoubleSided( obj, element ) {
  3109. obj.doubleSided = false;
  3110. var node = element.querySelectorAll('extra double_sided')[0];
  3111. if ( node ) {
  3112. if ( node && parseInt( node.textContent, 10 ) === 1 ) {
  3113. obj.doubleSided = true;
  3114. }
  3115. }
  3116. }
  3117. // Up axis conversion
  3118. function setUpConversion() {
  3119. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3120. upConversion = null;
  3121. } else {
  3122. switch ( colladaUp ) {
  3123. case 'X':
  3124. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  3125. break;
  3126. case 'Y':
  3127. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  3128. break;
  3129. case 'Z':
  3130. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  3131. break;
  3132. }
  3133. }
  3134. }
  3135. function fixCoords( data, sign ) {
  3136. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3137. return;
  3138. }
  3139. switch ( upConversion ) {
  3140. case 'XtoY':
  3141. var tmp = data[ 0 ];
  3142. data[ 0 ] = sign * data[ 1 ];
  3143. data[ 1 ] = tmp;
  3144. break;
  3145. case 'XtoZ':
  3146. var tmp = data[ 2 ];
  3147. data[ 2 ] = data[ 1 ];
  3148. data[ 1 ] = data[ 0 ];
  3149. data[ 0 ] = tmp;
  3150. break;
  3151. case 'YtoX':
  3152. var tmp = data[ 0 ];
  3153. data[ 0 ] = data[ 1 ];
  3154. data[ 1 ] = sign * tmp;
  3155. break;
  3156. case 'YtoZ':
  3157. var tmp = data[ 1 ];
  3158. data[ 1 ] = sign * data[ 2 ];
  3159. data[ 2 ] = tmp;
  3160. break;
  3161. case 'ZtoX':
  3162. var tmp = data[ 0 ];
  3163. data[ 0 ] = data[ 1 ];
  3164. data[ 1 ] = data[ 2 ];
  3165. data[ 2 ] = tmp;
  3166. break;
  3167. case 'ZtoY':
  3168. var tmp = data[ 1 ];
  3169. data[ 1 ] = data[ 2 ];
  3170. data[ 2 ] = sign * tmp;
  3171. break;
  3172. }
  3173. }
  3174. function getConvertedTranslation( axis, data ) {
  3175. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  3176. return data;
  3177. }
  3178. switch ( axis ) {
  3179. case 'X':
  3180. data = upConversion === 'XtoY' ? data * -1 : data;
  3181. break;
  3182. case 'Y':
  3183. data = upConversion === 'YtoZ' || upConversion === 'YtoX' ? data * -1 : data;
  3184. break;
  3185. case 'Z':
  3186. data = upConversion === 'ZtoY' ? data * -1 : data ;
  3187. break;
  3188. default:
  3189. break;
  3190. }
  3191. return data;
  3192. }
  3193. function getConvertedVec3( data, offset ) {
  3194. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  3195. fixCoords( arr, -1 );
  3196. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  3197. }
  3198. function getConvertedMat4( data ) {
  3199. if ( options.convertUpAxis ) {
  3200. // First fix rotation and scale
  3201. // Columns first
  3202. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  3203. fixCoords( arr, -1 );
  3204. data[ 0 ] = arr[ 0 ];
  3205. data[ 4 ] = arr[ 1 ];
  3206. data[ 8 ] = arr[ 2 ];
  3207. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  3208. fixCoords( arr, -1 );
  3209. data[ 1 ] = arr[ 0 ];
  3210. data[ 5 ] = arr[ 1 ];
  3211. data[ 9 ] = arr[ 2 ];
  3212. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  3213. fixCoords( arr, -1 );
  3214. data[ 2 ] = arr[ 0 ];
  3215. data[ 6 ] = arr[ 1 ];
  3216. data[ 10 ] = arr[ 2 ];
  3217. // Rows second
  3218. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  3219. fixCoords( arr, -1 );
  3220. data[ 0 ] = arr[ 0 ];
  3221. data[ 1 ] = arr[ 1 ];
  3222. data[ 2 ] = arr[ 2 ];
  3223. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  3224. fixCoords( arr, -1 );
  3225. data[ 4 ] = arr[ 0 ];
  3226. data[ 5 ] = arr[ 1 ];
  3227. data[ 6 ] = arr[ 2 ];
  3228. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  3229. fixCoords( arr, -1 );
  3230. data[ 8 ] = arr[ 0 ];
  3231. data[ 9 ] = arr[ 1 ];
  3232. data[ 10 ] = arr[ 2 ];
  3233. // Now fix translation
  3234. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  3235. fixCoords( arr, -1 );
  3236. data[ 3 ] = arr[ 0 ];
  3237. data[ 7 ] = arr[ 1 ];
  3238. data[ 11 ] = arr[ 2 ];
  3239. }
  3240. return new THREE.Matrix4().set(
  3241. data[0], data[1], data[2], data[3],
  3242. data[4], data[5], data[6], data[7],
  3243. data[8], data[9], data[10], data[11],
  3244. data[12], data[13], data[14], data[15]
  3245. );
  3246. }
  3247. function getConvertedIndex( index ) {
  3248. if ( index > -1 && index < 3 ) {
  3249. var members = [ 'X', 'Y', 'Z' ],
  3250. indices = { X: 0, Y: 1, Z: 2 };
  3251. index = getConvertedMember( members[ index ] );
  3252. index = indices[ index ];
  3253. }
  3254. return index;
  3255. }
  3256. function getConvertedMember( member ) {
  3257. if ( options.convertUpAxis ) {
  3258. switch ( member ) {
  3259. case 'X':
  3260. switch ( upConversion ) {
  3261. case 'XtoY':
  3262. case 'XtoZ':
  3263. case 'YtoX':
  3264. member = 'Y';
  3265. break;
  3266. case 'ZtoX':
  3267. member = 'Z';
  3268. break;
  3269. }
  3270. break;
  3271. case 'Y':
  3272. switch ( upConversion ) {
  3273. case 'XtoY':
  3274. case 'YtoX':
  3275. case 'ZtoX':
  3276. member = 'X';
  3277. break;
  3278. case 'XtoZ':
  3279. case 'YtoZ':
  3280. case 'ZtoY':
  3281. member = 'Z';
  3282. break;
  3283. }
  3284. break;
  3285. case 'Z':
  3286. switch ( upConversion ) {
  3287. case 'XtoZ':
  3288. member = 'X';
  3289. break;
  3290. case 'YtoZ':
  3291. case 'ZtoX':
  3292. case 'ZtoY':
  3293. member = 'Y';
  3294. break;
  3295. }
  3296. break;
  3297. }
  3298. }
  3299. return member;
  3300. }
  3301. return {
  3302. load: load,
  3303. parse: parse,
  3304. setPreferredShading: setPreferredShading,
  3305. applySkin: applySkin,
  3306. geometries : geometries,
  3307. options: options
  3308. };
  3309. };