ColladaLoader.js 99 KB

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