ColladaLoader.js 98 KB

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