ThreeExtras.js 565 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346
  1. <<<<<<< HEAD
  2. /**
  3. * @author alteredq / http://alteredqualia.com/
  4. */
  5. THREE.ColorUtils = {
  6. adjustHSV : function ( color, h, s, v ) {
  7. var hsv = THREE.ColorUtils.__hsv;
  8. THREE.ColorUtils.rgbToHsv( color, hsv );
  9. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  10. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  11. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  12. color.setHSV( hsv.h, hsv.s, hsv.v );
  13. },
  14. // based on MochiKit implementation by Bob Ippolito
  15. rgbToHsv : function ( color, hsv ) {
  16. var r = color.r;
  17. var g = color.g;
  18. var b = color.b;
  19. var max = Math.max( Math.max( r, g ), b );
  20. var min = Math.min( Math.min( r, g ), b );
  21. var hue;
  22. var saturation;
  23. var value = max;
  24. if ( min === max ) {
  25. hue = 0;
  26. saturation = 0;
  27. } else {
  28. var delta = ( max - min );
  29. saturation = delta / max;
  30. if ( r === max ) {
  31. hue = ( g - b ) / delta;
  32. } else if ( g === max ) {
  33. hue = 2 + ( ( b - r ) / delta );
  34. } else {
  35. hue = 4 + ( ( r - g ) / delta );
  36. }
  37. hue /= 6;
  38. if ( hue < 0 ) {
  39. hue += 1;
  40. }
  41. if ( hue > 1 ) {
  42. hue -= 1;
  43. }
  44. }
  45. if ( hsv === undefined ) {
  46. hsv = { h: 0, s: 0, v: 0 };
  47. }
  48. hsv.h = hue;
  49. hsv.s = saturation;
  50. hsv.v = value;
  51. return hsv;
  52. }
  53. };
  54. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  55. * @author mrdoob / http://mrdoob.com/
  56. * @author alteredq / http://alteredqualia.com/
  57. */
  58. THREE.GeometryUtils = {
  59. // Merge two geometries or geometry and geometry from object (using object's transform)
  60. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  61. var matrix, matrixRotation,
  62. vertexOffset = geometry1.vertices.length,
  63. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  64. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  65. vertices1 = geometry1.vertices,
  66. vertices2 = geometry2.vertices,
  67. faces1 = geometry1.faces,
  68. faces2 = geometry2.faces,
  69. uvs1 = geometry1.faceVertexUvs[ 0 ],
  70. uvs2 = geometry2.faceVertexUvs[ 0 ];
  71. var geo1MaterialsMap = {};
  72. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  73. var id = geometry1.materials[ i ].id;
  74. geo1MaterialsMap[ id ] = i;
  75. }
  76. if ( object2 instanceof THREE.Mesh ) {
  77. object2.matrixAutoUpdate && object2.updateMatrix();
  78. matrix = object2.matrix;
  79. matrixRotation = new THREE.Matrix4();
  80. matrixRotation.extractRotation( matrix, object2.scale );
  81. }
  82. // vertices
  83. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  84. var vertex = vertices2[ i ];
  85. var vertexCopy = vertex.clone();
  86. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  87. vertices1.push( vertexCopy );
  88. }
  89. // faces
  90. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  91. var face = faces2[ i ], faceCopy, normal, color,
  92. faceVertexNormals = face.vertexNormals,
  93. faceVertexColors = face.vertexColors;
  94. if ( face instanceof THREE.Face3 ) {
  95. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  96. } else if ( face instanceof THREE.Face4 ) {
  97. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  98. }
  99. faceCopy.normal.copy( face.normal );
  100. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  101. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  102. normal = faceVertexNormals[ j ].clone();
  103. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  104. faceCopy.vertexNormals.push( normal );
  105. }
  106. faceCopy.color.copy( face.color );
  107. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  108. color = faceVertexColors[ j ];
  109. faceCopy.vertexColors.push( color.clone() );
  110. }
  111. if ( face.materialIndex !== undefined ) {
  112. var material2 = geometry2.materials[ face.materialIndex ];
  113. var materialId2 = material2.id;
  114. var materialIndex = geo1MaterialsMap[ materialId2 ];
  115. if ( materialIndex === undefined ) {
  116. materialIndex = geometry1.materials.length;
  117. geo1MaterialsMap[ materialId2 ] = materialIndex;
  118. geometry1.materials.push( material2 );
  119. }
  120. faceCopy.materialIndex = materialIndex;
  121. }
  122. faceCopy.centroid.copy( face.centroid );
  123. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  124. faces1.push( faceCopy );
  125. }
  126. // uvs
  127. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  128. var uv = uvs2[ i ], uvCopy = [];
  129. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  130. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  131. }
  132. uvs1.push( uvCopy );
  133. }
  134. },
  135. clone: function ( geometry ) {
  136. var cloneGeo = new THREE.Geometry();
  137. var i, il;
  138. var vertices = geometry.vertices,
  139. faces = geometry.faces,
  140. uvs = geometry.faceVertexUvs[ 0 ];
  141. // materials
  142. if ( geometry.materials ) {
  143. cloneGeo.materials = geometry.materials.slice();
  144. }
  145. // vertices
  146. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  147. var vertex = vertices[ i ];
  148. cloneGeo.vertices.push( vertex.clone() );
  149. }
  150. // faces
  151. for ( i = 0, il = faces.length; i < il; i ++ ) {
  152. var face = faces[ i ];
  153. cloneGeo.faces.push( face.clone() );
  154. }
  155. // uvs
  156. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  157. var uv = uvs[ i ], uvCopy = [];
  158. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  159. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  160. }
  161. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  162. }
  163. return cloneGeo;
  164. },
  165. // Get random point in triangle (via barycentric coordinates)
  166. // (uniform distribution)
  167. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  168. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  169. var a, b, c,
  170. point = new THREE.Vector3(),
  171. tmp = THREE.GeometryUtils.__v1;
  172. a = THREE.GeometryUtils.random();
  173. b = THREE.GeometryUtils.random();
  174. if ( ( a + b ) > 1 ) {
  175. a = 1 - a;
  176. b = 1 - b;
  177. }
  178. c = 1 - a - b;
  179. point.copy( vectorA );
  180. point.multiplyScalar( a );
  181. tmp.copy( vectorB );
  182. tmp.multiplyScalar( b );
  183. point.addSelf( tmp );
  184. tmp.copy( vectorC );
  185. tmp.multiplyScalar( c );
  186. point.addSelf( tmp );
  187. return point;
  188. },
  189. // Get random point in face (triangle / quad)
  190. // (uniform distribution)
  191. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  192. var vA, vB, vC, vD;
  193. if ( face instanceof THREE.Face3 ) {
  194. vA = geometry.vertices[ face.a ];
  195. vB = geometry.vertices[ face.b ];
  196. vC = geometry.vertices[ face.c ];
  197. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  198. } else if ( face instanceof THREE.Face4 ) {
  199. vA = geometry.vertices[ face.a ];
  200. vB = geometry.vertices[ face.b ];
  201. vC = geometry.vertices[ face.c ];
  202. vD = geometry.vertices[ face.d ];
  203. var area1, area2;
  204. if ( useCachedAreas ) {
  205. if ( face._area1 && face._area2 ) {
  206. area1 = face._area1;
  207. area2 = face._area2;
  208. } else {
  209. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  210. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  211. face._area1 = area1;
  212. face._area2 = area2;
  213. }
  214. } else {
  215. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  216. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  217. }
  218. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  219. if ( r < area1 ) {
  220. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  221. } else {
  222. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  223. }
  224. }
  225. },
  226. // Get uniformly distributed random points in mesh
  227. // - create array with cumulative sums of face areas
  228. // - pick random number from 0 to total area
  229. // - find corresponding place in area array by binary search
  230. // - get random point in face
  231. randomPointsInGeometry: function ( geometry, n ) {
  232. var face, i,
  233. faces = geometry.faces,
  234. vertices = geometry.vertices,
  235. il = faces.length,
  236. totalArea = 0,
  237. cumulativeAreas = [],
  238. vA, vB, vC, vD;
  239. // precompute face areas
  240. for ( i = 0; i < il; i ++ ) {
  241. face = faces[ i ];
  242. if ( face instanceof THREE.Face3 ) {
  243. vA = vertices[ face.a ];
  244. vB = vertices[ face.b ];
  245. vC = vertices[ face.c ];
  246. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  247. } else if ( face instanceof THREE.Face4 ) {
  248. vA = vertices[ face.a ];
  249. vB = vertices[ face.b ];
  250. vC = vertices[ face.c ];
  251. vD = vertices[ face.d ];
  252. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  253. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  254. face._area = face._area1 + face._area2;
  255. }
  256. totalArea += face._area;
  257. cumulativeAreas[ i ] = totalArea;
  258. }
  259. // binary search cumulative areas array
  260. function binarySearchIndices( value ) {
  261. function binarySearch( start, end ) {
  262. // return closest larger index
  263. // if exact number is not found
  264. if ( end < start )
  265. return start;
  266. var mid = start + Math.floor( ( end - start ) / 2 );
  267. if ( cumulativeAreas[ mid ] > value ) {
  268. return binarySearch( start, mid - 1 );
  269. } else if ( cumulativeAreas[ mid ] < value ) {
  270. return binarySearch( mid + 1, end );
  271. } else {
  272. return mid;
  273. }
  274. }
  275. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  276. return result;
  277. }
  278. // pick random face weighted by face area
  279. var r, index,
  280. result = [];
  281. var stats = {};
  282. for ( i = 0; i < n; i ++ ) {
  283. r = THREE.GeometryUtils.random() * totalArea;
  284. index = binarySearchIndices( r );
  285. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  286. if ( ! stats[ index ] ) {
  287. stats[ index ] = 1;
  288. } else {
  289. stats[ index ] += 1;
  290. }
  291. }
  292. return result;
  293. },
  294. // Get triangle area (by Heron's formula)
  295. // http://en.wikipedia.org/wiki/Heron%27s_formula
  296. triangleArea: function ( vectorA, vectorB, vectorC ) {
  297. var s, a, b, c,
  298. tmp = THREE.GeometryUtils.__v1;
  299. tmp.sub( vectorA, vectorB );
  300. a = tmp.length();
  301. tmp.sub( vectorA, vectorC );
  302. b = tmp.length();
  303. tmp.sub( vectorB, vectorC );
  304. c = tmp.length();
  305. s = 0.5 * ( a + b + c );
  306. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  307. },
  308. // Center geometry so that 0,0,0 is in center of bounding box
  309. center: function ( geometry ) {
  310. geometry.computeBoundingBox();
  311. var bb = geometry.boundingBox;
  312. var offset = new THREE.Vector3();
  313. offset.add( bb.min, bb.max );
  314. offset.multiplyScalar( -0.5 );
  315. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  316. geometry.computeBoundingBox();
  317. return offset;
  318. },
  319. // Normalize UVs to be from <0,1>
  320. // (for now just the first set of UVs)
  321. normalizeUVs: function ( geometry ) {
  322. var uvSet = geometry.faceVertexUvs[ 0 ];
  323. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  324. var uvs = uvSet[ i ];
  325. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  326. // texture repeat
  327. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  328. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  329. }
  330. }
  331. },
  332. triangulateQuads: function ( geometry ) {
  333. var i, il, j, jl;
  334. var faces = [];
  335. var faceUvs = [];
  336. var faceVertexUvs = [];
  337. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  338. faceUvs[ i ] = [];
  339. }
  340. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  341. faceVertexUvs[ i ] = [];
  342. }
  343. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  344. var face = geometry.faces[ i ];
  345. if ( face instanceof THREE.Face4 ) {
  346. var a = face.a;
  347. var b = face.b;
  348. var c = face.c;
  349. var d = face.d;
  350. var triA = new THREE.Face3();
  351. var triB = new THREE.Face3();
  352. triA.color.copy( face.color );
  353. triB.color.copy( face.color );
  354. triA.materialIndex = face.materialIndex;
  355. triB.materialIndex = face.materialIndex;
  356. triA.a = a;
  357. triA.b = b;
  358. triA.c = d;
  359. triB.a = b;
  360. triB.b = c;
  361. triB.c = d;
  362. if ( face.vertexColors.length === 4 ) {
  363. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  364. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  365. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  366. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  367. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  368. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  369. }
  370. faces.push( triA, triB );
  371. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  372. if ( geometry.faceVertexUvs[ j ].length ) {
  373. var uvs = geometry.faceVertexUvs[ j ][ i ];
  374. var uvA = uvs[ 0 ];
  375. var uvB = uvs[ 1 ];
  376. var uvC = uvs[ 2 ];
  377. var uvD = uvs[ 3 ];
  378. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  379. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  380. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  381. }
  382. }
  383. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  384. if ( geometry.faceUvs[ j ].length ) {
  385. var faceUv = geometry.faceUvs[ j ][ i ];
  386. faceUvs[ j ].push( faceUv, faceUv );
  387. }
  388. }
  389. } else {
  390. faces.push( face );
  391. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  392. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  393. }
  394. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  395. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  396. }
  397. }
  398. }
  399. geometry.faces = faces;
  400. geometry.faceUvs = faceUvs;
  401. geometry.faceVertexUvs = faceVertexUvs;
  402. geometry.computeCentroids();
  403. geometry.computeFaceNormals();
  404. geometry.computeVertexNormals();
  405. if ( geometry.hasTangents ) geometry.computeTangents();
  406. },
  407. // Make all faces use unique vertices
  408. // so that each face can be separated from others
  409. explode: function( geometry ) {
  410. var vertices = [];
  411. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  412. var n = vertices.length;
  413. var face = geometry.faces[ i ];
  414. if ( face instanceof THREE.Face4 ) {
  415. var a = face.a;
  416. var b = face.b;
  417. var c = face.c;
  418. var d = face.d;
  419. var va = geometry.vertices[ a ];
  420. var vb = geometry.vertices[ b ];
  421. var vc = geometry.vertices[ c ];
  422. var vd = geometry.vertices[ d ];
  423. vertices.push( va.clone() );
  424. vertices.push( vb.clone() );
  425. vertices.push( vc.clone() );
  426. vertices.push( vd.clone() );
  427. face.a = n;
  428. face.b = n + 1;
  429. face.c = n + 2;
  430. face.d = n + 3;
  431. } else {
  432. var a = face.a;
  433. var b = face.b;
  434. var c = face.c;
  435. var va = geometry.vertices[ a ];
  436. var vb = geometry.vertices[ b ];
  437. var vc = geometry.vertices[ c ];
  438. vertices.push( va.clone() );
  439. vertices.push( vb.clone() );
  440. vertices.push( vc.clone() );
  441. face.a = n;
  442. face.b = n + 1;
  443. face.c = n + 2;
  444. }
  445. }
  446. geometry.vertices = vertices;
  447. delete geometry.__tmpVertices;
  448. },
  449. // Break faces with edges longer than maxEdgeLength
  450. // - not recursive
  451. tessellate: function ( geometry, maxEdgeLength ) {
  452. var i, il, face,
  453. a, b, c, d,
  454. va, vb, vc, vd,
  455. dab, dbc, dac, dcd, dad,
  456. m, m1, m2,
  457. vm, vm1, vm2,
  458. vnm, vnm1, vnm2,
  459. vcm, vcm1, vcm2,
  460. triA, triB,
  461. quadA, quadB,
  462. edge;
  463. var faces = [];
  464. var faceVertexUvs = [];
  465. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  466. faceVertexUvs[ i ] = [];
  467. }
  468. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  469. face = geometry.faces[ i ];
  470. if ( face instanceof THREE.Face3 ) {
  471. a = face.a;
  472. b = face.b;
  473. c = face.c;
  474. va = geometry.vertices[ a ];
  475. vb = geometry.vertices[ b ];
  476. vc = geometry.vertices[ c ];
  477. dab = va.distanceTo( vb );
  478. dbc = vb.distanceTo( vc );
  479. dac = va.distanceTo( vc );
  480. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  481. m = geometry.vertices.length;
  482. triA = face.clone();
  483. triB = face.clone();
  484. if ( dab >= dbc && dab >= dac ) {
  485. vm = va.clone();
  486. vm.lerpSelf( vb, 0.5 );
  487. triA.a = a;
  488. triA.b = m;
  489. triA.c = c;
  490. triB.a = m;
  491. triB.b = b;
  492. triB.c = c;
  493. if ( face.vertexNormals.length === 3 ) {
  494. vnm = face.vertexNormals[ 0 ].clone();
  495. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  496. triA.vertexNormals[ 1 ].copy( vnm );
  497. triB.vertexNormals[ 0 ].copy( vnm );
  498. }
  499. if ( face.vertexColors.length === 3 ) {
  500. vcm = face.vertexColors[ 0 ].clone();
  501. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  502. triA.vertexColors[ 1 ].copy( vcm );
  503. triB.vertexColors[ 0 ].copy( vcm );
  504. }
  505. edge = 0;
  506. } else if ( dbc >= dab && dbc >= dac ) {
  507. vm = vb.clone();
  508. vm.lerpSelf( vc, 0.5 );
  509. triA.a = a;
  510. triA.b = b;
  511. triA.c = m;
  512. triB.a = m;
  513. triB.b = c;
  514. triB.c = a;
  515. if ( face.vertexNormals.length === 3 ) {
  516. vnm = face.vertexNormals[ 1 ].clone();
  517. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  518. triA.vertexNormals[ 2 ].copy( vnm );
  519. triB.vertexNormals[ 0 ].copy( vnm );
  520. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  521. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  522. }
  523. if ( face.vertexColors.length === 3 ) {
  524. vcm = face.vertexColors[ 1 ].clone();
  525. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  526. triA.vertexColors[ 2 ].copy( vcm );
  527. triB.vertexColors[ 0 ].copy( vcm );
  528. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  529. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  530. }
  531. edge = 1;
  532. } else {
  533. vm = va.clone();
  534. vm.lerpSelf( vc, 0.5 );
  535. triA.a = a;
  536. triA.b = b;
  537. triA.c = m;
  538. triB.a = m;
  539. triB.b = b;
  540. triB.c = c;
  541. if ( face.vertexNormals.length === 3 ) {
  542. vnm = face.vertexNormals[ 0 ].clone();
  543. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  544. triA.vertexNormals[ 2 ].copy( vnm );
  545. triB.vertexNormals[ 0 ].copy( vnm );
  546. }
  547. if ( face.vertexColors.length === 3 ) {
  548. vcm = face.vertexColors[ 0 ].clone();
  549. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  550. triA.vertexColors[ 2 ].copy( vcm );
  551. triB.vertexColors[ 0 ].copy( vcm );
  552. }
  553. edge = 2;
  554. }
  555. faces.push( triA, triB );
  556. geometry.vertices.push( vm );
  557. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  558. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  559. if ( geometry.faceVertexUvs[ j ].length ) {
  560. uvs = geometry.faceVertexUvs[ j ][ i ];
  561. uvA = uvs[ 0 ];
  562. uvB = uvs[ 1 ];
  563. uvC = uvs[ 2 ];
  564. // AB
  565. if ( edge === 0 ) {
  566. uvM = uvA.clone();
  567. uvM.lerpSelf( uvB, 0.5 );
  568. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  569. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  570. // BC
  571. } else if ( edge === 1 ) {
  572. uvM = uvB.clone();
  573. uvM.lerpSelf( uvC, 0.5 );
  574. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  575. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  576. // AC
  577. } else {
  578. uvM = uvA.clone();
  579. uvM.lerpSelf( uvC, 0.5 );
  580. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  581. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  582. }
  583. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  584. }
  585. }
  586. } else {
  587. faces.push( face );
  588. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  589. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  590. }
  591. }
  592. } else {
  593. a = face.a;
  594. b = face.b;
  595. c = face.c;
  596. d = face.d;
  597. va = geometry.vertices[ a ];
  598. vb = geometry.vertices[ b ];
  599. vc = geometry.vertices[ c ];
  600. vd = geometry.vertices[ d ];
  601. dab = va.distanceTo( vb );
  602. dbc = vb.distanceTo( vc );
  603. dcd = vc.distanceTo( vd );
  604. dad = va.distanceTo( vd );
  605. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  606. m1 = geometry.vertices.length;
  607. m2 = geometry.vertices.length + 1;
  608. quadA = face.clone();
  609. quadB = face.clone();
  610. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  611. vm1 = va.clone();
  612. vm1.lerpSelf( vb, 0.5 );
  613. vm2 = vc.clone();
  614. vm2.lerpSelf( vd, 0.5 );
  615. quadA.a = a;
  616. quadA.b = m1;
  617. quadA.c = m2;
  618. quadA.d = d;
  619. quadB.a = m1;
  620. quadB.b = b;
  621. quadB.c = c;
  622. quadB.d = m2;
  623. if ( face.vertexNormals.length === 4 ) {
  624. vnm1 = face.vertexNormals[ 0 ].clone();
  625. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  626. vnm2 = face.vertexNormals[ 2 ].clone();
  627. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  628. quadA.vertexNormals[ 1 ].copy( vnm1 );
  629. quadA.vertexNormals[ 2 ].copy( vnm2 );
  630. quadB.vertexNormals[ 0 ].copy( vnm1 );
  631. quadB.vertexNormals[ 3 ].copy( vnm2 );
  632. }
  633. if ( face.vertexColors.length === 4 ) {
  634. vcm1 = face.vertexColors[ 0 ].clone();
  635. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  636. vcm2 = face.vertexColors[ 2 ].clone();
  637. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  638. quadA.vertexColors[ 1 ].copy( vcm1 );
  639. quadA.vertexColors[ 2 ].copy( vcm2 );
  640. quadB.vertexColors[ 0 ].copy( vcm1 );
  641. quadB.vertexColors[ 3 ].copy( vcm2 );
  642. }
  643. edge = 0;
  644. } else {
  645. vm1 = vb.clone();
  646. vm1.lerpSelf( vc, 0.5 );
  647. vm2 = vd.clone();
  648. vm2.lerpSelf( va, 0.5 );
  649. quadA.a = a;
  650. quadA.b = b;
  651. quadA.c = m1;
  652. quadA.d = m2;
  653. quadB.a = m2;
  654. quadB.b = m1;
  655. quadB.c = c;
  656. quadB.d = d;
  657. if ( face.vertexNormals.length === 4 ) {
  658. vnm1 = face.vertexNormals[ 1 ].clone();
  659. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  660. vnm2 = face.vertexNormals[ 3 ].clone();
  661. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  662. quadA.vertexNormals[ 2 ].copy( vnm1 );
  663. quadA.vertexNormals[ 3 ].copy( vnm2 );
  664. quadB.vertexNormals[ 0 ].copy( vnm2 );
  665. quadB.vertexNormals[ 1 ].copy( vnm1 );
  666. }
  667. if ( face.vertexColors.length === 4 ) {
  668. vcm1 = face.vertexColors[ 1 ].clone();
  669. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  670. vcm2 = face.vertexColors[ 3 ].clone();
  671. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  672. quadA.vertexColors[ 2 ].copy( vcm1 );
  673. quadA.vertexColors[ 3 ].copy( vcm2 );
  674. quadB.vertexColors[ 0 ].copy( vcm2 );
  675. quadB.vertexColors[ 1 ].copy( vcm1 );
  676. }
  677. edge = 1;
  678. }
  679. faces.push( quadA, quadB );
  680. geometry.vertices.push( vm1, vm2 );
  681. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  682. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  683. if ( geometry.faceVertexUvs[ j ].length ) {
  684. uvs = geometry.faceVertexUvs[ j ][ i ];
  685. uvA = uvs[ 0 ];
  686. uvB = uvs[ 1 ];
  687. uvC = uvs[ 2 ];
  688. uvD = uvs[ 3 ];
  689. // AB + CD
  690. if ( edge === 0 ) {
  691. uvM1 = uvA.clone();
  692. uvM1.lerpSelf( uvB, 0.5 );
  693. uvM2 = uvC.clone();
  694. uvM2.lerpSelf( uvD, 0.5 );
  695. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  696. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  697. // BC + AD
  698. } else {
  699. uvM1 = uvB.clone();
  700. uvM1.lerpSelf( uvC, 0.5 );
  701. uvM2 = uvD.clone();
  702. uvM2.lerpSelf( uvA, 0.5 );
  703. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  704. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  705. }
  706. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  707. }
  708. }
  709. } else {
  710. faces.push( face );
  711. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  712. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  713. }
  714. }
  715. }
  716. }
  717. geometry.faces = faces;
  718. geometry.faceVertexUvs = faceVertexUvs;
  719. }
  720. };
  721. THREE.GeometryUtils.random = THREE.Math.random16;
  722. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  723. /**
  724. * @author alteredq / http://alteredqualia.com/
  725. * @author mrdoob / http://mrdoob.com/
  726. */
  727. THREE.ImageUtils = {
  728. crossOrigin: 'anonymous',
  729. loadTexture: function ( path, mapping, callback ) {
  730. var image = new Image(), texture = new THREE.Texture( image, mapping );
  731. image.onload = function () { texture.needsUpdate = true; if ( callback ) callback( this ); };
  732. image.crossOrigin = this.crossOrigin;
  733. image.src = path;
  734. return texture;
  735. },
  736. loadTextureCube: function ( array, mapping, callback ) {
  737. var i, l, images = [], texture = new THREE.Texture( images, mapping );
  738. images.loadCount = 0;
  739. for ( i = 0, l = array.length; i < l; ++ i ) {
  740. images[ i ] = new Image();
  741. images[ i ].onload = function () {
  742. images.loadCount += 1;
  743. if ( images.loadCount === 6 ) texture.needsUpdate = true;
  744. if ( callback ) callback( this );
  745. };
  746. images[ i ].crossOrigin = this.crossOrigin;
  747. images[ i ].src = array[ i ];
  748. }
  749. return texture;
  750. },
  751. getNormalMap: function ( image, depth ) {
  752. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  753. var cross = function ( a, b ) {
  754. return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ];
  755. }
  756. var subtract = function ( a, b ) {
  757. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  758. }
  759. var normalize = function ( a ) {
  760. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  761. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  762. }
  763. depth = depth | 1;
  764. var width = image.width;
  765. var height = image.height;
  766. var canvas = document.createElement( 'canvas' );
  767. canvas.width = width;
  768. canvas.height = height;
  769. var context = canvas.getContext( '2d' );
  770. context.drawImage( image, 0, 0 );
  771. var data = context.getImageData( 0, 0, width, height ).data;
  772. var imageData = context.createImageData( width, height );
  773. var output = imageData.data;
  774. for ( var x = 0; x < width; x ++ ) {
  775. for ( var y = 1; y < height; y ++ ) {
  776. var ly = y - 1 < 0 ? height - 1 : y - 1;
  777. var uy = ( y + 1 ) % height;
  778. var lx = x - 1 < 0 ? width - 1 : x - 1;
  779. var ux = ( x + 1 ) % width;
  780. var points = [];
  781. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  782. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  783. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  784. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  785. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  786. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  787. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  788. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  789. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  790. var normals = [];
  791. var num_points = points.length;
  792. for ( var i = 0; i < num_points; i ++ ) {
  793. var v1 = points[ i ];
  794. var v2 = points[ ( i + 1 ) % num_points ];
  795. v1 = subtract( v1, origin );
  796. v2 = subtract( v2, origin );
  797. normals.push( normalize( cross( v1, v2 ) ) );
  798. }
  799. var normal = [ 0, 0, 0 ];
  800. for ( var i = 0; i < normals.length; i ++ ) {
  801. normal[ 0 ] += normals[ i ][ 0 ];
  802. normal[ 1 ] += normals[ i ][ 1 ];
  803. normal[ 2 ] += normals[ i ][ 2 ];
  804. }
  805. normal[ 0 ] /= normals.length;
  806. normal[ 1 ] /= normals.length;
  807. normal[ 2 ] /= normals.length;
  808. var idx = ( y * width + x ) * 4;
  809. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  810. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 / 2.0 ) * 255 ) | 0;
  811. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  812. output[ idx + 3 ] = 255;
  813. }
  814. }
  815. context.putImageData( imageData, 0, 0 );
  816. return canvas;
  817. },
  818. generateDataTexture: function ( width, height, color ) {
  819. var size = width * height;
  820. var data = new Uint8Array( 3 * size );
  821. var r = Math.floor( color.r * 255 );
  822. var g = Math.floor( color.g * 255 );
  823. var b = Math.floor( color.b * 255 );
  824. for ( var i = 0; i < size; i ++ ) {
  825. data[ i * 3 ] = r;
  826. data[ i * 3 + 1 ] = g;
  827. data[ i * 3 + 2 ] = b;
  828. }
  829. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  830. texture.needsUpdate = true;
  831. return texture;
  832. }
  833. };
  834. /**
  835. * @author alteredq / http://alteredqualia.com/
  836. */
  837. THREE.SceneUtils = {
  838. showHierarchy : function ( root, visible ) {
  839. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  840. },
  841. traverseHierarchy : function ( root, callback ) {
  842. var n, i, l = root.children.length;
  843. for ( i = 0; i < l; i ++ ) {
  844. n = root.children[ i ];
  845. callback( n );
  846. THREE.SceneUtils.traverseHierarchy( n, callback );
  847. }
  848. },
  849. createMultiMaterialObject : function ( geometry, materials ) {
  850. var i, il = materials.length,
  851. group = new THREE.Object3D();
  852. for ( i = 0; i < il; i ++ ) {
  853. var object = new THREE.Mesh( geometry, materials[ i ] );
  854. group.add( object );
  855. }
  856. return group;
  857. },
  858. cloneObject: function ( source ) {
  859. var object;
  860. // subclass specific properties
  861. // (must process in order from more specific subclasses to more abstract classes)
  862. if ( source instanceof THREE.MorphAnimMesh ) {
  863. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  864. object.duration = source.duration;
  865. object.mirroredLoop = source.mirroredLoop;
  866. object.time = source.time;
  867. object.lastKeyframe = source.lastKeyframe;
  868. object.currentKeyframe = source.currentKeyframe;
  869. object.direction = source.direction;
  870. object.directionBackwards = source.directionBackwards;
  871. } else if ( source instanceof THREE.SkinnedMesh ) {
  872. object = new THREE.SkinnedMesh( source.geometry, source.material );
  873. } else if ( source instanceof THREE.Mesh ) {
  874. object = new THREE.Mesh( source.geometry, source.material );
  875. } else if ( source instanceof THREE.Line ) {
  876. object = new THREE.Line( source.geometry, source.material, source.type );
  877. } else if ( source instanceof THREE.Ribbon ) {
  878. object = new THREE.Ribbon( source.geometry, source.material );
  879. } else if ( source instanceof THREE.ParticleSystem ) {
  880. object = new THREE.ParticleSystem( source.geometry, source.material );
  881. object.sortParticles = source.sortParticles;
  882. } else if ( source instanceof THREE.Particle ) {
  883. object = new THREE.Particle( source.material );
  884. } else if ( source instanceof THREE.Sprite ) {
  885. object = new THREE.Sprite( {} );
  886. object.color.copy( source.color );
  887. object.map = source.map;
  888. object.blending = source.blending;
  889. object.useScreenCoordinates = source.useScreenCoordinates;
  890. object.mergeWith3D = source.mergeWith3D;
  891. object.affectedByDistance = source.affectedByDistance;
  892. object.scaleByViewport = source.scaleByViewport;
  893. object.alignment = source.alignment;
  894. object.rotation3d.copy( source.rotation3d );
  895. object.rotation = source.rotation;
  896. object.opacity = source.opacity;
  897. object.uvOffset.copy( source.uvOffset );
  898. object.uvScale.copy( source.uvScale);
  899. } else if ( source instanceof THREE.LOD ) {
  900. object = new THREE.LOD();
  901. } else if ( source instanceof THREE.MarchingCubes ) {
  902. object = new THREE.MarchingCubes( source.resolution, source.material );
  903. object.field.set( source.field );
  904. object.isolation = source.isolation;
  905. } else if ( source instanceof THREE.Object3D ) {
  906. object = new THREE.Object3D();
  907. }
  908. // base class properties
  909. object.name = source.name;
  910. object.parent = source.parent;
  911. object.up.copy( source.up );
  912. object.position.copy( source.position );
  913. // because of Sprite madness
  914. if ( object.rotation instanceof THREE.Vector3 )
  915. object.rotation.copy( source.rotation );
  916. object.eulerOrder = source.eulerOrder;
  917. object.scale.copy( source.scale );
  918. object.dynamic = source.dynamic;
  919. object.doubleSided = source.doubleSided;
  920. object.flipSided = source.flipSided;
  921. object.renderDepth = source.renderDepth;
  922. object.rotationAutoUpdate = source.rotationAutoUpdate;
  923. object.matrix.copy( source.matrix );
  924. object.matrixWorld.copy( source.matrixWorld );
  925. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  926. object.matrixAutoUpdate = source.matrixAutoUpdate;
  927. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  928. object.quaternion.copy( source.quaternion );
  929. object.useQuaternion = source.useQuaternion;
  930. object.boundRadius = source.boundRadius;
  931. object.boundRadiusScale = source.boundRadiusScale;
  932. object.visible = source.visible;
  933. object.castShadow = source.castShadow;
  934. object.receiveShadow = source.receiveShadow;
  935. object.frustumCulled = source.frustumCulled;
  936. // children
  937. for ( var i = 0; i < source.children.length; i ++ ) {
  938. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  939. object.children[ i ] = child;
  940. child.parent = object;
  941. }
  942. // LODs need to be patched separately to use cloned children
  943. if ( source instanceof THREE.LOD ) {
  944. for ( var i = 0; i < source.LODs.length; i ++ ) {
  945. var lod = source.LODs[ i ];
  946. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  947. }
  948. }
  949. return object;
  950. },
  951. detach : function ( child, parent, scene ) {
  952. child.applyMatrix( parent.matrixWorld );
  953. parent.remove( child );
  954. scene.add( child );
  955. },
  956. attach: function ( child, scene, parent ) {
  957. var matrixWorldInverse = new THREE.Matrix4();
  958. matrixWorldInverse.getInverse( parent.matrixWorld );
  959. child.applyMatrix( matrixWorldInverse );
  960. scene.remove( child );
  961. parent.add( child );
  962. }
  963. };
  964. /**
  965. * @author alteredq / http://alteredqualia.com/
  966. * @author mr.doob / http://mrdoob.com/
  967. *
  968. * ShaderUtils currently contains:
  969. *
  970. * fresnel
  971. * normal
  972. * cube
  973. *
  974. */
  975. if ( THREE.WebGLRenderer ) {
  976. THREE.ShaderUtils = {
  977. lib: {
  978. /* -------------------------------------------------------------------------
  979. // Fresnel shader
  980. // - based on Nvidia Cg tutorial
  981. ------------------------------------------------------------------------- */
  982. 'fresnel': {
  983. uniforms: {
  984. "mRefractionRatio": { type: "f", value: 1.02 },
  985. "mFresnelBias": { type: "f", value: 0.1 },
  986. "mFresnelPower": { type: "f", value: 2.0 },
  987. "mFresnelScale": { type: "f", value: 1.0 },
  988. "tCube": { type: "t", value: 1, texture: null }
  989. },
  990. fragmentShader: [
  991. "uniform samplerCube tCube;",
  992. "varying vec3 vReflect;",
  993. "varying vec3 vRefract[3];",
  994. "varying float vReflectionFactor;",
  995. "void main() {",
  996. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  997. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  998. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  999. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  1000. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  1001. "refractedColor.a = 1.0;",
  1002. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  1003. "}"
  1004. ].join("\n"),
  1005. vertexShader: [
  1006. "uniform float mRefractionRatio;",
  1007. "uniform float mFresnelBias;",
  1008. "uniform float mFresnelScale;",
  1009. "uniform float mFresnelPower;",
  1010. "varying vec3 vReflect;",
  1011. "varying vec3 vRefract[3];",
  1012. "varying float vReflectionFactor;",
  1013. "void main() {",
  1014. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1015. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  1016. "vec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );",
  1017. "vec3 I = mPosition.xyz - cameraPosition;",
  1018. "vReflect = reflect( I, nWorld );",
  1019. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  1020. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  1021. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  1022. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  1023. "gl_Position = projectionMatrix * mvPosition;",
  1024. "}"
  1025. ].join("\n")
  1026. },
  1027. /* -------------------------------------------------------------------------
  1028. // Normal map shader
  1029. // - Blinn-Phong
  1030. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  1031. // - point and directional lights (use with "lights: true" material option)
  1032. ------------------------------------------------------------------------- */
  1033. 'normal' : {
  1034. uniforms: THREE.UniformsUtils.merge( [
  1035. THREE.UniformsLib[ "fog" ],
  1036. THREE.UniformsLib[ "lights" ],
  1037. THREE.UniformsLib[ "shadowmap" ],
  1038. {
  1039. "enableAO" : { type: "i", value: 0 },
  1040. "enableDiffuse" : { type: "i", value: 0 },
  1041. "enableSpecular" : { type: "i", value: 0 },
  1042. "enableReflection": { type: "i", value: 0 },
  1043. "tDiffuse" : { type: "t", value: 0, texture: null },
  1044. "tCube" : { type: "t", value: 1, texture: null },
  1045. "tNormal" : { type: "t", value: 2, texture: null },
  1046. "tSpecular" : { type: "t", value: 3, texture: null },
  1047. "tAO" : { type: "t", value: 4, texture: null },
  1048. "tDisplacement": { type: "t", value: 5, texture: null },
  1049. "uNormalScale": { type: "f", value: 1.0 },
  1050. "uDisplacementBias": { type: "f", value: 0.0 },
  1051. "uDisplacementScale": { type: "f", value: 1.0 },
  1052. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  1053. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  1054. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  1055. "uShininess": { type: "f", value: 30 },
  1056. "uOpacity": { type: "f", value: 1 },
  1057. "uReflectivity": { type: "f", value: 0.5 },
  1058. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  1059. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  1060. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  1061. }
  1062. ] ),
  1063. fragmentShader: [
  1064. "uniform vec3 uAmbientColor;",
  1065. "uniform vec3 uDiffuseColor;",
  1066. "uniform vec3 uSpecularColor;",
  1067. "uniform float uShininess;",
  1068. "uniform float uOpacity;",
  1069. "uniform bool enableDiffuse;",
  1070. "uniform bool enableSpecular;",
  1071. "uniform bool enableAO;",
  1072. "uniform bool enableReflection;",
  1073. "uniform sampler2D tDiffuse;",
  1074. "uniform sampler2D tNormal;",
  1075. "uniform sampler2D tSpecular;",
  1076. "uniform sampler2D tAO;",
  1077. "uniform samplerCube tCube;",
  1078. "uniform float uNormalScale;",
  1079. "uniform float uReflectivity;",
  1080. "varying vec3 vTangent;",
  1081. "varying vec3 vBinormal;",
  1082. "varying vec3 vNormal;",
  1083. "varying vec2 vUv;",
  1084. "uniform vec3 ambientLightColor;",
  1085. "#if MAX_DIR_LIGHTS > 0",
  1086. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  1087. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  1088. "#endif",
  1089. "#if MAX_POINT_LIGHTS > 0",
  1090. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  1091. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  1092. "#endif",
  1093. "#ifdef WRAP_AROUND",
  1094. "uniform vec3 wrapRGB;",
  1095. "#endif",
  1096. "varying vec3 vViewPosition;",
  1097. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  1098. THREE.ShaderChunk[ "fog_pars_fragment" ],
  1099. "void main() {",
  1100. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  1101. "vec3 specularTex = vec3( 1.0 );",
  1102. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  1103. "normalTex.xy *= uNormalScale;",
  1104. "normalTex = normalize( normalTex );",
  1105. "if( enableDiffuse ) {",
  1106. "#ifdef GAMMA_INPUT",
  1107. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  1108. "texelColor.xyz *= texelColor.xyz;",
  1109. "gl_FragColor = gl_FragColor * texelColor;",
  1110. "#else",
  1111. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  1112. "#endif",
  1113. "}",
  1114. "if( enableAO ) {",
  1115. "#ifdef GAMMA_INPUT",
  1116. "vec4 aoColor = texture2D( tAO, vUv );",
  1117. "aoColor.xyz *= aoColor.xyz;",
  1118. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  1119. "#else",
  1120. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  1121. "#endif",
  1122. "}",
  1123. "if( enableSpecular )",
  1124. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  1125. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  1126. "vec3 finalNormal = tsb * normalTex;",
  1127. "vec3 normal = normalize( finalNormal );",
  1128. "vec3 viewPosition = normalize( vViewPosition );",
  1129. // point lights
  1130. "#if MAX_POINT_LIGHTS > 0",
  1131. "vec3 pointDiffuse = vec3( 0.0 );",
  1132. "vec3 pointSpecular = vec3( 0.0 );",
  1133. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  1134. "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
  1135. "float pointDistance = vPointLight[ i ].w;",
  1136. // diffuse
  1137. "#ifdef WRAP_AROUND",
  1138. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  1139. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  1140. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  1141. "#else",
  1142. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  1143. "#endif",
  1144. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  1145. // specular
  1146. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  1147. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  1148. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  1149. "#ifdef PHYSICALLY_BASED_SHADING",
  1150. // 2.0 => 2.0001 is hack to work around ANGLE bug
  1151. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  1152. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  1153. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  1154. "#else",
  1155. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  1156. "#endif",
  1157. "}",
  1158. "#endif",
  1159. // directional lights
  1160. "#if MAX_DIR_LIGHTS > 0",
  1161. "vec3 dirDiffuse = vec3( 0.0 );",
  1162. "vec3 dirSpecular = vec3( 0.0 );",
  1163. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  1164. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  1165. "vec3 dirVector = normalize( lDirection.xyz );",
  1166. // diffuse
  1167. "#ifdef WRAP_AROUND",
  1168. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  1169. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  1170. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  1171. "#else",
  1172. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  1173. "#endif",
  1174. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  1175. // specular
  1176. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  1177. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  1178. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  1179. "#ifdef PHYSICALLY_BASED_SHADING",
  1180. // 2.0 => 2.0001 is hack to work around ANGLE bug
  1181. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  1182. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  1183. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  1184. "#else",
  1185. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  1186. "#endif",
  1187. "}",
  1188. "#endif",
  1189. // all lights contribution summation
  1190. "vec3 totalDiffuse = vec3( 0.0 );",
  1191. "vec3 totalSpecular = vec3( 0.0 );",
  1192. "#if MAX_DIR_LIGHTS > 0",
  1193. "totalDiffuse += dirDiffuse;",
  1194. "totalSpecular += dirSpecular;",
  1195. "#endif",
  1196. "#if MAX_POINT_LIGHTS > 0",
  1197. "totalDiffuse += pointDiffuse;",
  1198. "totalSpecular += pointSpecular;",
  1199. "#endif",
  1200. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor) + totalSpecular;",
  1201. "if ( enableReflection ) {",
  1202. "vec3 wPos = cameraPosition - vViewPosition;",
  1203. "vec3 vReflect = reflect( normalize( wPos ), normal );",
  1204. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  1205. "#ifdef GAMMA_INPUT",
  1206. "cubeColor.xyz *= cubeColor.xyz;",
  1207. "#endif",
  1208. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  1209. "}",
  1210. THREE.ShaderChunk[ "shadowmap_fragment" ],
  1211. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  1212. THREE.ShaderChunk[ "fog_fragment" ],
  1213. "}"
  1214. ].join("\n"),
  1215. vertexShader: [
  1216. "attribute vec4 tangent;",
  1217. "uniform vec2 uOffset;",
  1218. "uniform vec2 uRepeat;",
  1219. "#ifdef VERTEX_TEXTURES",
  1220. "uniform sampler2D tDisplacement;",
  1221. "uniform float uDisplacementScale;",
  1222. "uniform float uDisplacementBias;",
  1223. "#endif",
  1224. "varying vec3 vTangent;",
  1225. "varying vec3 vBinormal;",
  1226. "varying vec3 vNormal;",
  1227. "varying vec2 vUv;",
  1228. "#if MAX_POINT_LIGHTS > 0",
  1229. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  1230. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  1231. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  1232. "#endif",
  1233. "varying vec3 vViewPosition;",
  1234. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  1235. "void main() {",
  1236. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1237. "vViewPosition = -mvPosition.xyz;",
  1238. // normal, tangent and binormal vectors
  1239. "vNormal = normalMatrix * normal;",
  1240. "vTangent = normalMatrix * tangent.xyz;",
  1241. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  1242. "vUv = uv * uRepeat + uOffset;",
  1243. // point lights
  1244. "#if MAX_POINT_LIGHTS > 0",
  1245. "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",
  1246. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  1247. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  1248. "float lDistance = 1.0;",
  1249. "if ( pointLightDistance[ i ] > 0.0 )",
  1250. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  1251. "lVector = normalize( lVector );",
  1252. "vPointLight[ i ] = vec4( lVector, lDistance );",
  1253. "}",
  1254. "#endif",
  1255. // displacement mapping
  1256. "#ifdef VERTEX_TEXTURES",
  1257. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  1258. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  1259. "vec4 displacedPosition = vec4( normalize( vNormal.xyz ) * df, 0.0 ) + mvPosition;",
  1260. "gl_Position = projectionMatrix * displacedPosition;",
  1261. "#else",
  1262. "gl_Position = projectionMatrix * mvPosition;",
  1263. "#endif",
  1264. THREE.ShaderChunk[ "shadowmap_vertex" ],
  1265. "}"
  1266. ].join("\n")
  1267. },
  1268. /* -------------------------------------------------------------------------
  1269. // Cube map shader
  1270. ------------------------------------------------------------------------- */
  1271. 'cube': {
  1272. uniforms: { "tCube": { type: "t", value: 1, texture: null },
  1273. "tFlip": { type: "f", value: -1 } },
  1274. vertexShader: [
  1275. "varying vec3 vViewPosition;",
  1276. "void main() {",
  1277. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  1278. "vViewPosition = cameraPosition - mPosition.xyz;",
  1279. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  1280. "}"
  1281. ].join("\n"),
  1282. fragmentShader: [
  1283. "uniform samplerCube tCube;",
  1284. "uniform float tFlip;",
  1285. "varying vec3 vViewPosition;",
  1286. "void main() {",
  1287. "vec3 wPos = cameraPosition - vViewPosition;",
  1288. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  1289. "}"
  1290. ].join("\n")
  1291. }
  1292. }
  1293. };
  1294. };/**
  1295. * @author alteredq / http://alteredqualia.com/
  1296. */
  1297. THREE.BufferGeometry = function () {
  1298. this.id = THREE.GeometryCount ++;
  1299. // GL buffers
  1300. this.vertexIndexBuffer = null;
  1301. this.vertexPositionBuffer = null;
  1302. this.vertexNormalBuffer = null;
  1303. this.vertexUvBuffer = null;
  1304. this.vertexColorBuffer = null;
  1305. // typed arrays (kept only if dynamic flag is set)
  1306. this.vertexIndexArray = null;
  1307. this.vertexPositionArray = null;
  1308. this.vertexNormalArray = null;
  1309. this.vertexUvArray = null;
  1310. this.vertexColorArray = null;
  1311. this.dynamic = false;
  1312. // boundings
  1313. this.boundingBox = null;
  1314. this.boundingSphere = null;
  1315. // for compatibility
  1316. this.morphTargets = [];
  1317. };
  1318. THREE.BufferGeometry.prototype = {
  1319. constructor : THREE.BufferGeometry,
  1320. // for compatibility
  1321. computeBoundingBox: function () {
  1322. },
  1323. // for compatibility
  1324. computeBoundingSphere: function () {
  1325. }
  1326. };
  1327. /**
  1328. * @author zz85 / http://www.lab4games.net/zz85/blog
  1329. * Extensible curve object
  1330. *
  1331. * Some common of Curve methods
  1332. * .getPoint(t), getTangent(t)
  1333. * .getPointAt(u), getTagentAt(u)
  1334. * .getPoints(), .getSpacedPoints()
  1335. * .getLength()
  1336. * .updateArcLengths()
  1337. *
  1338. * This file contains following classes:
  1339. *
  1340. * -- 2d classes --
  1341. * THREE.Curve
  1342. * THREE.LineCurve
  1343. * THREE.QuadraticBezierCurve
  1344. * THREE.CubicBezierCurve
  1345. * THREE.SplineCurve
  1346. * THREE.ArcCurve
  1347. *
  1348. * -- 3d classes --
  1349. * THREE.LineCurve3
  1350. * THREE.QuadraticBezierCurve3
  1351. * THREE.CubicBezierCurve3
  1352. * THREE.SplineCurve3
  1353. * THREE.ClosedSplineCurve3
  1354. *
  1355. * A series of curves can be represented as a THREE.CurvePath
  1356. *
  1357. **/
  1358. /**************************************************************
  1359. * Abstract Curve base class
  1360. **************************************************************/
  1361. THREE.Curve = function () {
  1362. };
  1363. // Virtual base class method to overwrite and implement in subclasses
  1364. // - t [0 .. 1]
  1365. THREE.Curve.prototype.getPoint = function ( t ) {
  1366. console.log( "Warning, getPoint() not implemented!" );
  1367. return null;
  1368. };
  1369. // Get point at relative position in curve according to arc length
  1370. // - u [0 .. 1]
  1371. THREE.Curve.prototype.getPointAt = function ( u ) {
  1372. var t = this.getUtoTmapping( u );
  1373. return this.getPoint( t );
  1374. };
  1375. // Get sequence of points using getPoint( t )
  1376. THREE.Curve.prototype.getPoints = function ( divisions ) {
  1377. if ( !divisions ) divisions = 5;
  1378. var d, pts = [];
  1379. for ( d = 0; d <= divisions; d ++ ) {
  1380. pts.push( this.getPoint( d / divisions ) );
  1381. }
  1382. return pts;
  1383. };
  1384. // Get sequence of points using getPointAt( u )
  1385. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  1386. if ( !divisions ) divisions = 5;
  1387. var d, pts = [];
  1388. for ( d = 0; d <= divisions; d ++ ) {
  1389. pts.push( this.getPointAt( d / divisions ) );
  1390. }
  1391. return pts;
  1392. };
  1393. // Get total curve arc length
  1394. THREE.Curve.prototype.getLength = function () {
  1395. var lengths = this.getLengths();
  1396. return lengths[ lengths.length - 1 ];
  1397. };
  1398. // Get list of cumulative segment lengths
  1399. THREE.Curve.prototype.getLengths = function ( divisions ) {
  1400. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  1401. if ( this.cacheArcLengths
  1402. && ( this.cacheArcLengths.length == divisions + 1 )
  1403. && !this.needsUpdate) {
  1404. //console.log( "cached", this.cacheArcLengths );
  1405. return this.cacheArcLengths;
  1406. }
  1407. this.needsUpdate = false;
  1408. var cache = [];
  1409. var current, last = this.getPoint( 0 );
  1410. var p, sum = 0;
  1411. cache.push( 0 );
  1412. for ( p = 1; p <= divisions; p ++ ) {
  1413. current = this.getPoint ( p / divisions );
  1414. sum += current.distanceTo( last );
  1415. cache.push( sum );
  1416. last = current;
  1417. }
  1418. this.cacheArcLengths = cache;
  1419. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  1420. };
  1421. THREE.Curve.prototype.updateArcLengths = function() {
  1422. this.needsUpdate = true;
  1423. this.getLengths();
  1424. };
  1425. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  1426. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  1427. var arcLengths = this.getLengths();
  1428. var i = 0, il = arcLengths.length;
  1429. var targetArcLength; // The targeted u distance value to get
  1430. if ( distance ) {
  1431. targetArcLength = distance;
  1432. } else {
  1433. targetArcLength = u * arcLengths[ il - 1 ];
  1434. }
  1435. //var time = Date.now();
  1436. // binary search for the index with largest value smaller than target u distance
  1437. var low = 0, high = il - 1, comparison;
  1438. while ( low <= high ) {
  1439. i = Math.floor( low + ( high - low ) / 2 ); // less likely to overflow, though probably not issue here, JS doesn't really have integers, all numbers are floats
  1440. comparison = arcLengths[ i ] - targetArcLength;
  1441. if ( comparison < 0 ) {
  1442. low = i + 1;
  1443. continue;
  1444. } else if ( comparison > 0 ) {
  1445. high = i - 1;
  1446. continue;
  1447. } else {
  1448. high = i;
  1449. break;
  1450. // DONE
  1451. }
  1452. }
  1453. i = high;
  1454. //console.log('b' , i, low, high, Date.now()- time);
  1455. if ( arcLengths[ i ] == targetArcLength ) {
  1456. var t = i / ( il - 1 );
  1457. return t;
  1458. }
  1459. // we could get finer grain at lengths, or use simple interpolatation between two points
  1460. var lengthBefore = arcLengths[ i ];
  1461. var lengthAfter = arcLengths[ i + 1 ];
  1462. var segmentLength = lengthAfter - lengthBefore;
  1463. // determine where we are between the 'before' and 'after' points
  1464. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  1465. // add that fractional amount to t
  1466. var t = ( i + segmentFraction ) / ( il -1 );
  1467. return t;
  1468. };
  1469. // In 2D space, there are actually 2 normal vectors,
  1470. // and in 3D space, infinte
  1471. // TODO this should be depreciated.
  1472. THREE.Curve.prototype.getNormalVector = function( t ) {
  1473. var vec = this.getTangent( t );
  1474. return new THREE.Vector2( -vec.y , vec.x );
  1475. };
  1476. // Returns a unit vector tangent at t
  1477. // In case any sub curve does not implement its tangent / normal finding,
  1478. // we get 2 points with a small delta and find a gradient of the 2 points
  1479. // which seems to make a reasonable approximation
  1480. THREE.Curve.prototype.getTangent = function( t ) {
  1481. var delta = 0.0001;
  1482. var t1 = t - delta;
  1483. var t2 = t + delta;
  1484. // Capping in case of danger
  1485. if ( t1 < 0 ) t1 = 0;
  1486. if ( t2 > 1 ) t2 = 1;
  1487. var pt1 = this.getPoint( t1 );
  1488. var pt2 = this.getPoint( t2 );
  1489. var vec = pt2.clone().subSelf(pt1);
  1490. return vec.normalize();
  1491. };
  1492. THREE.Curve.prototype.getTangentAt = function ( u ) {
  1493. var t = this.getUtoTmapping( u );
  1494. return this.getTangent( t );
  1495. };
  1496. /**************************************************************
  1497. * Line
  1498. **************************************************************/
  1499. THREE.LineCurve = function ( v1, v2 ) {
  1500. this.v1 = v1;
  1501. this.v2 = v2;
  1502. };
  1503. THREE.LineCurve.prototype = new THREE.Curve();
  1504. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  1505. THREE.LineCurve.prototype.getPoint = function ( t ) {
  1506. var point = this.v2.clone().subSelf(this.v1);
  1507. point.multiplyScalar( t ).addSelf( this.v1 );
  1508. return point;
  1509. };
  1510. // Line curve is linear, so we can overwrite default getPointAt
  1511. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  1512. return this.getPoint( u );
  1513. };
  1514. THREE.LineCurve.prototype.getTangent = function( t ) {
  1515. var tangent = this.v2.clone().subSelf(this.v1);
  1516. return tangent.normalize();
  1517. };
  1518. /**************************************************************
  1519. * Quadratic Bezier curve
  1520. **************************************************************/
  1521. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  1522. this.v0 = v0;
  1523. this.v1 = v1;
  1524. this.v2 = v2;
  1525. };
  1526. THREE.QuadraticBezierCurve.prototype = new THREE.Curve();
  1527. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  1528. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  1529. var tx, ty;
  1530. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  1531. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  1532. return new THREE.Vector2( tx, ty );
  1533. };
  1534. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  1535. var tx, ty;
  1536. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  1537. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  1538. // returns unit vector
  1539. var tangent = new THREE.Vector2( tx, ty );
  1540. tangent.normalize();
  1541. return tangent;
  1542. };
  1543. /**************************************************************
  1544. * Cubic Bezier curve
  1545. **************************************************************/
  1546. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  1547. this.v0 = v0;
  1548. this.v1 = v1;
  1549. this.v2 = v2;
  1550. this.v3 = v3;
  1551. };
  1552. THREE.CubicBezierCurve.prototype = new THREE.Curve();
  1553. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  1554. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  1555. var tx, ty;
  1556. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  1557. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  1558. return new THREE.Vector2( tx, ty );
  1559. };
  1560. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  1561. var tx, ty;
  1562. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  1563. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  1564. var tangent = new THREE.Vector2( tx, ty );
  1565. tangent.normalize();
  1566. return tangent;
  1567. };
  1568. /**************************************************************
  1569. * Spline curve
  1570. **************************************************************/
  1571. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  1572. this.points = (points == undefined) ? [] : points;
  1573. };
  1574. THREE.SplineCurve.prototype = new THREE.Curve();
  1575. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  1576. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  1577. var v = new THREE.Vector2();
  1578. var c = [];
  1579. var points = this.points, point, intPoint, weight;
  1580. point = ( points.length - 1 ) * t;
  1581. intPoint = Math.floor( point );
  1582. weight = point - intPoint;
  1583. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  1584. c[ 1 ] = intPoint;
  1585. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  1586. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  1587. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  1588. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  1589. return v;
  1590. };
  1591. /**************************************************************
  1592. * Arc curve
  1593. **************************************************************/
  1594. THREE.ArcCurve = function ( aX, aY, aRadius,
  1595. aStartAngle, aEndAngle,
  1596. aClockwise ) {
  1597. this.aX = aX;
  1598. this.aY = aY;
  1599. this.aRadius = aRadius;
  1600. this.aStartAngle = aStartAngle;
  1601. this.aEndAngle = aEndAngle;
  1602. this.aClockwise = aClockwise;
  1603. };
  1604. THREE.ArcCurve.prototype = new THREE.Curve();
  1605. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  1606. THREE.ArcCurve.prototype.getPoint = function ( t ) {
  1607. var deltaAngle = this.aEndAngle - this.aStartAngle;
  1608. if ( !this.aClockwise ) {
  1609. t = 1 - t;
  1610. }
  1611. var angle = this.aStartAngle + t * deltaAngle;
  1612. var tx = this.aX + this.aRadius * Math.cos( angle );
  1613. var ty = this.aY + this.aRadius * Math.sin( angle );
  1614. return new THREE.Vector2( tx, ty );
  1615. };
  1616. /**************************************************************
  1617. * Utils
  1618. **************************************************************/
  1619. THREE.Curve.Utils = {
  1620. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  1621. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  1622. },
  1623. // Puay Bing, thanks for helping with this derivative!
  1624. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  1625. return -3 * p0 * (1 - t) * (1 - t) +
  1626. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  1627. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  1628. 3 * t * t * p3;
  1629. },
  1630. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  1631. // To check if my formulas are correct
  1632. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  1633. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  1634. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  1635. var h11 = 3 * t * t - 2 * t; // t3 − t2
  1636. return h00 + h10 + h01 + h11;
  1637. },
  1638. // Catmull-Rom
  1639. interpolate: function( p0, p1, p2, p3, t ) {
  1640. var v0 = ( p2 - p0 ) * 0.5;
  1641. var v1 = ( p3 - p1 ) * 0.5;
  1642. var t2 = t * t;
  1643. var t3 = t * t2;
  1644. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  1645. }
  1646. };
  1647. // TODO: Transformation for Curves?
  1648. /**************************************************************
  1649. * 3D Curves
  1650. **************************************************************/
  1651. // A Factory method for creating new curve subclasses
  1652. THREE.Curve.create = function( constructor, getPointFunc ) {
  1653. var subClass = constructor;
  1654. subClass.prototype = new THREE.Curve();
  1655. subClass.prototype.constructor = constructor;
  1656. subClass.prototype.getPoint = getPointFunc;
  1657. return subClass;
  1658. };
  1659. /**************************************************************
  1660. * Line3D
  1661. **************************************************************/
  1662. THREE.LineCurve3 = THREE.Curve.create(
  1663. function ( v1, v2 ) {
  1664. this.v1 = v1;
  1665. this.v2 = v2;
  1666. },
  1667. function ( t ) {
  1668. var r = new THREE.Vector3();
  1669. r.sub( this.v2, this.v1 ); // diff
  1670. r.multiplyScalar( t );
  1671. r.addSelf( this.v1 );
  1672. return r;
  1673. }
  1674. );
  1675. /**************************************************************
  1676. * Quadratic Bezier 3D curve
  1677. **************************************************************/
  1678. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  1679. function ( v0, v1, v2 ) {
  1680. this.v0 = v0;
  1681. this.v1 = v1;
  1682. this.v2 = v2;
  1683. },
  1684. function ( t ) {
  1685. var tx, ty, tz;
  1686. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  1687. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  1688. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  1689. return new THREE.Vector3( tx, ty, tz );
  1690. }
  1691. );
  1692. /**************************************************************
  1693. * Cubic Bezier 3D curve
  1694. **************************************************************/
  1695. THREE.CubicBezierCurve3 = THREE.Curve.create(
  1696. function ( v0, v1, v2, v3 ) {
  1697. this.v0 = v0;
  1698. this.v1 = v1;
  1699. this.v2 = v2;
  1700. this.v3 = v3;
  1701. },
  1702. function ( t ) {
  1703. var tx, ty, tz;
  1704. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  1705. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  1706. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  1707. return new THREE.Vector3( tx, ty, tz );
  1708. }
  1709. );
  1710. /**************************************************************
  1711. * Spline 3D curve
  1712. **************************************************************/
  1713. THREE.SplineCurve3 = THREE.Curve.create(
  1714. function ( points /* array of Vector3 */) {
  1715. this.points = (points == undefined) ? [] : points;
  1716. },
  1717. function ( t ) {
  1718. var v = new THREE.Vector3();
  1719. var c = [];
  1720. var points = this.points, point, intPoint, weight;
  1721. point = ( points.length - 1 ) * t;
  1722. intPoint = Math.floor( point );
  1723. weight = point - intPoint;
  1724. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  1725. c[ 1 ] = intPoint;
  1726. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  1727. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  1728. var pt0 = points[ c[0] ],
  1729. pt1 = points[ c[1] ],
  1730. pt2 = points[ c[2] ],
  1731. pt3 = points[ c[3] ];
  1732. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  1733. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  1734. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  1735. return v;
  1736. }
  1737. );
  1738. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  1739. // var v = new THREE.Vector3();
  1740. // var c = [];
  1741. // var points = this.points, point, intPoint, weight;
  1742. // point = ( points.length - 1 ) * t;
  1743. // intPoint = Math.floor( point );
  1744. // weight = point - intPoint;
  1745. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  1746. // c[ 1 ] = intPoint;
  1747. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  1748. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  1749. // var pt0 = points[ c[0] ],
  1750. // pt1 = points[ c[1] ],
  1751. // pt2 = points[ c[2] ],
  1752. // pt3 = points[ c[3] ];
  1753. // // t = weight;
  1754. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  1755. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  1756. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  1757. // return v;
  1758. // }
  1759. /**************************************************************
  1760. * Closed Spline 3D curve
  1761. **************************************************************/
  1762. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  1763. function ( points /* array of Vector3 */) {
  1764. this.points = (points == undefined) ? [] : points;
  1765. },
  1766. function ( t ) {
  1767. var v = new THREE.Vector3();
  1768. var c = [];
  1769. var points = this.points, point, intPoint, weight;
  1770. point = ( points.length - 0 ) * t;
  1771. // This needs to be from 0-length +1
  1772. intPoint = Math.floor( point );
  1773. weight = point - intPoint;
  1774. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  1775. c[ 0 ] = ( intPoint - 1 ) % points.length;
  1776. c[ 1 ] = ( intPoint ) % points.length;
  1777. c[ 2 ] = ( intPoint + 1 ) % points.length;
  1778. c[ 3 ] = ( intPoint + 2 ) % points.length;
  1779. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  1780. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  1781. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  1782. return v;
  1783. }
  1784. );/**
  1785. * @author zz85 / http://www.lab4games.net/zz85/blog
  1786. *
  1787. **/
  1788. /**************************************************************
  1789. * Curved Path - a curve path is simply a array of connected
  1790. * curves, but retains the api of a curve
  1791. **************************************************************/
  1792. THREE.CurvePath = function () {
  1793. this.curves = [];
  1794. this.bends = [];
  1795. this.autoClose = false; // Automatically closes the path
  1796. };
  1797. THREE.CurvePath.prototype = new THREE.Curve();
  1798. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  1799. THREE.CurvePath.prototype.add = function ( curve ) {
  1800. this.curves.push( curve );
  1801. };
  1802. THREE.CurvePath.prototype.checkConnection = function() {
  1803. // TODO
  1804. // If the ending of curve is not connected to the starting
  1805. // or the next curve, then, this is not a real path
  1806. };
  1807. THREE.CurvePath.prototype.closePath = function() {
  1808. // TODO Test
  1809. // and verify for vector3 (needs to implement equals)
  1810. // Add a line curve if start and end of lines are not connected
  1811. var startPoint = this.curves[0].getPoint(0);
  1812. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  1813. if (!startPoint.equals(endPoint)) {
  1814. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  1815. }
  1816. };
  1817. // To get accurate point with reference to
  1818. // entire path distance at time t,
  1819. // following has to be done:
  1820. // 1. Length of each sub path have to be known
  1821. // 2. Locate and identify type of curve
  1822. // 3. Get t for the curve
  1823. // 4. Return curve.getPointAt(t')
  1824. THREE.CurvePath.prototype.getPoint = function( t ) {
  1825. var d = t * this.getLength();
  1826. var curveLengths = this.getCurveLengths();
  1827. var i = 0, diff, curve;
  1828. // To think about boundaries points.
  1829. while ( i < curveLengths.length ) {
  1830. if ( curveLengths[ i ] >= d ) {
  1831. diff = curveLengths[ i ] - d;
  1832. curve = this.curves[ i ];
  1833. var u = 1 - diff / curve.getLength();
  1834. return curve.getPointAt( u );
  1835. break;
  1836. }
  1837. i ++;
  1838. }
  1839. return null;
  1840. // loop where sum != 0, sum > d , sum+1 <d
  1841. };
  1842. /*
  1843. THREE.CurvePath.prototype.getTangent = function( t ) {
  1844. };*/
  1845. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  1846. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  1847. // getPoint() depends on getLength
  1848. THREE.CurvePath.prototype.getLength = function() {
  1849. var lens = this.getCurveLengths();
  1850. return lens[ lens.length - 1 ];
  1851. };
  1852. // Compute lengths and cache them
  1853. // We cannot overwrite getLengths() because UtoT mapping uses it.
  1854. THREE.CurvePath.prototype.getCurveLengths = function() {
  1855. // We use cache values if curves and cache array are same length
  1856. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  1857. return this.cacheLengths;
  1858. };
  1859. // Get length of subsurve
  1860. // Push sums into cached array
  1861. var lengths = [], sums = 0;
  1862. var i, il = this.curves.length;
  1863. for ( i = 0; i < il; i ++ ) {
  1864. sums += this.curves[ i ].getLength();
  1865. lengths.push( sums );
  1866. }
  1867. this.cacheLengths = lengths;
  1868. return lengths;
  1869. };
  1870. // Returns min and max coordinates, as well as centroid
  1871. THREE.CurvePath.prototype.getBoundingBox = function () {
  1872. var points = this.getPoints();
  1873. var maxX, maxY;
  1874. var minX, minY;
  1875. maxX = maxY = Number.NEGATIVE_INFINITY;
  1876. minX = minY = Number.POSITIVE_INFINITY;
  1877. var p, i, il, sum;
  1878. sum = new THREE.Vector2();
  1879. for ( i = 0, il = points.length; i < il; i ++ ) {
  1880. p = points[ i ];
  1881. if ( p.x > maxX ) maxX = p.x;
  1882. else if ( p.x < minX ) minX = p.x;
  1883. if ( p.y > maxY ) maxY = p.y;
  1884. else if ( p.y < maxY ) minY = p.y;
  1885. sum.addSelf( p.x, p.y );
  1886. }
  1887. return {
  1888. minX: minX,
  1889. minY: minY,
  1890. maxX: maxX,
  1891. maxY: maxY,
  1892. centroid: sum.divideScalar( il )
  1893. };
  1894. };
  1895. /**************************************************************
  1896. * Create Geometries Helpers
  1897. **************************************************************/
  1898. /// Generate geometry from path points (for Line or ParticleSystem objects)
  1899. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  1900. var pts = this.getPoints( divisions, true );
  1901. return this.createGeometry( pts );
  1902. };
  1903. // Generate geometry from equidistance sampling along the path
  1904. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  1905. var pts = this.getSpacedPoints( divisions, true );
  1906. return this.createGeometry( pts );
  1907. };
  1908. THREE.CurvePath.prototype.createGeometry = function( points ) {
  1909. var geometry = new THREE.Geometry();
  1910. for ( var i = 0; i < points.length; i ++ ) {
  1911. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, 0 ) );
  1912. }
  1913. return geometry;
  1914. };
  1915. /**************************************************************
  1916. * Bend / Wrap Helper Methods
  1917. **************************************************************/
  1918. // Wrap path / Bend modifiers?
  1919. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  1920. this.bends.push( bendpath );
  1921. };
  1922. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  1923. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  1924. var i, il;
  1925. if ( !bends ) {
  1926. bends = this.bends;
  1927. }
  1928. for ( i = 0, il = bends.length; i < il; i ++ ) {
  1929. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  1930. }
  1931. return oldPts;
  1932. };
  1933. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  1934. var oldPts = this.getSpacedPoints( segments );
  1935. var i, il;
  1936. if ( !bends ) {
  1937. bends = this.bends;
  1938. }
  1939. for ( i = 0, il = bends.length; i < il; i ++ ) {
  1940. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  1941. }
  1942. return oldPts;
  1943. };
  1944. // This returns getPoints() bend/wrapped around the contour of a path.
  1945. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  1946. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  1947. var bounds = this.getBoundingBox();
  1948. var i, il, p, oldX, oldY, xNorm;
  1949. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  1950. p = oldPts[ i ];
  1951. oldX = p.x;
  1952. oldY = p.y;
  1953. xNorm = oldX / bounds.maxX;
  1954. // If using actual distance, for length > path, requires line extrusions
  1955. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  1956. xNorm = path.getUtoTmapping( xNorm, oldX );
  1957. // check for out of bounds?
  1958. var pathPt = path.getPoint( xNorm );
  1959. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  1960. p.x = pathPt.x + normal.x;
  1961. p.y = pathPt.y + normal.y;
  1962. }
  1963. return oldPts;
  1964. };
  1965. /**
  1966. * https://github.com/mrdoob/eventtarget.js/
  1967. */
  1968. THREE.EventTarget = function () {
  1969. var listeners = {};
  1970. this.addEventListener = function ( type, listener ) {
  1971. if ( listeners[ type ] == undefined ) {
  1972. listeners[ type ] = [];
  1973. }
  1974. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1975. listeners[ type ].push( listener );
  1976. }
  1977. };
  1978. this.dispatchEvent = function ( event ) {
  1979. for ( var listener in listeners[ event.type ] ) {
  1980. listeners[ event.type ][ listener ]( event );
  1981. }
  1982. };
  1983. this.removeEventListener = function ( type, listener ) {
  1984. var index = listeners[ type ].indexOf( listener );
  1985. if ( index !== - 1 ) {
  1986. listeners[ type ].splice( index, 1 );
  1987. }
  1988. };
  1989. };
  1990. /**
  1991. * @author alteredq / http://alteredqualia.com/
  1992. */
  1993. THREE.Gyroscope = function () {
  1994. THREE.Object3D.call( this );
  1995. };
  1996. THREE.Gyroscope.prototype = new THREE.Object3D();
  1997. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  1998. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  1999. this.matrixAutoUpdate && this.updateMatrix();
  2000. // update matrixWorld
  2001. if ( this.matrixWorldNeedsUpdate || force ) {
  2002. if ( this.parent ) {
  2003. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2004. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  2005. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  2006. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  2007. } else {
  2008. this.matrixWorld.copy( this.matrix );
  2009. }
  2010. this.matrixWorldNeedsUpdate = false;
  2011. force = true;
  2012. }
  2013. // update children
  2014. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2015. this.children[ i ].updateMatrixWorld( force );
  2016. }
  2017. };
  2018. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  2019. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  2020. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  2021. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  2022. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  2023. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  2024. /**
  2025. * @author zz85 / http://www.lab4games.net/zz85/blog
  2026. * Creates free form 2d path using series of points, lines or curves.
  2027. *
  2028. **/
  2029. THREE.Path = function ( points ) {
  2030. THREE.CurvePath.call(this);
  2031. this.actions = [];
  2032. if ( points ) {
  2033. this.fromPoints( points );
  2034. }
  2035. };
  2036. THREE.Path.prototype = new THREE.CurvePath();
  2037. THREE.Path.prototype.constructor = THREE.Path;
  2038. THREE.PathActions = {
  2039. MOVE_TO: 'moveTo',
  2040. LINE_TO: 'lineTo',
  2041. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  2042. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  2043. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  2044. ARC: 'arc' // Circle
  2045. };
  2046. // TODO Clean up PATH API
  2047. // Create path using straight lines to connect all points
  2048. // - vectors: array of Vector2
  2049. THREE.Path.prototype.fromPoints = function ( vectors ) {
  2050. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  2051. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  2052. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  2053. };
  2054. };
  2055. // startPath() endPath()?
  2056. THREE.Path.prototype.moveTo = function ( x, y ) {
  2057. var args = Array.prototype.slice.call( arguments );
  2058. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  2059. };
  2060. THREE.Path.prototype.lineTo = function ( x, y ) {
  2061. var args = Array.prototype.slice.call( arguments );
  2062. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2063. var x0 = lastargs[ lastargs.length - 2 ];
  2064. var y0 = lastargs[ lastargs.length - 1 ];
  2065. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  2066. this.curves.push( curve );
  2067. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  2068. };
  2069. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  2070. var args = Array.prototype.slice.call( arguments );
  2071. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2072. var x0 = lastargs[ lastargs.length - 2 ];
  2073. var y0 = lastargs[ lastargs.length - 1 ];
  2074. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  2075. new THREE.Vector2( aCPx, aCPy ),
  2076. new THREE.Vector2( aX, aY ) );
  2077. this.curves.push( curve );
  2078. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  2079. };
  2080. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  2081. aCP2x, aCP2y,
  2082. aX, aY ) {
  2083. var args = Array.prototype.slice.call( arguments );
  2084. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2085. var x0 = lastargs[ lastargs.length - 2 ];
  2086. var y0 = lastargs[ lastargs.length - 1 ];
  2087. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  2088. new THREE.Vector2( aCP1x, aCP1y ),
  2089. new THREE.Vector2( aCP2x, aCP2y ),
  2090. new THREE.Vector2( aX, aY ) );
  2091. this.curves.push( curve );
  2092. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  2093. };
  2094. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  2095. var args = Array.prototype.slice.call( arguments );
  2096. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2097. var x0 = lastargs[ lastargs.length - 2 ];
  2098. var y0 = lastargs[ lastargs.length - 1 ];
  2099. //---
  2100. var npts = [ new THREE.Vector2( x0, y0 ) ];
  2101. Array.prototype.push.apply( npts, pts );
  2102. var curve = new THREE.SplineCurve( npts );
  2103. this.curves.push( curve );
  2104. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  2105. };
  2106. // FUTURE: Change the API or follow canvas API?
  2107. // TODO ARC ( x, y, x - radius, y - radius, startAngle, endAngle )
  2108. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  2109. aStartAngle, aEndAngle, aClockwise ) {
  2110. var args = Array.prototype.slice.call( arguments );
  2111. var laste = this.actions[ this.actions.length - 1];
  2112. var curve = new THREE.ArcCurve( laste.x + aX, laste.y + aY, aRadius,
  2113. aStartAngle, aEndAngle, aClockwise );
  2114. this.curves.push( curve );
  2115. // All of the other actions look to the last two elements in the list to
  2116. // find the ending point, so we need to append them.
  2117. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  2118. args.push(lastPoint.x);
  2119. args.push(lastPoint.y);
  2120. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  2121. };
  2122. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  2123. aStartAngle, aEndAngle, aClockwise ) {
  2124. var args = Array.prototype.slice.call( arguments );
  2125. var curve = new THREE.ArcCurve( aX, aY, aRadius,
  2126. aStartAngle, aEndAngle, aClockwise );
  2127. this.curves.push( curve );
  2128. // console.log( 'arc', args );
  2129. // All of the other actions look to the last two elements in the list to
  2130. // find the ending point, so we need to append them.
  2131. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  2132. args.push(lastPoint.x);
  2133. args.push(lastPoint.y);
  2134. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  2135. };
  2136. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  2137. if ( ! divisions ) divisions = 40;
  2138. var points = [];
  2139. for ( var i = 0; i < divisions; i ++ ) {
  2140. points.push( this.getPoint( i / divisions ) );
  2141. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  2142. }
  2143. // if ( closedPath ) {
  2144. //
  2145. // points.push( points[ 0 ] );
  2146. //
  2147. // }
  2148. return points;
  2149. };
  2150. /* Return an array of vectors based on contour of the path */
  2151. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  2152. if (this.useSpacedPoints) {
  2153. console.log('tata');
  2154. return this.getSpacedPoints( divisions, closedPath );
  2155. }
  2156. divisions = divisions || 12;
  2157. var points = [];
  2158. var i, il, item, action, args;
  2159. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  2160. laste, j,
  2161. t, tx, ty;
  2162. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  2163. item = this.actions[ i ];
  2164. action = item.action;
  2165. args = item.args;
  2166. switch( action ) {
  2167. case THREE.PathActions.MOVE_TO:
  2168. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  2169. break;
  2170. case THREE.PathActions.LINE_TO:
  2171. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  2172. break;
  2173. case THREE.PathActions.QUADRATIC_CURVE_TO:
  2174. cpx = args[ 2 ];
  2175. cpy = args[ 3 ];
  2176. cpx1 = args[ 0 ];
  2177. cpy1 = args[ 1 ];
  2178. if ( points.length > 0 ) {
  2179. laste = points[ points.length - 1 ];
  2180. cpx0 = laste.x;
  2181. cpy0 = laste.y;
  2182. } else {
  2183. laste = this.actions[ i - 1 ].args;
  2184. cpx0 = laste[ laste.length - 2 ];
  2185. cpy0 = laste[ laste.length - 1 ];
  2186. }
  2187. for ( j = 1; j <= divisions; j ++ ) {
  2188. t = j / divisions;
  2189. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  2190. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  2191. points.push( new THREE.Vector2( tx, ty ) );
  2192. }
  2193. break;
  2194. case THREE.PathActions.BEZIER_CURVE_TO:
  2195. cpx = args[ 4 ];
  2196. cpy = args[ 5 ];
  2197. cpx1 = args[ 0 ];
  2198. cpy1 = args[ 1 ];
  2199. cpx2 = args[ 2 ];
  2200. cpy2 = args[ 3 ];
  2201. if ( points.length > 0 ) {
  2202. laste = points[ points.length - 1 ];
  2203. cpx0 = laste.x;
  2204. cpy0 = laste.y;
  2205. } else {
  2206. laste = this.actions[ i - 1 ].args;
  2207. cpx0 = laste[ laste.length - 2 ];
  2208. cpy0 = laste[ laste.length - 1 ];
  2209. }
  2210. for ( j = 1; j <= divisions; j ++ ) {
  2211. t = j / divisions;
  2212. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  2213. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  2214. points.push( new THREE.Vector2( tx, ty ) );
  2215. }
  2216. break;
  2217. case THREE.PathActions.CSPLINE_THRU:
  2218. laste = this.actions[ i - 1 ].args;
  2219. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  2220. var spts = [ last ];
  2221. var n = divisions * args[ 0 ].length;
  2222. spts = spts.concat( args[ 0 ] );
  2223. var spline = new THREE.SplineCurve( spts );
  2224. for ( j = 1; j <= n; j ++ ) {
  2225. points.push( spline.getPointAt( j / n ) ) ;
  2226. }
  2227. break;
  2228. case THREE.PathActions.ARC:
  2229. laste = this.actions[ i - 1 ].args;
  2230. var aX = args[ 0 ], aY = args[ 1 ],
  2231. aRadius = args[ 2 ],
  2232. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  2233. aClockwise = !!args[ 5 ];
  2234. var deltaAngle = aEndAngle - aStartAngle;
  2235. var angle;
  2236. var tdivisions = divisions * 2;
  2237. for ( j = 1; j <= tdivisions; j ++ ) {
  2238. t = j / tdivisions;
  2239. if ( ! aClockwise ) {
  2240. t = 1 - t;
  2241. }
  2242. angle = aStartAngle + t * deltaAngle;
  2243. tx = aX + aRadius * Math.cos( angle );
  2244. ty = aY + aRadius * Math.sin( angle );
  2245. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  2246. points.push( new THREE.Vector2( tx, ty ) );
  2247. }
  2248. //console.log(points);
  2249. break;
  2250. } // end switch
  2251. }
  2252. // Normalize to remove the closing point by default.
  2253. var lastPoint = points[ points.length - 1];
  2254. var EPSILON = 0.0000000001;
  2255. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  2256. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  2257. points.splice( points.length - 1, 1);
  2258. if ( closedPath ) {
  2259. points.push( points[ 0 ] );
  2260. }
  2261. return points;
  2262. };
  2263. // This was used for testing purposes. Should be removed soon.
  2264. THREE.Path.prototype.transform = function( path, segments ) {
  2265. var bounds = this.getBoundingBox();
  2266. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  2267. //console.log( path.cacheArcLengths() );
  2268. //path.getLengths(400);
  2269. //segments = 40;
  2270. return this.getWrapPoints( oldPts, path );
  2271. };
  2272. // Read http://www.tinaja.com/glib/nonlingr.pdf
  2273. // nonlinear transforms
  2274. THREE.Path.prototype.nltransform = function( a, b, c, d, e, f ) {
  2275. // a - horizontal size
  2276. // b - lean
  2277. // c - x offset
  2278. // d - vertical size
  2279. // e - climb
  2280. // f - y offset
  2281. var oldPts = this.getPoints();
  2282. var i, il, p, oldX, oldY;
  2283. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  2284. p = oldPts[i];
  2285. oldX = p.x;
  2286. oldY = p.y;
  2287. p.x = a * oldX + b * oldY + c;
  2288. p.y = d * oldY + e * oldX + f;
  2289. }
  2290. return oldPts;
  2291. };
  2292. // FUTURE Export JSON Format
  2293. /* Draws this path onto a 2d canvas easily */
  2294. THREE.Path.prototype.debug = function( canvas ) {
  2295. var bounds = this.getBoundingBox();
  2296. if ( !canvas ) {
  2297. canvas = document.createElement( "canvas" );
  2298. canvas.setAttribute( 'width', bounds.maxX + 100 );
  2299. canvas.setAttribute( 'height', bounds.maxY + 100 );
  2300. document.body.appendChild( canvas );
  2301. }
  2302. var ctx = canvas.getContext( "2d" );
  2303. ctx.fillStyle = "white";
  2304. ctx.fillRect( 0, 0, canvas.width, canvas.height );
  2305. ctx.strokeStyle = "black";
  2306. ctx.beginPath();
  2307. var i, il, item, action, args;
  2308. // Debug Path
  2309. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  2310. item = this.actions[ i ];
  2311. args = item.args;
  2312. action = item.action;
  2313. // Short hand for now
  2314. if ( action != THREE.PathActions.CSPLINE_THRU ) {
  2315. ctx[ action ].apply( ctx, args );
  2316. }
  2317. /*
  2318. switch ( action ) {
  2319. case THREE.PathActions.MOVE_TO:
  2320. ctx[ action ]( args[ 0 ], args[ 1 ] );
  2321. break;
  2322. case THREE.PathActions.LINE_TO:
  2323. ctx[ action ]( args[ 0 ], args[ 1 ] );
  2324. break;
  2325. case THREE.PathActions.QUADRATIC_CURVE_TO:
  2326. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ] );
  2327. break;
  2328. case THREE.PathActions.CUBIC_CURVE_TO:
  2329. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ], args[ 4 ], args[ 5 ] );
  2330. break;
  2331. }
  2332. */
  2333. }
  2334. ctx.stroke();
  2335. ctx.closePath();
  2336. // Debug Points
  2337. ctx.strokeStyle = "red";
  2338. /* TO CLEAN UP */
  2339. var p, points = this.getPoints();
  2340. for ( i = 0, il = points.length; i < il; i ++ ) {
  2341. p = points[ i ];
  2342. ctx.beginPath();
  2343. ctx.arc( p.x, p.y, 1.5, 0, Math.PI * 2, false );
  2344. ctx.stroke();
  2345. ctx.closePath();
  2346. }
  2347. };
  2348. // Breaks path into shapes
  2349. THREE.Path.prototype.toShapes = function() {
  2350. var i, il, item, action, args;
  2351. var subPaths = [], lastPath = new THREE.Path();
  2352. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  2353. item = this.actions[ i ];
  2354. args = item.args;
  2355. action = item.action;
  2356. if ( action == THREE.PathActions.MOVE_TO ) {
  2357. if ( lastPath.actions.length != 0 ) {
  2358. subPaths.push( lastPath );
  2359. lastPath = new THREE.Path();
  2360. }
  2361. }
  2362. lastPath[ action ].apply( lastPath, args );
  2363. }
  2364. if ( lastPath.actions.length != 0 ) {
  2365. subPaths.push( lastPath );
  2366. }
  2367. // console.log(subPaths);
  2368. if ( subPaths.length == 0 ) return [];
  2369. var tmpPath, tmpShape, shapes = [];
  2370. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  2371. // console.log("Holes first", holesFirst);
  2372. if ( subPaths.length == 1) {
  2373. tmpPath = subPaths[0];
  2374. tmpShape = new THREE.Shape();
  2375. tmpShape.actions = tmpPath.actions;
  2376. tmpShape.curves = tmpPath.curves;
  2377. shapes.push( tmpShape );
  2378. return shapes;
  2379. };
  2380. if ( holesFirst ) {
  2381. tmpShape = new THREE.Shape();
  2382. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  2383. tmpPath = subPaths[ i ];
  2384. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  2385. tmpShape.actions = tmpPath.actions;
  2386. tmpShape.curves = tmpPath.curves;
  2387. shapes.push( tmpShape );
  2388. tmpShape = new THREE.Shape();
  2389. //console.log('cw', i);
  2390. } else {
  2391. tmpShape.holes.push( tmpPath );
  2392. //console.log('ccw', i);
  2393. }
  2394. }
  2395. } else {
  2396. // Shapes first
  2397. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  2398. tmpPath = subPaths[ i ];
  2399. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  2400. if ( tmpShape ) shapes.push( tmpShape );
  2401. tmpShape = new THREE.Shape();
  2402. tmpShape.actions = tmpPath.actions;
  2403. tmpShape.curves = tmpPath.curves;
  2404. } else {
  2405. tmpShape.holes.push( tmpPath );
  2406. }
  2407. }
  2408. shapes.push( tmpShape );
  2409. }
  2410. //console.log("shape", shapes);
  2411. return shapes;
  2412. };
  2413. /**
  2414. * @author zz85 / http://www.lab4games.net/zz85/blog
  2415. * Defines a 2d shape plane using paths.
  2416. **/
  2417. // STEP 1 Create a path.
  2418. // STEP 2 Turn path into shape.
  2419. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  2420. // STEP 3a - Extract points from each shape, turn to vertices
  2421. // STEP 3b - Triangulate each shape, add faces.
  2422. THREE.Shape = function ( ) {
  2423. THREE.Path.apply( this, arguments );
  2424. this.holes = [];
  2425. };
  2426. THREE.Shape.prototype = new THREE.Path();
  2427. THREE.Shape.prototype.constructor = THREE.Path;
  2428. // Convenience method to return ExtrudeGeometry
  2429. THREE.Shape.prototype.extrude = function ( options ) {
  2430. var extruded = new THREE.ExtrudeGeometry( this, options );
  2431. return extruded;
  2432. };
  2433. // Get points of holes
  2434. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  2435. var i, il = this.holes.length, holesPts = [];
  2436. for ( i = 0; i < il; i ++ ) {
  2437. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  2438. }
  2439. return holesPts;
  2440. };
  2441. // Get points of holes (spaced by regular distance)
  2442. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  2443. var i, il = this.holes.length, holesPts = [];
  2444. for ( i = 0; i < il; i ++ ) {
  2445. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  2446. }
  2447. return holesPts;
  2448. };
  2449. // Get points of shape and holes (keypoints based on segments parameter)
  2450. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  2451. return {
  2452. shape: this.getTransformedPoints( divisions ),
  2453. holes: this.getPointsHoles( divisions )
  2454. };
  2455. };
  2456. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  2457. if (this.useSpacedPoints) {
  2458. return this.extractAllSpacedPoints(divisions);
  2459. }
  2460. return this.extractAllPoints(divisions);
  2461. };
  2462. //
  2463. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  2464. //
  2465. // return {
  2466. //
  2467. // shape: this.transform( bend, divisions ),
  2468. // holes: this.getPointsHoles( divisions, bend )
  2469. //
  2470. // };
  2471. //
  2472. // };
  2473. // Get points of shape and holes (spaced by regular distance)
  2474. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  2475. return {
  2476. shape: this.getTransformedSpacedPoints( divisions ),
  2477. holes: this.getSpacedPointsHoles( divisions )
  2478. };
  2479. };
  2480. /**************************************************************
  2481. * Utils
  2482. **************************************************************/
  2483. THREE.Shape.Utils = {
  2484. /*
  2485. contour - array of vector2 for contour
  2486. holes - array of array of vector2
  2487. */
  2488. removeHoles: function ( contour, holes ) {
  2489. var shape = contour.concat(); // work on this shape
  2490. var allpoints = shape.concat();
  2491. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  2492. var prevShapeVert, nextShapeVert,
  2493. prevHoleVert, nextHoleVert,
  2494. holeIndex, shapeIndex,
  2495. shapeId, shapeGroup,
  2496. h, h2,
  2497. hole, shortest, d,
  2498. p, pts1, pts2,
  2499. tmpShape1, tmpShape2,
  2500. tmpHole1, tmpHole2,
  2501. verts = [];
  2502. for ( h = 0; h < holes.length; h ++ ) {
  2503. hole = holes[ h ];
  2504. /*
  2505. shapeholes[ h ].concat(); // preserves original
  2506. holes.push( hole );
  2507. */
  2508. Array.prototype.push.apply( allpoints, hole );
  2509. shortest = Number.POSITIVE_INFINITY;
  2510. // Find the shortest pair of pts between shape and hole
  2511. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  2512. // Using distanceToSquared() intead of distanceTo() should speed a little
  2513. // since running square roots operations are reduced.
  2514. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  2515. pts1 = hole[ h2 ];
  2516. var dist = [];
  2517. for ( p = 0; p < shape.length; p++ ) {
  2518. pts2 = shape[ p ];
  2519. d = pts1.distanceToSquared( pts2 );
  2520. dist.push( d );
  2521. if ( d < shortest ) {
  2522. shortest = d;
  2523. holeIndex = h2;
  2524. shapeIndex = p;
  2525. }
  2526. }
  2527. }
  2528. //console.log("shortest", shortest, dist);
  2529. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  2530. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  2531. var areaapts = [
  2532. hole[ holeIndex ],
  2533. shape[ shapeIndex ],
  2534. shape[ prevShapeVert ]
  2535. ];
  2536. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  2537. var areabpts = [
  2538. hole[ holeIndex ],
  2539. hole[ prevHoleVert ],
  2540. shape[ shapeIndex ]
  2541. ];
  2542. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  2543. var shapeOffset = 1;
  2544. var holeOffset = -1;
  2545. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  2546. shapeIndex += shapeOffset;
  2547. holeIndex += holeOffset;
  2548. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  2549. shapeIndex %= shape.length;
  2550. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  2551. holeIndex %= hole.length;
  2552. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  2553. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  2554. areaapts = [
  2555. hole[ holeIndex ],
  2556. shape[ shapeIndex ],
  2557. shape[ prevShapeVert ]
  2558. ];
  2559. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  2560. areabpts = [
  2561. hole[ holeIndex ],
  2562. hole[ prevHoleVert ],
  2563. shape[ shapeIndex ]
  2564. ];
  2565. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  2566. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  2567. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  2568. // In case areas are not correct.
  2569. //console.log("USE THIS");
  2570. shapeIndex = oldShapeIndex;
  2571. holeIndex = oldHoleIndex ;
  2572. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  2573. shapeIndex %= shape.length;
  2574. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  2575. holeIndex %= hole.length;
  2576. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  2577. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  2578. } else {
  2579. //console.log("USE THAT ")
  2580. }
  2581. tmpShape1 = shape.slice( 0, shapeIndex );
  2582. tmpShape2 = shape.slice( shapeIndex );
  2583. tmpHole1 = hole.slice( holeIndex );
  2584. tmpHole2 = hole.slice( 0, holeIndex );
  2585. // Should check orders here again?
  2586. var trianglea = [
  2587. hole[ holeIndex ],
  2588. shape[ shapeIndex ],
  2589. shape[ prevShapeVert ]
  2590. ];
  2591. var triangleb = [
  2592. hole[ holeIndex ] ,
  2593. hole[ prevHoleVert ],
  2594. shape[ shapeIndex ]
  2595. ];
  2596. verts.push( trianglea );
  2597. verts.push( triangleb );
  2598. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  2599. }
  2600. return {
  2601. shape:shape, /* shape with no holes */
  2602. isolatedPts: verts, /* isolated faces */
  2603. allpoints: allpoints
  2604. }
  2605. },
  2606. triangulateShape: function ( contour, holes ) {
  2607. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  2608. var shape = shapeWithoutHoles.shape,
  2609. allpoints = shapeWithoutHoles.allpoints,
  2610. isolatedPts = shapeWithoutHoles.isolatedPts;
  2611. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  2612. // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.
  2613. //console.log( "triangles",triangles, triangles.length );
  2614. //console.log( "allpoints",allpoints, allpoints.length );
  2615. var i, il, f, face,
  2616. key, index,
  2617. allPointsMap = {},
  2618. isolatedPointsMap = {};
  2619. // prepare all points map
  2620. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  2621. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  2622. if ( allPointsMap[ key ] !== undefined ) {
  2623. console.log( "Duplicate point", key );
  2624. }
  2625. allPointsMap[ key ] = i;
  2626. }
  2627. // check all face vertices against all points map
  2628. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  2629. face = triangles[ i ];
  2630. for ( f = 0; f < 3; f ++ ) {
  2631. key = face[ f ].x + ":" + face[ f ].y;
  2632. index = allPointsMap[ key ];
  2633. if ( index !== undefined ) {
  2634. face[ f ] = index;
  2635. }
  2636. }
  2637. }
  2638. // check isolated points vertices against all points map
  2639. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  2640. face = isolatedPts[ i ];
  2641. for ( f = 0; f < 3; f ++ ) {
  2642. key = face[ f ].x + ":" + face[ f ].y;
  2643. index = allPointsMap[ key ];
  2644. if ( index !== undefined ) {
  2645. face[ f ] = index;
  2646. }
  2647. }
  2648. }
  2649. return triangles.concat( isolatedPts );
  2650. }, // end triangulate shapes
  2651. /*
  2652. triangulate2 : function( pts, holes ) {
  2653. // For use with Poly2Tri.js
  2654. var allpts = pts.concat();
  2655. var shape = [];
  2656. for (var p in pts) {
  2657. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  2658. }
  2659. var swctx = new js.poly2tri.SweepContext(shape);
  2660. for (var h in holes) {
  2661. var aHole = holes[h];
  2662. var newHole = []
  2663. for (i in aHole) {
  2664. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  2665. allpts.push(aHole[i]);
  2666. }
  2667. swctx.AddHole(newHole);
  2668. }
  2669. var find;
  2670. var findIndexForPt = function (pt) {
  2671. find = new THREE.Vector2(pt.x, pt.y);
  2672. var p;
  2673. for (p=0, pl = allpts.length; p<pl; p++) {
  2674. if (allpts[p].equals(find)) return p;
  2675. }
  2676. return -1;
  2677. };
  2678. // triangulate
  2679. js.poly2tri.sweep.Triangulate(swctx);
  2680. var triangles = swctx.GetTriangles();
  2681. var tr ;
  2682. var facesPts = [];
  2683. for (var t in triangles) {
  2684. tr = triangles[t];
  2685. facesPts.push([
  2686. findIndexForPt(tr.GetPoint(0)),
  2687. findIndexForPt(tr.GetPoint(1)),
  2688. findIndexForPt(tr.GetPoint(2))
  2689. ]);
  2690. }
  2691. // console.log(facesPts);
  2692. // console.log("triangles", triangles.length, triangles);
  2693. // Returns array of faces with 3 element each
  2694. return facesPts;
  2695. },
  2696. */
  2697. isClockWise: function ( pts ) {
  2698. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  2699. },
  2700. // Bezier Curves formulas obtained from
  2701. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  2702. // Quad Bezier Functions
  2703. b2p0: function ( t, p ) {
  2704. var k = 1 - t;
  2705. return k * k * p;
  2706. },
  2707. b2p1: function ( t, p ) {
  2708. return 2 * ( 1 - t ) * t * p;
  2709. },
  2710. b2p2: function ( t, p ) {
  2711. return t * t * p;
  2712. },
  2713. b2: function ( t, p0, p1, p2 ) {
  2714. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  2715. },
  2716. // Cubic Bezier Functions
  2717. b3p0: function ( t, p ) {
  2718. var k = 1 - t;
  2719. return k * k * k * p;
  2720. },
  2721. b3p1: function ( t, p ) {
  2722. var k = 1 - t;
  2723. return 3 * k * k * t * p;
  2724. },
  2725. b3p2: function ( t, p ) {
  2726. var k = 1 - t;
  2727. return 3 * k * t * t * p;
  2728. },
  2729. b3p3: function ( t, p ) {
  2730. return t * t * t * p;
  2731. },
  2732. b3: function ( t, p0, p1, p2, p3 ) {
  2733. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  2734. }
  2735. };
  2736. /**
  2737. * @author zz85 / http://www.lab4games.net/zz85/blog
  2738. *
  2739. * TextPath
  2740. *
  2741. **/
  2742. THREE.TextPath = function ( text, parameters ) {
  2743. THREE.Path.call( this );
  2744. this.parameters = parameters || {};
  2745. this.set( text );
  2746. };
  2747. THREE.TextPath.prototype.set = function ( text, parameters ) {
  2748. parameters = parameters || this.parameters;
  2749. this.text = text;
  2750. var size = parameters.size !== undefined ? parameters.size : 100;
  2751. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  2752. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  2753. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  2754. var style = parameters.style !== undefined ? parameters.style : "normal";
  2755. THREE.FontUtils.size = size;
  2756. THREE.FontUtils.divisions = curveSegments;
  2757. THREE.FontUtils.face = font;
  2758. THREE.FontUtils.weight = weight;
  2759. THREE.FontUtils.style = style;
  2760. };
  2761. THREE.TextPath.prototype.toShapes = function () {
  2762. // Get a Font data json object
  2763. var data = THREE.FontUtils.drawText( this.text );
  2764. var paths = data.paths;
  2765. var shapes = [];
  2766. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  2767. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  2768. }
  2769. return shapes;
  2770. //console.log(path);
  2771. //console.log(fontShapes);
  2772. // Either find actions or curves.
  2773. //var text3d = new THREE.ExtrudeGeometry( shapes , { amount: 20, bevelEnabled:true, bevelThickness:3 } );
  2774. //return text3d;
  2775. };
  2776. /**
  2777. * @author mikael emtinger / http://gomo.se/
  2778. */
  2779. THREE.AnimationHandler = (function() {
  2780. var playing = [];
  2781. var library = {};
  2782. var that = {};
  2783. //--- update ---
  2784. that.update = function( deltaTimeMS ) {
  2785. for( var i = 0; i < playing.length; i++ )
  2786. playing[ i ].update( deltaTimeMS );
  2787. };
  2788. //--- add ---
  2789. that.addToUpdate = function( animation ) {
  2790. if( playing.indexOf( animation ) === -1 )
  2791. playing.push( animation );
  2792. };
  2793. //--- remove ---
  2794. that.removeFromUpdate = function( animation ) {
  2795. var index = playing.indexOf( animation );
  2796. if( index !== -1 )
  2797. playing.splice( index, 1 );
  2798. };
  2799. //--- add ---
  2800. that.add = function( data ) {
  2801. if( library[ data.name ] !== undefined )
  2802. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  2803. library[ data.name ] = data;
  2804. initData( data );
  2805. };
  2806. //--- get ---
  2807. that.get = function( name ) {
  2808. if( typeof name === "string" ) {
  2809. if( library[ name ] ) {
  2810. return library[ name ];
  2811. } else {
  2812. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  2813. return null;
  2814. }
  2815. } else {
  2816. // todo: add simple tween library
  2817. }
  2818. };
  2819. //--- parse ---
  2820. that.parse = function( root ) {
  2821. // setup hierarchy
  2822. var hierarchy = [];
  2823. if ( root instanceof THREE.SkinnedMesh ) {
  2824. for( var b = 0; b < root.bones.length; b++ ) {
  2825. hierarchy.push( root.bones[ b ] );
  2826. }
  2827. } else {
  2828. parseRecurseHierarchy( root, hierarchy );
  2829. }
  2830. return hierarchy;
  2831. };
  2832. var parseRecurseHierarchy = function( root, hierarchy ) {
  2833. hierarchy.push( root );
  2834. for( var c = 0; c < root.children.length; c++ )
  2835. parseRecurseHierarchy( root.children[ c ], hierarchy );
  2836. }
  2837. //--- init data ---
  2838. var initData = function( data ) {
  2839. if( data.initialized === true )
  2840. return;
  2841. // loop through all keys
  2842. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  2843. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2844. // remove minus times
  2845. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  2846. data.hierarchy[ h ].keys[ k ].time = 0;
  2847. // create quaternions
  2848. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  2849. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  2850. var quat = data.hierarchy[ h ].keys[ k ].rot;
  2851. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  2852. }
  2853. }
  2854. // prepare morph target keys
  2855. if( data.hierarchy[h].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  2856. // get all used
  2857. var usedMorphTargets = {};
  2858. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2859. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  2860. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  2861. usedMorphTargets[ morphTargetName ] = -1;
  2862. }
  2863. }
  2864. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  2865. // set all used on all frames
  2866. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2867. var influences = {};
  2868. for( var morphTargetName in usedMorphTargets ) {
  2869. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  2870. if( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  2871. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  2872. break;
  2873. }
  2874. }
  2875. if( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  2876. influences[ morphTargetName ] = 0;
  2877. }
  2878. }
  2879. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  2880. }
  2881. }
  2882. // remove all keys that are on the same time
  2883. for( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2884. if( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  2885. data.hierarchy[ h ].keys.splice( k, 1 );
  2886. k --;
  2887. }
  2888. }
  2889. // set index
  2890. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2891. data.hierarchy[ h ].keys[ k ].index = k;
  2892. }
  2893. }
  2894. // JIT
  2895. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  2896. data.JIT = {};
  2897. data.JIT.hierarchy = [];
  2898. for( var h = 0; h < data.hierarchy.length; h ++ )
  2899. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  2900. // done
  2901. data.initialized = true;
  2902. };
  2903. // interpolation types
  2904. that.LINEAR = 0;
  2905. that.CATMULLROM = 1;
  2906. that.CATMULLROM_FORWARD = 2;
  2907. return that;
  2908. }());
  2909. /**
  2910. * @author mikael emtinger / http://gomo.se/
  2911. * @author mrdoob / http://mrdoob.com/
  2912. * @author alteredq / http://alteredqualia.com/
  2913. */
  2914. THREE.Animation = function( root, data, interpolationType, JITCompile ) {
  2915. this.root = root;
  2916. this.data = THREE.AnimationHandler.get( data );
  2917. this.hierarchy = THREE.AnimationHandler.parse( root );
  2918. this.currentTime = 0;
  2919. this.timeScale = 1;
  2920. this.isPlaying = false;
  2921. this.isPaused = true;
  2922. this.loop = true;
  2923. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  2924. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  2925. this.points = [];
  2926. this.target = new THREE.Vector3();
  2927. };
  2928. // Play
  2929. THREE.Animation.prototype.play = function( loop, startTimeMS ) {
  2930. if( !this.isPlaying ) {
  2931. this.isPlaying = true;
  2932. this.loop = loop !== undefined ? loop : true;
  2933. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  2934. // reset key cache
  2935. var h, hl = this.hierarchy.length,
  2936. object;
  2937. for ( h = 0; h < hl; h++ ) {
  2938. object = this.hierarchy[ h ];
  2939. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  2940. object.useQuaternion = true;
  2941. }
  2942. object.matrixAutoUpdate = true;
  2943. if ( object.animationCache === undefined ) {
  2944. object.animationCache = {};
  2945. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  2946. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  2947. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  2948. }
  2949. var prevKey = object.animationCache.prevKey;
  2950. var nextKey = object.animationCache.nextKey;
  2951. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  2952. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  2953. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  2954. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  2955. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  2956. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  2957. }
  2958. this.update( 0 );
  2959. }
  2960. this.isPaused = false;
  2961. THREE.AnimationHandler.addToUpdate( this );
  2962. };
  2963. // Pause
  2964. THREE.Animation.prototype.pause = function() {
  2965. if( this.isPaused ) {
  2966. THREE.AnimationHandler.addToUpdate( this );
  2967. } else {
  2968. THREE.AnimationHandler.removeFromUpdate( this );
  2969. }
  2970. this.isPaused = !this.isPaused;
  2971. };
  2972. // Stop
  2973. THREE.Animation.prototype.stop = function() {
  2974. this.isPlaying = false;
  2975. this.isPaused = false;
  2976. THREE.AnimationHandler.removeFromUpdate( this );
  2977. // reset JIT matrix and remove cache
  2978. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  2979. if ( this.hierarchy[ h ].animationCache !== undefined ) {
  2980. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  2981. this.hierarchy[ h ].skinMatrix = this.hierarchy[ h ].animationCache.originalMatrix;
  2982. } else {
  2983. this.hierarchy[ h ].matrix = this.hierarchy[ h ].animationCache.originalMatrix;
  2984. }
  2985. delete this.hierarchy[ h ].animationCache;
  2986. }
  2987. }
  2988. };
  2989. // Update
  2990. THREE.Animation.prototype.update = function( deltaTimeMS ) {
  2991. // early out
  2992. if( !this.isPlaying ) return;
  2993. // vars
  2994. var types = [ "pos", "rot", "scl" ];
  2995. var type;
  2996. var scale;
  2997. var vector;
  2998. var prevXYZ, nextXYZ;
  2999. var prevKey, nextKey;
  3000. var object;
  3001. var animationCache;
  3002. var frame;
  3003. var JIThierarchy = this.data.JIT.hierarchy;
  3004. var currentTime, unloopedCurrentTime;
  3005. var currentPoint, forwardPoint, angle;
  3006. // update
  3007. this.currentTime += deltaTimeMS * this.timeScale;
  3008. unloopedCurrentTime = this.currentTime;
  3009. currentTime = this.currentTime = this.currentTime % this.data.length;
  3010. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  3011. // update
  3012. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3013. object = this.hierarchy[ h ];
  3014. animationCache = object.animationCache;
  3015. // use JIT?
  3016. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  3017. if( object instanceof THREE.Bone ) {
  3018. object.skinMatrix = JIThierarchy[ h ][ frame ];
  3019. object.matrixAutoUpdate = false;
  3020. object.matrixWorldNeedsUpdate = false;
  3021. } else {
  3022. object.matrix = JIThierarchy[ h ][ frame ];
  3023. object.matrixAutoUpdate = false;
  3024. object.matrixWorldNeedsUpdate = true;
  3025. }
  3026. // use interpolation
  3027. } else {
  3028. // make sure so original matrix and not JIT matrix is set
  3029. if ( this.JITCompile ) {
  3030. if( object instanceof THREE.Bone ) {
  3031. object.skinMatrix = object.animationCache.originalMatrix;
  3032. } else {
  3033. object.matrix = object.animationCache.originalMatrix;
  3034. }
  3035. }
  3036. // loop through pos/rot/scl
  3037. for ( var t = 0; t < 3; t++ ) {
  3038. // get keys
  3039. type = types[ t ];
  3040. prevKey = animationCache.prevKey[ type ];
  3041. nextKey = animationCache.nextKey[ type ];
  3042. // switch keys?
  3043. if ( nextKey.time <= unloopedCurrentTime ) {
  3044. // did we loop?
  3045. if ( currentTime < unloopedCurrentTime ) {
  3046. if ( this.loop ) {
  3047. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  3048. nextKey = this.getNextKeyWith( type, h, 1 );
  3049. while( nextKey.time < currentTime ) {
  3050. prevKey = nextKey;
  3051. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  3052. }
  3053. } else {
  3054. this.stop();
  3055. return;
  3056. }
  3057. } else {
  3058. do {
  3059. prevKey = nextKey;
  3060. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  3061. } while( nextKey.time < currentTime )
  3062. }
  3063. animationCache.prevKey[ type ] = prevKey;
  3064. animationCache.nextKey[ type ] = nextKey;
  3065. }
  3066. object.matrixAutoUpdate = true;
  3067. object.matrixWorldNeedsUpdate = true;
  3068. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  3069. prevXYZ = prevKey[ type ];
  3070. nextXYZ = nextKey[ type ];
  3071. // check scale error
  3072. if ( scale < 0 || scale > 1 ) {
  3073. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  3074. scale = scale < 0 ? 0 : 1;
  3075. }
  3076. // interpolate
  3077. if ( type === "pos" ) {
  3078. vector = object.position;
  3079. if( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  3080. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  3081. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  3082. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  3083. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  3084. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3085. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  3086. this.points[ 1 ] = prevXYZ;
  3087. this.points[ 2 ] = nextXYZ;
  3088. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  3089. scale = scale * 0.33 + 0.33;
  3090. currentPoint = this.interpolateCatmullRom( this.points, scale );
  3091. vector.x = currentPoint[ 0 ];
  3092. vector.y = currentPoint[ 1 ];
  3093. vector.z = currentPoint[ 2 ];
  3094. if( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3095. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  3096. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  3097. this.target.subSelf( vector );
  3098. this.target.y = 0;
  3099. this.target.normalize();
  3100. angle = Math.atan2( this.target.x, this.target.z );
  3101. object.rotation.set( 0, angle, 0 );
  3102. }
  3103. }
  3104. } else if ( type === "rot" ) {
  3105. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  3106. } else if( type === "scl" ) {
  3107. vector = object.scale;
  3108. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  3109. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  3110. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  3111. }
  3112. }
  3113. }
  3114. }
  3115. // update JIT?
  3116. if ( this.JITCompile ) {
  3117. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  3118. this.hierarchy[ 0 ].updateMatrixWorld( true );
  3119. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  3120. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  3121. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  3122. } else {
  3123. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  3124. }
  3125. }
  3126. }
  3127. }
  3128. };
  3129. // Catmull-Rom spline
  3130. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  3131. var c = [], v3 = [],
  3132. point, intPoint, weight, w2, w3,
  3133. pa, pb, pc, pd;
  3134. point = ( points.length - 1 ) * scale;
  3135. intPoint = Math.floor( point );
  3136. weight = point - intPoint;
  3137. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3138. c[ 1 ] = intPoint;
  3139. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  3140. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  3141. pa = points[ c[ 0 ] ];
  3142. pb = points[ c[ 1 ] ];
  3143. pc = points[ c[ 2 ] ];
  3144. pd = points[ c[ 3 ] ];
  3145. w2 = weight * weight;
  3146. w3 = weight * w2;
  3147. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  3148. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  3149. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  3150. return v3;
  3151. };
  3152. THREE.Animation.prototype.interpolate = function( p0, p1, p2, p3, t, t2, t3 ) {
  3153. var v0 = ( p2 - p0 ) * 0.5,
  3154. v1 = ( p3 - p1 ) * 0.5;
  3155. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3156. };
  3157. // Get next key with
  3158. THREE.Animation.prototype.getNextKeyWith = function( type, h, key ) {
  3159. var keys = this.data.hierarchy[ h ].keys;
  3160. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  3161. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3162. key = key < keys.length - 1 ? key : keys.length - 1;
  3163. } else {
  3164. key = key % keys.length;
  3165. }
  3166. for ( ; key < keys.length; key++ ) {
  3167. if ( keys[ key ][ type ] !== undefined ) {
  3168. return keys[ key ];
  3169. }
  3170. }
  3171. return this.data.hierarchy[ h ].keys[ 0 ];
  3172. };
  3173. // Get previous key with
  3174. THREE.Animation.prototype.getPrevKeyWith = function( type, h, key ) {
  3175. var keys = this.data.hierarchy[ h ].keys;
  3176. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  3177. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3178. key = key > 0 ? key : 0;
  3179. } else {
  3180. key = key >= 0 ? key : key + keys.length;
  3181. }
  3182. for ( ; key >= 0; key-- ) {
  3183. if ( keys[ key ][ type ] !== undefined ) {
  3184. return keys[ key ];
  3185. }
  3186. }
  3187. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  3188. };/**
  3189. * @author mikael emtinger / http://gomo.se/
  3190. * @author mrdoob / http://mrdoob.com/
  3191. * @author alteredq / http://alteredqualia.com/
  3192. * @author khang duong
  3193. * @author erik kitson
  3194. */
  3195. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  3196. this.root = root;
  3197. this.data = THREE.AnimationHandler.get( data );
  3198. this.hierarchy = THREE.AnimationHandler.parse( root );
  3199. this.currentTime = 0;
  3200. this.timeScale = 0.001;
  3201. this.isPlaying = false;
  3202. this.isPaused = true;
  3203. this.loop = true;
  3204. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  3205. // initialize to first keyframes
  3206. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3207. var keys = this.data.hierarchy[h].keys,
  3208. sids = this.data.hierarchy[h].sids,
  3209. obj = this.hierarchy[h];
  3210. if ( keys.length && sids ) {
  3211. for ( var s = 0; s < sids.length; s++ ) {
  3212. var sid = sids[ s ],
  3213. next = this.getNextKeyWith( sid, h, 0 );
  3214. if ( next ) {
  3215. next.apply( sid );
  3216. }
  3217. }
  3218. obj.matrixAutoUpdate = false;
  3219. this.data.hierarchy[h].node.updateMatrix();
  3220. obj.matrixWorldNeedsUpdate = true;
  3221. }
  3222. }
  3223. };
  3224. // Play
  3225. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  3226. if( !this.isPlaying ) {
  3227. this.isPlaying = true;
  3228. this.loop = loop !== undefined ? loop : true;
  3229. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  3230. this.startTimeMs = startTimeMS;
  3231. this.startTime = 10000000;
  3232. this.endTime = -this.startTime;
  3233. // reset key cache
  3234. var h, hl = this.hierarchy.length,
  3235. object,
  3236. node;
  3237. for ( h = 0; h < hl; h++ ) {
  3238. object = this.hierarchy[ h ];
  3239. node = this.data.hierarchy[ h ];
  3240. object.useQuaternion = true;
  3241. if ( node.animationCache === undefined ) {
  3242. node.animationCache = {};
  3243. node.animationCache.prevKey = null;
  3244. node.animationCache.nextKey = null;
  3245. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  3246. }
  3247. var keys = this.data.hierarchy[h].keys;
  3248. if (keys.length) {
  3249. node.animationCache.prevKey = keys[ 0 ];
  3250. node.animationCache.nextKey = keys[ 1 ];
  3251. this.startTime = Math.min( keys[0].time, this.startTime );
  3252. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  3253. }
  3254. }
  3255. this.update( 0 );
  3256. }
  3257. this.isPaused = false;
  3258. THREE.AnimationHandler.addToUpdate( this );
  3259. };
  3260. // Pause
  3261. THREE.KeyFrameAnimation.prototype.pause = function() {
  3262. if( this.isPaused ) {
  3263. THREE.AnimationHandler.addToUpdate( this );
  3264. } else {
  3265. THREE.AnimationHandler.removeFromUpdate( this );
  3266. }
  3267. this.isPaused = !this.isPaused;
  3268. };
  3269. // Stop
  3270. THREE.KeyFrameAnimation.prototype.stop = function() {
  3271. this.isPlaying = false;
  3272. this.isPaused = false;
  3273. THREE.AnimationHandler.removeFromUpdate( this );
  3274. // reset JIT matrix and remove cache
  3275. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  3276. var obj = this.hierarchy[ h ];
  3277. var node = this.data.hierarchy[ h ];
  3278. if ( node.animationCache !== undefined ) {
  3279. var original = node.animationCache.originalMatrix;
  3280. if( obj instanceof THREE.Bone ) {
  3281. original.copy( obj.skinMatrix );
  3282. obj.skinMatrix = original;
  3283. } else {
  3284. original.copy( obj.matrix );
  3285. obj.matrix = original;
  3286. }
  3287. delete node.animationCache;
  3288. }
  3289. }
  3290. };
  3291. // Update
  3292. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  3293. // early out
  3294. if( !this.isPlaying ) return;
  3295. // vars
  3296. var prevKey, nextKey;
  3297. var object;
  3298. var node;
  3299. var frame;
  3300. var JIThierarchy = this.data.JIT.hierarchy;
  3301. var currentTime, unloopedCurrentTime;
  3302. var looped;
  3303. // update
  3304. this.currentTime += deltaTimeMS * this.timeScale;
  3305. unloopedCurrentTime = this.currentTime;
  3306. currentTime = this.currentTime = this.currentTime % this.data.length;
  3307. // if looped around, the current time should be based on the startTime
  3308. if ( currentTime < this.startTimeMs ) {
  3309. currentTime = this.currentTime = this.startTimeMs + currentTime;
  3310. }
  3311. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  3312. looped = currentTime < unloopedCurrentTime;
  3313. if ( looped && !this.loop ) {
  3314. // Set the animation to the last keyframes and stop
  3315. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3316. var keys = this.data.hierarchy[h].keys,
  3317. sids = this.data.hierarchy[h].sids,
  3318. end = keys.length-1,
  3319. obj = this.hierarchy[h];
  3320. if ( keys.length ) {
  3321. for ( var s = 0; s < sids.length; s++ ) {
  3322. var sid = sids[ s ],
  3323. prev = this.getPrevKeyWith( sid, h, end );
  3324. if ( prev ) {
  3325. prev.apply( sid );
  3326. }
  3327. }
  3328. this.data.hierarchy[h].node.updateMatrix();
  3329. obj.matrixWorldNeedsUpdate = true;
  3330. }
  3331. }
  3332. this.stop();
  3333. return;
  3334. }
  3335. // check pre-infinity
  3336. if ( currentTime < this.startTime ) {
  3337. return;
  3338. }
  3339. // update
  3340. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3341. object = this.hierarchy[ h ];
  3342. node = this.data.hierarchy[ h ];
  3343. var keys = node.keys,
  3344. animationCache = node.animationCache;
  3345. // use JIT?
  3346. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  3347. if( object instanceof THREE.Bone ) {
  3348. object.skinMatrix = JIThierarchy[ h ][ frame ];
  3349. object.matrixWorldNeedsUpdate = false;
  3350. } else {
  3351. object.matrix = JIThierarchy[ h ][ frame ];
  3352. object.matrixWorldNeedsUpdate = true;
  3353. }
  3354. // use interpolation
  3355. } else if ( keys.length ) {
  3356. // make sure so original matrix and not JIT matrix is set
  3357. if ( this.JITCompile && animationCache ) {
  3358. if( object instanceof THREE.Bone ) {
  3359. object.skinMatrix = animationCache.originalMatrix;
  3360. } else {
  3361. object.matrix = animationCache.originalMatrix;
  3362. }
  3363. }
  3364. prevKey = animationCache.prevKey;
  3365. nextKey = animationCache.nextKey;
  3366. if ( prevKey && nextKey ) {
  3367. // switch keys?
  3368. if ( nextKey.time <= unloopedCurrentTime ) {
  3369. // did we loop?
  3370. if ( looped && this.loop ) {
  3371. prevKey = keys[ 0 ];
  3372. nextKey = keys[ 1 ];
  3373. while ( nextKey.time < currentTime ) {
  3374. prevKey = nextKey;
  3375. nextKey = keys[ prevKey.index + 1 ];
  3376. }
  3377. } else if ( !looped ) {
  3378. var lastIndex = keys.length - 1;
  3379. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  3380. prevKey = nextKey;
  3381. nextKey = keys[ prevKey.index + 1 ];
  3382. }
  3383. }
  3384. animationCache.prevKey = prevKey;
  3385. animationCache.nextKey = nextKey;
  3386. }
  3387. if(nextKey.time >= currentTime)
  3388. prevKey.interpolate( nextKey, currentTime );
  3389. else
  3390. prevKey.interpolate( nextKey, nextKey.time);
  3391. }
  3392. this.data.hierarchy[h].node.updateMatrix();
  3393. object.matrixWorldNeedsUpdate = true;
  3394. }
  3395. }
  3396. // update JIT?
  3397. if ( this.JITCompile ) {
  3398. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  3399. this.hierarchy[ 0 ].updateMatrixWorld( true );
  3400. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  3401. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  3402. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  3403. } else {
  3404. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  3405. }
  3406. }
  3407. }
  3408. }
  3409. };
  3410. // Get next key with
  3411. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  3412. var keys = this.data.hierarchy[ h ].keys;
  3413. key = key % keys.length;
  3414. for ( ; key < keys.length; key++ ) {
  3415. if ( keys[ key ].hasTarget( sid ) ) {
  3416. return keys[ key ];
  3417. }
  3418. }
  3419. return keys[ 0 ];
  3420. };
  3421. // Get previous key with
  3422. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  3423. var keys = this.data.hierarchy[ h ].keys;
  3424. key = key >= 0 ? key : key + keys.length;
  3425. for ( ; key >= 0; key-- ) {
  3426. if ( keys[ key ].hasTarget( sid ) ) {
  3427. return keys[ key ];
  3428. }
  3429. }
  3430. return keys[ keys.length - 1 ];
  3431. };
  3432. /**
  3433. * Camera for rendering cube maps
  3434. * - renders scene into axis-aligned cube
  3435. *
  3436. * @author alteredq / http://alteredqualia.com/
  3437. */
  3438. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  3439. THREE.Object3D.call( this );
  3440. var fov = 90, aspect = 1;
  3441. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3442. cameraPX.up.set( 0, -1, 0 );
  3443. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  3444. this.add( cameraPX );
  3445. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3446. cameraNX.up.set( 0, -1, 0 );
  3447. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  3448. this.add( cameraNX );
  3449. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3450. cameraPY.up.set( 0, 0, 1 );
  3451. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  3452. this.add( cameraPY );
  3453. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3454. cameraNY.up.set( 0, 0, -1 );
  3455. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  3456. this.add( cameraNY );
  3457. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3458. cameraPZ.up.set( 0, -1, 0 );
  3459. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  3460. this.add( cameraPZ );
  3461. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3462. cameraNZ.up.set( 0, -1, 0 );
  3463. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  3464. this.add( cameraNZ );
  3465. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  3466. this.updateCubeMap = function ( renderer, scene ) {
  3467. var renderTarget = this.renderTarget;
  3468. var generateMipmaps = renderTarget.generateMipmaps;
  3469. renderTarget.generateMipmaps = false;
  3470. renderTarget.activeCubeFace = 0;
  3471. renderer.render( scene, cameraPX, renderTarget );
  3472. renderTarget.activeCubeFace = 1;
  3473. renderer.render( scene, cameraNX, renderTarget );
  3474. renderTarget.activeCubeFace = 2;
  3475. renderer.render( scene, cameraPY, renderTarget );
  3476. renderTarget.activeCubeFace = 3;
  3477. renderer.render( scene, cameraNY, renderTarget );
  3478. renderTarget.activeCubeFace = 4;
  3479. renderer.render( scene, cameraPZ, renderTarget );
  3480. renderTarget.generateMipmaps = generateMipmaps;
  3481. renderTarget.activeCubeFace = 5;
  3482. renderer.render( scene, cameraNZ, renderTarget );
  3483. };
  3484. };
  3485. THREE.CubeCamera.prototype = new THREE.Object3D();
  3486. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  3487. /*
  3488. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  3489. *
  3490. * A general perpose camera, for setting FOV, Lens Focal Length,
  3491. * and switching between perspective and orthographic views easily.
  3492. * Use this only if you do not wish to manage
  3493. * both a Orthographic and Perspective Camera
  3494. *
  3495. */
  3496. THREE.CombinedCamera = function ( width, height, fov, near, far, orthonear, orthofar ) {
  3497. THREE.Camera.call( this );
  3498. this.fov = fov;
  3499. this.left = -width / 2;
  3500. this.right = width / 2
  3501. this.top = height / 2;
  3502. this.bottom = -height / 2;
  3503. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  3504. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthonear, orthofar );
  3505. this.cameraP = new THREE.PerspectiveCamera( fov, width/height, near, far );
  3506. this.zoom = 1;
  3507. this.toPerspective();
  3508. var aspect = width/height;
  3509. };
  3510. THREE.CombinedCamera.prototype = new THREE.Camera();
  3511. THREE.CombinedCamera.prototype.constructor = THREE.CombinedCamera;
  3512. THREE.CombinedCamera.prototype.toPerspective = function () {
  3513. // Switches to the Perspective Camera
  3514. this.near = this.cameraP.near;
  3515. this.far = this.cameraP.far;
  3516. this.cameraP.fov = this.fov / this.zoom ;
  3517. this.cameraP.updateProjectionMatrix();
  3518. this.projectionMatrix = this.cameraP.projectionMatrix;
  3519. this.inPersepectiveMode = true;
  3520. this.inOrthographicMode = false;
  3521. };
  3522. THREE.CombinedCamera.prototype.toOrthographic = function () {
  3523. // Switches to the Orthographic camera estimating viewport from Perspective
  3524. var fov = this.fov;
  3525. var aspect = this.cameraP.aspect;
  3526. var near = this.cameraP.near;
  3527. var far = this.cameraP.far;
  3528. // The size that we set is the mid plane of the viewing frustum
  3529. var hyperfocus = ( near + far ) / 2;
  3530. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  3531. var planeHeight = 2 * halfHeight;
  3532. var planeWidth = planeHeight * aspect;
  3533. var halfWidth = planeWidth / 2;
  3534. halfHeight /= this.zoom;
  3535. halfWidth /= this.zoom;
  3536. this.cameraO.left = -halfWidth;
  3537. this.cameraO.right = halfWidth;
  3538. this.cameraO.top = halfHeight;
  3539. this.cameraO.bottom = -halfHeight;
  3540. // this.cameraO.left = -farHalfWidth;
  3541. // this.cameraO.right = farHalfWidth;
  3542. // this.cameraO.top = farHalfHeight;
  3543. // this.cameraO.bottom = -farHalfHeight;
  3544. // this.cameraO.left = this.left / this.zoom;
  3545. // this.cameraO.right = this.right / this.zoom;
  3546. // this.cameraO.top = this.top / this.zoom;
  3547. // this.cameraO.bottom = this.bottom / this.zoom;
  3548. this.cameraO.updateProjectionMatrix();
  3549. this.near = this.cameraO.near;
  3550. this.far = this.cameraO.far;
  3551. this.projectionMatrix = this.cameraO.projectionMatrix;
  3552. this.inPersepectiveMode = false;
  3553. this.inOrthographicMode = true;
  3554. };
  3555. THREE.CombinedCamera.prototype.setSize = function(width, height) {
  3556. this.cameraP.aspect = width / height;
  3557. this.left = -width / 2;
  3558. this.right = width / 2
  3559. this.top = height / 2;
  3560. this.bottom = -height / 2;
  3561. }
  3562. THREE.CombinedCamera.prototype.setFov = function(fov) {
  3563. this.fov = fov;
  3564. if (this.inPersepectiveMode) {
  3565. this.toPerspective();
  3566. } else {
  3567. this.toOrthographic();
  3568. }
  3569. };
  3570. // For mantaining similar API with PerspectiveCamera
  3571. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  3572. if (this.inPersepectiveMode) {
  3573. this.toPerspective();
  3574. } else {
  3575. this.toPerspective();
  3576. this.toOrthographic();
  3577. }
  3578. };
  3579. /*
  3580. * Uses Focal Length (in mm) to estimate and set FOV
  3581. * 35mm (fullframe) camera is used if frame size is not specified;
  3582. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3583. */
  3584. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3585. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  3586. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3587. this.setFov( fov );
  3588. return fov;
  3589. };
  3590. THREE.CombinedCamera.prototype.setZoom = function(zoom) {
  3591. this.zoom = zoom;
  3592. if (this.inPersepectiveMode) {
  3593. this.toPerspective();
  3594. } else {
  3595. this.toOrthographic();
  3596. }
  3597. };
  3598. THREE.CombinedCamera.prototype.toFrontView = function() {
  3599. this.rotation.x = 0;
  3600. this.rotation.y = 0;
  3601. this.rotation.z = 0;
  3602. // should we be modifing the matrix instead?
  3603. this.rotationAutoUpdate = false;
  3604. };
  3605. THREE.CombinedCamera.prototype.toBackView = function() {
  3606. this.rotation.x = 0;
  3607. this.rotation.y = Math.PI;
  3608. this.rotation.z = 0;
  3609. this.rotationAutoUpdate = false;
  3610. };
  3611. THREE.CombinedCamera.prototype.toLeftView = function() {
  3612. this.rotation.x = 0;
  3613. this.rotation.y = - Math.PI / 2;
  3614. this.rotation.z = 0;
  3615. this.rotationAutoUpdate = false;
  3616. };
  3617. THREE.CombinedCamera.prototype.toRightView = function() {
  3618. this.rotation.x = 0;
  3619. this.rotation.y = Math.PI / 2;
  3620. this.rotation.z = 0;
  3621. this.rotationAutoUpdate = false;
  3622. };
  3623. THREE.CombinedCamera.prototype.toTopView = function() {
  3624. this.rotation.x = - Math.PI / 2;
  3625. this.rotation.y = 0;
  3626. this.rotation.z = 0;
  3627. this.rotationAutoUpdate = false;
  3628. };
  3629. THREE.CombinedCamera.prototype.toBottomView = function() {
  3630. this.rotation.x = Math.PI / 2;
  3631. this.rotation.y = 0;
  3632. this.rotation.z = 0;
  3633. this.rotationAutoUpdate = false;
  3634. };
  3635. /**
  3636. * @author mrdoob / http://mrdoob.com/
  3637. * @author alteredq / http://alteredqualia.com/
  3638. * @author paulirish / http://paulirish.com/
  3639. */
  3640. THREE.FirstPersonControls = function ( object, domElement ) {
  3641. this.object = object;
  3642. this.target = new THREE.Vector3( 0, 0, 0 );
  3643. this.domElement = ( domElement !== undefined ) ? domElement : document;
  3644. this.movementSpeed = 1.0;
  3645. this.lookSpeed = 0.005;
  3646. this.noFly = false;
  3647. this.lookVertical = true;
  3648. this.autoForward = false;
  3649. this.activeLook = true;
  3650. this.heightSpeed = false;
  3651. this.heightCoef = 1.0;
  3652. this.heightMin = 0.0;
  3653. this.constrainVertical = false;
  3654. this.verticalMin = 0;
  3655. this.verticalMax = Math.PI;
  3656. this.autoSpeedFactor = 0.0;
  3657. this.mouseX = 0;
  3658. this.mouseY = 0;
  3659. this.lat = 0;
  3660. this.lon = 0;
  3661. this.phi = 0;
  3662. this.theta = 0;
  3663. this.moveForward = false;
  3664. this.moveBackward = false;
  3665. this.moveLeft = false;
  3666. this.moveRight = false;
  3667. this.freeze = false;
  3668. this.mouseDragOn = false;
  3669. if ( this.domElement === document ) {
  3670. this.viewHalfX = window.innerWidth / 2;
  3671. this.viewHalfY = window.innerHeight / 2;
  3672. } else {
  3673. this.viewHalfX = this.domElement.offsetWidth / 2;
  3674. this.viewHalfY = this.domElement.offsetHeight / 2;
  3675. this.domElement.setAttribute( 'tabindex', -1 );
  3676. }
  3677. this.onMouseDown = function ( event ) {
  3678. if ( this.domElement !== document ) {
  3679. this.domElement.focus();
  3680. }
  3681. event.preventDefault();
  3682. event.stopPropagation();
  3683. if ( this.activeLook ) {
  3684. switch ( event.button ) {
  3685. case 0: this.moveForward = true; break;
  3686. case 2: this.moveBackward = true; break;
  3687. }
  3688. }
  3689. this.mouseDragOn = true;
  3690. };
  3691. this.onMouseUp = function ( event ) {
  3692. event.preventDefault();
  3693. event.stopPropagation();
  3694. if ( this.activeLook ) {
  3695. switch ( event.button ) {
  3696. case 0: this.moveForward = false; break;
  3697. case 2: this.moveBackward = false; break;
  3698. }
  3699. }
  3700. this.mouseDragOn = false;
  3701. };
  3702. this.onMouseMove = function ( event ) {
  3703. if ( this.domElement === document ) {
  3704. this.mouseX = event.pageX - this.viewHalfX;
  3705. this.mouseY = event.pageY - this.viewHalfY;
  3706. } else {
  3707. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  3708. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  3709. }
  3710. };
  3711. this.onKeyDown = function ( event ) {
  3712. switch( event.keyCode ) {
  3713. case 38: /*up*/
  3714. case 87: /*W*/ this.moveForward = true; break;
  3715. case 37: /*left*/
  3716. case 65: /*A*/ this.moveLeft = true; break;
  3717. case 40: /*down*/
  3718. case 83: /*S*/ this.moveBackward = true; break;
  3719. case 39: /*right*/
  3720. case 68: /*D*/ this.moveRight = true; break;
  3721. case 82: /*R*/ this.moveUp = true; break;
  3722. case 70: /*F*/ this.moveDown = true; break;
  3723. case 81: /*Q*/ this.freeze = !this.freeze; break;
  3724. }
  3725. };
  3726. this.onKeyUp = function ( event ) {
  3727. switch( event.keyCode ) {
  3728. case 38: /*up*/
  3729. case 87: /*W*/ this.moveForward = false; break;
  3730. case 37: /*left*/
  3731. case 65: /*A*/ this.moveLeft = false; break;
  3732. case 40: /*down*/
  3733. case 83: /*S*/ this.moveBackward = false; break;
  3734. case 39: /*right*/
  3735. case 68: /*D*/ this.moveRight = false; break;
  3736. case 82: /*R*/ this.moveUp = false; break;
  3737. case 70: /*F*/ this.moveDown = false; break;
  3738. }
  3739. };
  3740. this.update = function( delta ) {
  3741. var actualMoveSpeed = 0;
  3742. if ( this.freeze ) {
  3743. return;
  3744. } else {
  3745. if ( this.heightSpeed ) {
  3746. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  3747. var heightDelta = y - this.heightMin;
  3748. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  3749. } else {
  3750. this.autoSpeedFactor = 0.0;
  3751. }
  3752. actualMoveSpeed = delta * this.movementSpeed;
  3753. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  3754. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  3755. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  3756. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  3757. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  3758. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  3759. var actualLookSpeed = delta * this.lookSpeed;
  3760. if ( !this.activeLook ) {
  3761. actualLookSpeed = 0;
  3762. }
  3763. this.lon += this.mouseX * actualLookSpeed;
  3764. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed;
  3765. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  3766. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  3767. this.theta = this.lon * Math.PI / 180;
  3768. var targetPosition = this.target,
  3769. position = this.object.position;
  3770. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  3771. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  3772. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  3773. }
  3774. var verticalLookRatio = 1;
  3775. if ( this.constrainVertical ) {
  3776. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  3777. }
  3778. this.lon += this.mouseX * actualLookSpeed;
  3779. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  3780. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  3781. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  3782. this.theta = this.lon * Math.PI / 180;
  3783. if ( this.constrainVertical ) {
  3784. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  3785. }
  3786. var targetPosition = this.target,
  3787. position = this.object.position;
  3788. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  3789. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  3790. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  3791. this.object.lookAt( targetPosition );
  3792. };
  3793. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  3794. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  3795. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  3796. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  3797. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  3798. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  3799. function bind( scope, fn ) {
  3800. return function () {
  3801. fn.apply( scope, arguments );
  3802. };
  3803. };
  3804. };
  3805. /**
  3806. * @author alteredq / http://alteredqualia.com/
  3807. */
  3808. THREE.PathControls = function ( object, domElement ) {
  3809. this.object = object;
  3810. this.domElement = ( domElement !== undefined ) ? domElement : document;
  3811. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  3812. // API
  3813. this.duration = 10 * 1000; // milliseconds
  3814. this.waypoints = [];
  3815. this.useConstantSpeed = true;
  3816. this.resamplingCoef = 50;
  3817. this.debugPath = new THREE.Object3D();
  3818. this.debugDummy = new THREE.Object3D();
  3819. this.animationParent = new THREE.Object3D();
  3820. this.lookSpeed = 0.005;
  3821. this.lookVertical = true;
  3822. this.lookHorizontal = true;
  3823. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  3824. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  3825. // internals
  3826. this.target = new THREE.Object3D();
  3827. this.mouseX = 0;
  3828. this.mouseY = 0;
  3829. this.lat = 0;
  3830. this.lon = 0;
  3831. this.phi = 0;
  3832. this.theta = 0;
  3833. if ( this.domElement === document ) {
  3834. this.viewHalfX = window.innerWidth / 2;
  3835. this.viewHalfY = window.innerHeight / 2;
  3836. } else {
  3837. this.viewHalfX = this.domElement.offsetWidth / 2;
  3838. this.viewHalfY = this.domElement.offsetHeight / 2;
  3839. this.domElement.setAttribute( 'tabindex', -1 );
  3840. }
  3841. var PI2 = Math.PI * 2,
  3842. PI180 = Math.PI / 180;
  3843. // methods
  3844. this.update = function ( delta ) {
  3845. var srcRange, dstRange;
  3846. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  3847. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  3848. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  3849. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  3850. this.phi = ( 90 - this.lat ) * PI180;
  3851. this.theta = this.lon * PI180;
  3852. this.phi = normalize_angle_rad( this.phi );
  3853. // constrain vertical look angle
  3854. srcRange = this.verticalAngleMap.srcRange;
  3855. dstRange = this.verticalAngleMap.dstRange;
  3856. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  3857. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  3858. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  3859. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  3860. // constrain horizontal look angle
  3861. srcRange = this.horizontalAngleMap.srcRange;
  3862. dstRange = this.horizontalAngleMap.dstRange;
  3863. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  3864. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  3865. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  3866. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  3867. var targetPosition = this.target.position,
  3868. position = this.object.position;
  3869. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  3870. targetPosition.y = 100 * Math.cos( this.phi );
  3871. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  3872. this.object.lookAt( this.target.position );
  3873. };
  3874. this.onMouseMove = function ( event ) {
  3875. if ( this.domElement === document ) {
  3876. this.mouseX = event.pageX - this.viewHalfX;
  3877. this.mouseY = event.pageY - this.viewHalfY;
  3878. } else {
  3879. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  3880. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  3881. }
  3882. };
  3883. // utils
  3884. function normalize_angle_rad( a ) {
  3885. var b = a % PI2;
  3886. return b >= 0 ? b : b + PI2;
  3887. };
  3888. function distance( a, b ) {
  3889. var dx = a[ 0 ] - b[ 0 ],
  3890. dy = a[ 1 ] - b[ 1 ],
  3891. dz = a[ 2 ] - b[ 2 ];
  3892. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  3893. };
  3894. function QuadraticEaseInOut ( k ) {
  3895. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  3896. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  3897. };
  3898. function bind( scope, fn ) {
  3899. return function () {
  3900. fn.apply( scope, arguments );
  3901. };
  3902. };
  3903. function initAnimationPath( parent, spline, name, duration ) {
  3904. var animationData = {
  3905. name: name,
  3906. fps: 0.6,
  3907. length: duration,
  3908. hierarchy: []
  3909. };
  3910. var i,
  3911. parentAnimation, childAnimation,
  3912. path = spline.getControlPointsArray(),
  3913. sl = spline.getLength(),
  3914. pl = path.length,
  3915. t = 0,
  3916. first = 0,
  3917. last = pl - 1;
  3918. parentAnimation = { parent: -1, keys: [] };
  3919. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  3920. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  3921. for ( i = 1; i < pl - 1; i++ ) {
  3922. // real distance (approximation via linear segments)
  3923. t = duration * sl.chunks[ i ] / sl.total;
  3924. // equal distance
  3925. //t = duration * ( i / pl );
  3926. // linear distance
  3927. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  3928. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  3929. }
  3930. animationData.hierarchy[ 0 ] = parentAnimation;
  3931. THREE.AnimationHandler.add( animationData );
  3932. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  3933. };
  3934. function createSplineGeometry( spline, n_sub ) {
  3935. var i, index, position,
  3936. geometry = new THREE.Geometry();
  3937. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  3938. index = i / ( spline.points.length * n_sub );
  3939. position = spline.getPoint( index );
  3940. geometry.vertices[ i ] = new THREE.Vector3( position.x, position.y, position.z );
  3941. }
  3942. return geometry;
  3943. };
  3944. function createPath( parent, spline ) {
  3945. var lineGeo = createSplineGeometry( spline, 10 ),
  3946. particleGeo = createSplineGeometry( spline, 10 ),
  3947. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  3948. lineObj = new THREE.Line( lineGeo, lineMat ),
  3949. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  3950. lineObj.scale.set( 1, 1, 1 );
  3951. parent.add( lineObj );
  3952. particleObj.scale.set( 1, 1, 1 );
  3953. parent.add( particleObj );
  3954. var waypoint,
  3955. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  3956. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  3957. for ( var i = 0; i < spline.points.length; i ++ ) {
  3958. waypoint = new THREE.Mesh( geo, mat );
  3959. waypoint.position.copy( spline.points[ i ] );
  3960. parent.add( waypoint );
  3961. }
  3962. };
  3963. this.init = function ( ) {
  3964. // constructor
  3965. this.spline = new THREE.Spline();
  3966. this.spline.initFromArray( this.waypoints );
  3967. if ( this.useConstantSpeed ) {
  3968. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  3969. }
  3970. if ( this.createDebugDummy ) {
  3971. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  3972. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  3973. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  3974. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  3975. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  3976. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  3977. dummyChild.position.set( 0, 10, 0 );
  3978. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  3979. this.animationParent.add( this.object );
  3980. this.animationParent.add( this.target );
  3981. this.animationParent.add( dummyChild );
  3982. } else {
  3983. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  3984. this.animationParent.add( this.target );
  3985. this.animationParent.add( this.object );
  3986. }
  3987. if ( this.createDebugPath ) {
  3988. createPath( this.debugPath, this.spline );
  3989. }
  3990. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  3991. };
  3992. };
  3993. THREE.PathControlsIdCounter = 0;
  3994. /**
  3995. * @author James Baicoianu / http://www.baicoianu.com/
  3996. */
  3997. THREE.FlyControls = function ( object, domElement ) {
  3998. this.object = object;
  3999. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4000. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  4001. // API
  4002. this.movementSpeed = 1.0;
  4003. this.rollSpeed = 0.005;
  4004. this.dragToLook = false;
  4005. this.autoForward = false;
  4006. // disable default target object behavior
  4007. this.object.useQuaternion = true;
  4008. // internals
  4009. this.tmpQuaternion = new THREE.Quaternion();
  4010. this.mouseStatus = 0;
  4011. this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
  4012. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  4013. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  4014. this.handleEvent = function ( event ) {
  4015. if ( typeof this[ event.type ] == 'function' ) {
  4016. this[ event.type ]( event );
  4017. }
  4018. };
  4019. this.keydown = function( event ) {
  4020. if ( event.altKey ) {
  4021. return;
  4022. }
  4023. switch( event.keyCode ) {
  4024. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  4025. case 87: /*W*/ this.moveState.forward = 1; break;
  4026. case 83: /*S*/ this.moveState.back = 1; break;
  4027. case 65: /*A*/ this.moveState.left = 1; break;
  4028. case 68: /*D*/ this.moveState.right = 1; break;
  4029. case 82: /*R*/ this.moveState.up = 1; break;
  4030. case 70: /*F*/ this.moveState.down = 1; break;
  4031. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  4032. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  4033. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  4034. case 39: /*right*/ this.moveState.yawRight = 1; break;
  4035. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  4036. case 69: /*E*/ this.moveState.rollRight = 1; break;
  4037. }
  4038. this.updateMovementVector();
  4039. this.updateRotationVector();
  4040. };
  4041. this.keyup = function( event ) {
  4042. switch( event.keyCode ) {
  4043. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  4044. case 87: /*W*/ this.moveState.forward = 0; break;
  4045. case 83: /*S*/ this.moveState.back = 0; break;
  4046. case 65: /*A*/ this.moveState.left = 0; break;
  4047. case 68: /*D*/ this.moveState.right = 0; break;
  4048. case 82: /*R*/ this.moveState.up = 0; break;
  4049. case 70: /*F*/ this.moveState.down = 0; break;
  4050. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  4051. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  4052. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  4053. case 39: /*right*/ this.moveState.yawRight = 0; break;
  4054. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  4055. case 69: /*E*/ this.moveState.rollRight = 0; break;
  4056. }
  4057. this.updateMovementVector();
  4058. this.updateRotationVector();
  4059. };
  4060. this.mousedown = function( event ) {
  4061. if ( this.domElement !== document ) {
  4062. this.domElement.focus();
  4063. }
  4064. event.preventDefault();
  4065. event.stopPropagation();
  4066. if ( this.dragToLook ) {
  4067. this.mouseStatus ++;
  4068. } else {
  4069. switch ( event.button ) {
  4070. case 0: this.object.moveForward = true; break;
  4071. case 2: this.object.moveBackward = true; break;
  4072. }
  4073. }
  4074. };
  4075. this.mousemove = function( event ) {
  4076. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  4077. var container = this.getContainerDimensions();
  4078. var halfWidth = container.size[ 0 ] / 2;
  4079. var halfHeight = container.size[ 1 ] / 2;
  4080. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  4081. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  4082. this.updateRotationVector();
  4083. }
  4084. };
  4085. this.mouseup = function( event ) {
  4086. event.preventDefault();
  4087. event.stopPropagation();
  4088. if ( this.dragToLook ) {
  4089. this.mouseStatus --;
  4090. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  4091. } else {
  4092. switch ( event.button ) {
  4093. case 0: this.moveForward = false; break;
  4094. case 2: this.moveBackward = false; break;
  4095. }
  4096. }
  4097. this.updateRotationVector();
  4098. };
  4099. this.update = function( delta ) {
  4100. var moveMult = delta * this.movementSpeed;
  4101. var rotMult = delta * this.rollSpeed;
  4102. this.object.translateX( this.moveVector.x * moveMult );
  4103. this.object.translateY( this.moveVector.y * moveMult );
  4104. this.object.translateZ( this.moveVector.z * moveMult );
  4105. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  4106. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  4107. this.object.matrix.setPosition( this.object.position );
  4108. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  4109. this.object.matrixWorldNeedsUpdate = true;
  4110. };
  4111. this.updateMovementVector = function() {
  4112. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  4113. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  4114. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  4115. this.moveVector.z = ( -forward + this.moveState.back );
  4116. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  4117. };
  4118. this.updateRotationVector = function() {
  4119. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  4120. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  4121. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  4122. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  4123. };
  4124. this.getContainerDimensions = function() {
  4125. if ( this.domElement != document ) {
  4126. return {
  4127. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  4128. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  4129. };
  4130. } else {
  4131. return {
  4132. size : [ window.innerWidth, window.innerHeight ],
  4133. offset : [ 0, 0 ]
  4134. };
  4135. }
  4136. };
  4137. function bind( scope, fn ) {
  4138. return function () {
  4139. fn.apply( scope, arguments );
  4140. };
  4141. };
  4142. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  4143. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  4144. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  4145. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  4146. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  4147. this.updateMovementVector();
  4148. this.updateRotationVector();
  4149. };
  4150. /**
  4151. * @author mikael emtinger / http://gomo.se/
  4152. * @author alteredq / http://alteredqualia.com/
  4153. */
  4154. THREE.RollControls = function ( object, domElement ) {
  4155. this.object = object;
  4156. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4157. // API
  4158. this.mouseLook = true;
  4159. this.autoForward = false;
  4160. this.lookSpeed = 1;
  4161. this.movementSpeed = 1;
  4162. this.rollSpeed = 1;
  4163. this.constrainVertical = [ -0.9, 0.9 ];
  4164. // disable default target object behavior
  4165. this.object.matrixAutoUpdate = false;
  4166. // internals
  4167. this.forward = new THREE.Vector3( 0, 0, 1 );
  4168. this.roll = 0;
  4169. var xTemp = new THREE.Vector3();
  4170. var yTemp = new THREE.Vector3();
  4171. var zTemp = new THREE.Vector3();
  4172. var rollMatrix = new THREE.Matrix4();
  4173. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  4174. var mouseX = 0, mouseY = 0;
  4175. var windowHalfX = window.innerWidth / 2;
  4176. var windowHalfY = window.innerHeight / 2;
  4177. // custom update
  4178. this.update = function ( delta ) {
  4179. if ( this.mouseLook ) {
  4180. var actualLookSpeed = delta * this.lookSpeed;
  4181. this.rotateHorizontally( actualLookSpeed * mouseX );
  4182. this.rotateVertically( actualLookSpeed * mouseY );
  4183. }
  4184. var actualSpeed = delta * this.movementSpeed;
  4185. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  4186. this.object.translateZ( -actualSpeed * forwardOrAuto );
  4187. this.object.translateX( actualSpeed * sideSpeed );
  4188. this.object.translateY( actualSpeed * upSpeed );
  4189. if( doRoll ) {
  4190. this.roll += this.rollSpeed * delta * rollDirection;
  4191. }
  4192. // cap forward up / down
  4193. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  4194. this.forward.y = this.constrainVertical[ 1 ];
  4195. this.forward.normalize();
  4196. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  4197. this.forward.y = this.constrainVertical[ 0 ];
  4198. this.forward.normalize();
  4199. }
  4200. // construct unrolled camera matrix
  4201. zTemp.copy( this.forward );
  4202. yTemp.set( 0, 1, 0 );
  4203. xTemp.cross( yTemp, zTemp ).normalize();
  4204. yTemp.cross( zTemp, xTemp ).normalize();
  4205. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  4206. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  4207. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  4208. // calculate roll matrix
  4209. rollMatrix.identity();
  4210. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  4211. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  4212. // multiply camera with roll
  4213. this.object.matrix.multiplySelf( rollMatrix );
  4214. this.object.matrixWorldNeedsUpdate = true;
  4215. // set position
  4216. this.object.matrix.elements[12] = this.object.position.x;
  4217. this.object.matrix.elements[13] = this.object.position.y;
  4218. this.object.matrix.elements[14] = this.object.position.z;
  4219. };
  4220. this.translateX = function ( distance ) {
  4221. this.object.position.x += this.object.matrix.elements[0] * distance;
  4222. this.object.position.y += this.object.matrix.elements[1] * distance;
  4223. this.object.position.z += this.object.matrix.elements[2] * distance;
  4224. };
  4225. this.translateY = function ( distance ) {
  4226. this.object.position.x += this.object.matrix.elements[4] * distance;
  4227. this.object.position.y += this.object.matrix.elements[5] * distance;
  4228. this.object.position.z += this.object.matrix.elements[6] * distance;
  4229. };
  4230. this.translateZ = function ( distance ) {
  4231. this.object.position.x -= this.object.matrix.elements[8] * distance;
  4232. this.object.position.y -= this.object.matrix.elements[9] * distance;
  4233. this.object.position.z -= this.object.matrix.elements[10] * distance;
  4234. };
  4235. this.rotateHorizontally = function ( amount ) {
  4236. // please note that the amount is NOT degrees, but a scale value
  4237. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  4238. xTemp.multiplyScalar( amount );
  4239. this.forward.subSelf( xTemp );
  4240. this.forward.normalize();
  4241. };
  4242. this.rotateVertically = function ( amount ) {
  4243. // please note that the amount is NOT degrees, but a scale value
  4244. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  4245. yTemp.multiplyScalar( amount );
  4246. this.forward.addSelf( yTemp );
  4247. this.forward.normalize();
  4248. };
  4249. function onKeyDown( event ) {
  4250. switch( event.keyCode ) {
  4251. case 38: /*up*/
  4252. case 87: /*W*/ forwardSpeed = 1; break;
  4253. case 37: /*left*/
  4254. case 65: /*A*/ sideSpeed = -1; break;
  4255. case 40: /*down*/
  4256. case 83: /*S*/ forwardSpeed = -1; break;
  4257. case 39: /*right*/
  4258. case 68: /*D*/ sideSpeed = 1; break;
  4259. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  4260. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  4261. case 82: /*R*/ upSpeed = 1; break;
  4262. case 70: /*F*/ upSpeed = -1; break;
  4263. }
  4264. };
  4265. function onKeyUp( event ) {
  4266. switch( event.keyCode ) {
  4267. case 38: /*up*/
  4268. case 87: /*W*/ forwardSpeed = 0; break;
  4269. case 37: /*left*/
  4270. case 65: /*A*/ sideSpeed = 0; break;
  4271. case 40: /*down*/
  4272. case 83: /*S*/ forwardSpeed = 0; break;
  4273. case 39: /*right*/
  4274. case 68: /*D*/ sideSpeed = 0; break;
  4275. case 81: /*Q*/ doRoll = false; break;
  4276. case 69: /*E*/ doRoll = false; break;
  4277. case 82: /*R*/ upSpeed = 0; break;
  4278. case 70: /*F*/ upSpeed = 0; break;
  4279. }
  4280. };
  4281. function onMouseMove( event ) {
  4282. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  4283. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  4284. };
  4285. function onMouseDown ( event ) {
  4286. event.preventDefault();
  4287. event.stopPropagation();
  4288. switch ( event.button ) {
  4289. case 0: forwardSpeed = 1; break;
  4290. case 2: forwardSpeed = -1; break;
  4291. }
  4292. };
  4293. function onMouseUp ( event ) {
  4294. event.preventDefault();
  4295. event.stopPropagation();
  4296. switch ( event.button ) {
  4297. case 0: forwardSpeed = 0; break;
  4298. case 2: forwardSpeed = 0; break;
  4299. }
  4300. };
  4301. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  4302. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  4303. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  4304. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  4305. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  4306. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  4307. };
  4308. /**
  4309. * @author Eberhard Graether / http://egraether.com/
  4310. */
  4311. THREE.TrackballControls = function ( object, domElement ) {
  4312. THREE.EventTarget.call( this );
  4313. var _this = this,
  4314. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  4315. this.object = object;
  4316. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4317. // API
  4318. this.enabled = true;
  4319. this.screen = { width: window.innerWidth, height: window.innerHeight, offsetLeft: 0, offsetTop: 0 };
  4320. this.radius = ( this.screen.width + this.screen.height ) / 4;
  4321. this.rotateSpeed = 1.0;
  4322. this.zoomSpeed = 1.2;
  4323. this.panSpeed = 0.3;
  4324. this.noRotate = false;
  4325. this.noZoom = false;
  4326. this.noPan = false;
  4327. this.staticMoving = false;
  4328. this.dynamicDampingFactor = 0.2;
  4329. this.minDistance = 0;
  4330. this.maxDistance = Infinity;
  4331. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  4332. // internals
  4333. this.target = new THREE.Vector3();
  4334. var lastPosition = new THREE.Vector3();
  4335. var _keyPressed = false,
  4336. _state = STATE.NONE,
  4337. _eye = new THREE.Vector3(),
  4338. _rotateStart = new THREE.Vector3(),
  4339. _rotateEnd = new THREE.Vector3(),
  4340. _zoomStart = new THREE.Vector2(),
  4341. _zoomEnd = new THREE.Vector2(),
  4342. _panStart = new THREE.Vector2(),
  4343. _panEnd = new THREE.Vector2();
  4344. // events
  4345. var changeEvent = { type: 'change' };
  4346. // methods
  4347. this.handleEvent = function ( event ) {
  4348. if ( typeof this[ event.type ] == 'function' ) {
  4349. this[ event.type ]( event );
  4350. }
  4351. };
  4352. this.getMouseOnScreen = function ( clientX, clientY ) {
  4353. return new THREE.Vector2(
  4354. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  4355. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  4356. );
  4357. };
  4358. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  4359. var mouseOnBall = new THREE.Vector3(
  4360. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  4361. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  4362. 0.0
  4363. );
  4364. var length = mouseOnBall.length();
  4365. if ( length > 1.0 ) {
  4366. mouseOnBall.normalize();
  4367. } else {
  4368. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  4369. }
  4370. _eye.copy( _this.object.position ).subSelf( _this.target );
  4371. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  4372. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  4373. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  4374. return projection;
  4375. };
  4376. this.rotateCamera = function () {
  4377. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  4378. if ( angle ) {
  4379. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  4380. quaternion = new THREE.Quaternion();
  4381. angle *= _this.rotateSpeed;
  4382. quaternion.setFromAxisAngle( axis, -angle );
  4383. quaternion.multiplyVector3( _eye );
  4384. quaternion.multiplyVector3( _this.object.up );
  4385. quaternion.multiplyVector3( _rotateEnd );
  4386. if ( _this.staticMoving ) {
  4387. _rotateStart = _rotateEnd;
  4388. } else {
  4389. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  4390. quaternion.multiplyVector3( _rotateStart );
  4391. }
  4392. }
  4393. };
  4394. this.zoomCamera = function () {
  4395. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  4396. if ( factor !== 1.0 && factor > 0.0 ) {
  4397. _eye.multiplyScalar( factor );
  4398. if ( _this.staticMoving ) {
  4399. _zoomStart = _zoomEnd;
  4400. } else {
  4401. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  4402. }
  4403. }
  4404. };
  4405. this.panCamera = function () {
  4406. var mouseChange = _panEnd.clone().subSelf( _panStart );
  4407. if ( mouseChange.lengthSq() ) {
  4408. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  4409. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  4410. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  4411. _this.object.position.addSelf( pan );
  4412. _this.target.addSelf( pan );
  4413. if ( _this.staticMoving ) {
  4414. _panStart = _panEnd;
  4415. } else {
  4416. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  4417. }
  4418. }
  4419. };
  4420. this.checkDistances = function () {
  4421. if ( !_this.noZoom || !_this.noPan ) {
  4422. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  4423. _this.object.position.setLength( _this.maxDistance );
  4424. }
  4425. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  4426. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  4427. }
  4428. }
  4429. };
  4430. this.update = function () {
  4431. _eye.copy( _this.object.position ).subSelf( _this.target );
  4432. if ( !_this.noRotate ) {
  4433. _this.rotateCamera();
  4434. }
  4435. if ( !_this.noZoom ) {
  4436. _this.zoomCamera();
  4437. }
  4438. if ( !_this.noPan ) {
  4439. _this.panCamera();
  4440. }
  4441. _this.object.position.add( _this.target, _eye );
  4442. _this.checkDistances();
  4443. _this.object.lookAt( _this.target );
  4444. if ( lastPosition.distanceTo( _this.object.position ) > 0 ) {
  4445. _this.dispatchEvent( changeEvent );
  4446. lastPosition.copy( _this.object.position );
  4447. }
  4448. };
  4449. // listeners
  4450. function keydown( event ) {
  4451. if ( ! _this.enabled ) return;
  4452. if ( _state !== STATE.NONE ) {
  4453. return;
  4454. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  4455. _state = STATE.ROTATE;
  4456. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  4457. _state = STATE.ZOOM;
  4458. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  4459. _state = STATE.PAN;
  4460. }
  4461. if ( _state !== STATE.NONE ) {
  4462. _keyPressed = true;
  4463. }
  4464. };
  4465. function keyup( event ) {
  4466. if ( ! _this.enabled ) return;
  4467. if ( _state !== STATE.NONE ) {
  4468. _state = STATE.NONE;
  4469. }
  4470. };
  4471. function mousedown( event ) {
  4472. if ( ! _this.enabled ) return;
  4473. event.preventDefault();
  4474. event.stopPropagation();
  4475. if ( _state === STATE.NONE ) {
  4476. _state = event.button;
  4477. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  4478. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  4479. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  4480. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4481. } else if ( !this.noPan ) {
  4482. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4483. }
  4484. }
  4485. };
  4486. function mousemove( event ) {
  4487. if ( ! _this.enabled ) return;
  4488. if ( _keyPressed ) {
  4489. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  4490. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4491. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4492. _keyPressed = false;
  4493. }
  4494. if ( _state === STATE.NONE ) {
  4495. return;
  4496. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  4497. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  4498. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  4499. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4500. } else if ( _state === STATE.PAN && !_this.noPan ) {
  4501. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4502. }
  4503. };
  4504. function mouseup( event ) {
  4505. if ( ! _this.enabled ) return;
  4506. event.preventDefault();
  4507. event.stopPropagation();
  4508. _state = STATE.NONE;
  4509. };
  4510. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  4511. this.domElement.addEventListener( 'mousemove', mousemove, false );
  4512. this.domElement.addEventListener( 'mousedown', mousedown, false );
  4513. this.domElement.addEventListener( 'mouseup', mouseup, false );
  4514. window.addEventListener( 'keydown', keydown, false );
  4515. window.addEventListener( 'keyup', keyup, false );
  4516. };
  4517. /**
  4518. * @author mr.doob / http://mrdoob.com/
  4519. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  4520. */
  4521. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  4522. THREE.Geometry.call( this );
  4523. var scope = this,
  4524. width_half = width / 2,
  4525. height_half = height / 2,
  4526. depth_half = depth / 2;
  4527. var mpx, mpy, mpz, mnx, mny, mnz;
  4528. if ( materials !== undefined ) {
  4529. if ( materials instanceof Array ) {
  4530. this.materials = materials;
  4531. } else {
  4532. this.materials = [];
  4533. for ( var i = 0; i < 6; i ++ ) {
  4534. this.materials.push( materials );
  4535. }
  4536. }
  4537. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  4538. } else {
  4539. this.materials = [];
  4540. }
  4541. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  4542. if ( sides != undefined ) {
  4543. for ( var s in sides ) {
  4544. if ( this.sides[ s ] !== undefined ) {
  4545. this.sides[ s ] = sides[ s ];
  4546. }
  4547. }
  4548. }
  4549. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  4550. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  4551. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  4552. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  4553. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  4554. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  4555. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  4556. var w, ix, iy,
  4557. gridX = segmentsWidth || 1,
  4558. gridY = segmentsHeight || 1,
  4559. width_half = width / 2,
  4560. height_half = height / 2,
  4561. offset = scope.vertices.length;
  4562. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  4563. w = 'z';
  4564. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  4565. w = 'y';
  4566. gridY = segmentsDepth || 1;
  4567. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  4568. w = 'x';
  4569. gridX = segmentsDepth || 1;
  4570. }
  4571. var gridX1 = gridX + 1,
  4572. gridY1 = gridY + 1,
  4573. segment_width = width / gridX,
  4574. segment_height = height / gridY,
  4575. normal = new THREE.Vector3();
  4576. normal[ w ] = depth > 0 ? 1 : - 1;
  4577. for ( iy = 0; iy < gridY1; iy ++ ) {
  4578. for ( ix = 0; ix < gridX1; ix ++ ) {
  4579. var vector = new THREE.Vector3();
  4580. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  4581. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  4582. vector[ w ] = depth;
  4583. scope.vertices.push( vector );
  4584. }
  4585. }
  4586. for ( iy = 0; iy < gridY; iy++ ) {
  4587. for ( ix = 0; ix < gridX; ix++ ) {
  4588. var a = ix + gridX1 * iy;
  4589. var b = ix + gridX1 * ( iy + 1 );
  4590. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  4591. var d = ( ix + 1 ) + gridX1 * iy;
  4592. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  4593. face.normal.copy( normal );
  4594. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  4595. face.materialIndex = material;
  4596. scope.faces.push( face );
  4597. scope.faceVertexUvs[ 0 ].push( [
  4598. new THREE.UV( ix / gridX, iy / gridY ),
  4599. new THREE.UV( ix / gridX, ( iy + 1 ) / gridY ),
  4600. new THREE.UV( ( ix + 1 ) / gridX, ( iy + 1 ) / gridY ),
  4601. new THREE.UV( ( ix + 1 ) / gridX, iy / gridY )
  4602. ] );
  4603. }
  4604. }
  4605. }
  4606. this.computeCentroids();
  4607. this.mergeVertices();
  4608. };
  4609. THREE.CubeGeometry.prototype = new THREE.Geometry();
  4610. THREE.CubeGeometry.prototype.constructor = THREE.CubeGeometry;
  4611. /**
  4612. * @author mr.doob / http://mrdoob.com/
  4613. */
  4614. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  4615. THREE.Geometry.call( this );
  4616. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  4617. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  4618. height = height !== undefined ? height : 100;
  4619. var heightHalf = height / 2;
  4620. var segmentsX = segmentsRadius || 8;
  4621. var segmentsY = segmentsHeight || 1;
  4622. var x, y, vertices = [], uvs = [];
  4623. for ( y = 0; y <= segmentsY; y ++ ) {
  4624. var verticesRow = [];
  4625. var uvsRow = [];
  4626. var v = y / segmentsY;
  4627. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  4628. for ( x = 0; x <= segmentsX; x ++ ) {
  4629. var u = x / segmentsX;
  4630. var vertex = new THREE.Vector3();
  4631. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  4632. vertex.y = - v * height + heightHalf;
  4633. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  4634. this.vertices.push( vertex );
  4635. verticesRow.push( this.vertices.length - 1 );
  4636. uvsRow.push( new THREE.UV( u, v ) );
  4637. }
  4638. vertices.push( verticesRow );
  4639. uvs.push( uvsRow );
  4640. }
  4641. for ( y = 0; y < segmentsY; y ++ ) {
  4642. for ( x = 0; x < segmentsX; x ++ ) {
  4643. var v1 = vertices[ y ][ x ];
  4644. var v2 = vertices[ y + 1 ][ x ];
  4645. var v3 = vertices[ y + 1 ][ x + 1 ];
  4646. var v4 = vertices[ y ][ x + 1 ];
  4647. // FIXME: These normals aren't right for cones.
  4648. var n1 = this.vertices[ v1 ].clone().setY( 0 ).normalize();
  4649. var n2 = this.vertices[ v2 ].clone().setY( 0 ).normalize();
  4650. var n3 = this.vertices[ v3 ].clone().setY( 0 ).normalize();
  4651. var n4 = this.vertices[ v4 ].clone().setY( 0 ).normalize();
  4652. var uv1 = uvs[ y ][ x ].clone();
  4653. var uv2 = uvs[ y + 1 ][ x ].clone();
  4654. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  4655. var uv4 = uvs[ y ][ x + 1 ].clone();
  4656. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  4657. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  4658. }
  4659. }
  4660. // top cap
  4661. if ( !openEnded && radiusTop > 0 ) {
  4662. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  4663. for ( x = 0; x < segmentsX; x ++ ) {
  4664. var v1 = vertices[ 0 ][ x ];
  4665. var v2 = vertices[ 0 ][ x + 1 ];
  4666. var v3 = this.vertices.length - 1;
  4667. var n1 = new THREE.Vector3( 0, 1, 0 );
  4668. var n2 = new THREE.Vector3( 0, 1, 0 );
  4669. var n3 = new THREE.Vector3( 0, 1, 0 );
  4670. var uv1 = uvs[ 0 ][ x ].clone();
  4671. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  4672. var uv3 = new THREE.UV( uv2.u, 0 );
  4673. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  4674. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  4675. }
  4676. }
  4677. // bottom cap
  4678. if ( !openEnded && radiusBottom > 0 ) {
  4679. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  4680. for ( x = 0; x < segmentsX; x ++ ) {
  4681. var v1 = vertices[ y ][ x + 1 ];
  4682. var v2 = vertices[ y ][ x ];
  4683. var v3 = this.vertices.length - 1;
  4684. var n1 = new THREE.Vector3( 0, - 1, 0 );
  4685. var n2 = new THREE.Vector3( 0, - 1, 0 );
  4686. var n3 = new THREE.Vector3( 0, - 1, 0 );
  4687. var uv1 = uvs[ y ][ x + 1 ].clone();
  4688. var uv2 = uvs[ y ][ x ].clone();
  4689. var uv3 = new THREE.UV( uv2.u, 1 );
  4690. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  4691. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  4692. }
  4693. }
  4694. this.computeCentroids();
  4695. this.computeFaceNormals();
  4696. }
  4697. THREE.CylinderGeometry.prototype = new THREE.Geometry();
  4698. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  4699. /**
  4700. * @author zz85 / http://www.lab4games.net/zz85/blog
  4701. *
  4702. * Creates extruded geometry from a path shape.
  4703. *
  4704. * parameters = {
  4705. *
  4706. * size: <float>, // size of the text
  4707. * height: <float>, // thickness to extrude text
  4708. * curveSegments: <int>, // number of points on the curves
  4709. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  4710. amount: <int>, // Amount
  4711. *
  4712. * bevelEnabled: <bool>, // turn on bevel
  4713. * bevelThickness: <float>, // how deep into text bevel goes
  4714. * bevelSize: <float>, // how far from text outline is bevel
  4715. * bevelSegments: <int>, // number of bevel layers
  4716. *
  4717. * extrudePath: <THREE.CurvePath> // 2d/3d spline path to extrude shape orthogonality to
  4718. * bendPath: <THREE.CurvePath> // 2d path for bend the shape around x/y plane
  4719. *
  4720. * material: <int> // material index for front and back faces
  4721. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  4722. *
  4723. * }
  4724. **/
  4725. THREE.ExtrudeGeometry = function( shapes, options ) {
  4726. if ( typeof( shapes ) === "undefined" ) {
  4727. shapes = [];
  4728. return;
  4729. }
  4730. THREE.Geometry.call( this );
  4731. shapes = shapes instanceof Array ? shapes : [ shapes ];
  4732. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  4733. this.addShapeList( shapes, options );
  4734. this.computeCentroids();
  4735. this.computeFaceNormals();
  4736. // can't really use automatic vertex normals
  4737. // as then front and back sides get smoothed too
  4738. // should do separate smoothing just for sides
  4739. //this.computeVertexNormals();
  4740. //console.log( "took", ( Date.now() - startTime ) );
  4741. };
  4742. THREE.ExtrudeGeometry.prototype = new THREE.Geometry();
  4743. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  4744. THREE.ExtrudeGeometry.prototype.addShapeList = function(shapes, options) {
  4745. var sl = shapes.length;
  4746. for ( var s = 0; s < sl; s ++ ) {
  4747. var shape = shapes[ s ];
  4748. this.addShape( shape, options );
  4749. }
  4750. };
  4751. THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
  4752. var amount = options.amount !== undefined ? options.amount : 100;
  4753. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  4754. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  4755. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  4756. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  4757. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  4758. var steps = options.steps !== undefined ? options.steps : 1;
  4759. var bendPath = options.bendPath;
  4760. var extrudePath = options.extrudePath;
  4761. var extrudePts, extrudeByPath = false;
  4762. var material = options.material;
  4763. var extrudeMaterial = options.extrudeMaterial;
  4764. var shapebb = this.shapebb;
  4765. //shapebb = shape.getBoundingBox();
  4766. var splineTube, binormal, normal, position2;
  4767. if ( extrudePath ) {
  4768. extrudePts = extrudePath.getSpacedPoints( steps );
  4769. extrudeByPath = true;
  4770. bevelEnabled = false; // bevels not supported for path extrusion
  4771. // SETUP TNB variables
  4772. // Reuse TNB from TubeGeomtry for now.
  4773. // TODO1 - have a .isClosed in spline?
  4774. splineTube = new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  4775. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  4776. binormal = new THREE.Vector3();
  4777. normal = new THREE.Vector3();
  4778. position2 = new THREE.Vector3();
  4779. }
  4780. // Safeguards if bevels are not enabled
  4781. if ( ! bevelEnabled ) {
  4782. bevelSegments = 0;
  4783. bevelThickness = 0;
  4784. bevelSize = 0;
  4785. }
  4786. // Variables initalization
  4787. var ahole, h, hl; // looping of holes
  4788. var scope = this;
  4789. var bevelPoints = [];
  4790. var shapesOffset = this.vertices.length;
  4791. if ( bendPath ) {
  4792. shape.addWrapPath( bendPath );
  4793. }
  4794. var shapePoints = shape.extractPoints();
  4795. var vertices = shapePoints.shape;
  4796. var holes = shapePoints.holes;
  4797. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  4798. if ( reverse ) {
  4799. vertices = vertices.reverse();
  4800. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  4801. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  4802. ahole = holes[ h ];
  4803. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  4804. holes[ h ] = ahole.reverse();
  4805. }
  4806. }
  4807. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  4808. }
  4809. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  4810. //var faces = THREE.Shape.Utils.triangulate2( vertices, holes );
  4811. // Would it be better to move points after triangulation?
  4812. // shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
  4813. // vertices = shapePoints.shape;
  4814. // holes = shapePoints.holes;
  4815. //console.log(faces);
  4816. ////
  4817. /// Handle Vertices
  4818. ////
  4819. var contour = vertices; // vertices has all points but contour has only points of circumference
  4820. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  4821. ahole = holes[ h ];
  4822. vertices = vertices.concat( ahole );
  4823. }
  4824. function scalePt2 ( pt, vec, size ) {
  4825. if ( !vec ) console.log( "die" );
  4826. return vec.clone().multiplyScalar( size ).addSelf( pt );
  4827. }
  4828. var b, bs, t, z,
  4829. vert, vlen = vertices.length,
  4830. face, flen = faces.length,
  4831. cont, clen = contour.length;
  4832. //------
  4833. // Find directions for point movement
  4834. //
  4835. var RAD_TO_DEGREES = 180 / Math.PI;
  4836. function getBevelVec( pt_i, pt_j, pt_k ) {
  4837. // Algorithm 2
  4838. return getBevelVec2( pt_i, pt_j, pt_k );
  4839. }
  4840. function getBevelVec1( pt_i, pt_j, pt_k ) {
  4841. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  4842. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  4843. if ( anglea > angleb ) {
  4844. angleb += Math.PI * 2;
  4845. }
  4846. var anglec = ( anglea + angleb ) / 2;
  4847. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  4848. var x = - Math.cos( anglec );
  4849. var y = - Math.sin( anglec );
  4850. var vec = new THREE.Vector2( x, y ); //.normalize();
  4851. return vec;
  4852. }
  4853. function getBevelVec2( pt_i, pt_j, pt_k ) {
  4854. var a = THREE.ExtrudeGeometry.__v1,
  4855. b = THREE.ExtrudeGeometry.__v2,
  4856. v_hat = THREE.ExtrudeGeometry.__v3,
  4857. w_hat = THREE.ExtrudeGeometry.__v4,
  4858. p = THREE.ExtrudeGeometry.__v5,
  4859. q = THREE.ExtrudeGeometry.__v6,
  4860. v, w,
  4861. v_dot_w_hat, q_sub_p_dot_w_hat,
  4862. s, intersection;
  4863. // good reading for line-line intersection
  4864. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  4865. // define a as vector j->i
  4866. // define b as vectot k->i
  4867. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  4868. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  4869. // get unit vectors
  4870. v = a.normalize();
  4871. w = b.normalize();
  4872. // normals from pt i
  4873. v_hat.set( -v.y, v.x );
  4874. w_hat.set( w.y, -w.x );
  4875. // pts from i
  4876. p.copy( pt_i ).addSelf( v_hat );
  4877. q.copy( pt_i ).addSelf( w_hat );
  4878. if ( p.equals( q ) ) {
  4879. //console.log("Warning: lines are straight");
  4880. return w_hat.clone();
  4881. }
  4882. // Points from j, k. helps prevents points cross overover most of the time
  4883. p.copy( pt_j ).addSelf( v_hat );
  4884. q.copy( pt_k ).addSelf( w_hat );
  4885. v_dot_w_hat = v.dot( w_hat );
  4886. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  4887. // We should not reach these conditions
  4888. if ( v_dot_w_hat === 0 ) {
  4889. console.log( "Either infinite or no solutions!" );
  4890. if ( q_sub_p_dot_w_hat === 0 ) {
  4891. console.log( "Its finite solutions." );
  4892. } else {
  4893. console.log( "Too bad, no solutions." );
  4894. }
  4895. }
  4896. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  4897. if ( s < 0 ) {
  4898. // in case of emergecy, revert to algorithm 1.
  4899. return getBevelVec1( pt_i, pt_j, pt_k );
  4900. }
  4901. intersection = v.multiplyScalar( s ).addSelf( p );
  4902. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  4903. }
  4904. var contourMovements = [];
  4905. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  4906. if ( j === il ) j = 0;
  4907. if ( k === il ) k = 0;
  4908. // (j)---(i)---(k)
  4909. // console.log('i,j,k', i, j , k)
  4910. var pt_i = contour[ i ];
  4911. var pt_j = contour[ j ];
  4912. var pt_k = contour[ k ];
  4913. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  4914. }
  4915. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  4916. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  4917. ahole = holes[ h ];
  4918. oneHoleMovements = [];
  4919. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  4920. if ( j === il ) j = 0;
  4921. if ( k === il ) k = 0;
  4922. // (j)---(i)---(k)
  4923. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  4924. }
  4925. holesMovements.push( oneHoleMovements );
  4926. verticesMovements = verticesMovements.concat( oneHoleMovements );
  4927. }
  4928. // Loop bevelSegments, 1 for the front, 1 for the back
  4929. for ( b = 0; b < bevelSegments; b ++ ) {
  4930. //for ( b = bevelSegments; b > 0; b -- ) {
  4931. t = b / bevelSegments;
  4932. z = bevelThickness * ( 1 - t );
  4933. //z = bevelThickness * t;
  4934. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  4935. //bs = bevelSize * t ; // linear
  4936. // contract shape
  4937. for ( i = 0, il = contour.length; i < il; i ++ ) {
  4938. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  4939. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  4940. v( vert.x, vert.y, - z );
  4941. }
  4942. // expand holes
  4943. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  4944. ahole = holes[ h ];
  4945. oneHoleMovements = holesMovements[ h ];
  4946. for ( i = 0, il = ahole.length; i < il; i++ ) {
  4947. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  4948. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  4949. v( vert.x, vert.y, -z );
  4950. }
  4951. }
  4952. }
  4953. bs = bevelSize;
  4954. // Back facing vertices
  4955. for ( i = 0; i < vlen; i ++ ) {
  4956. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  4957. if ( !extrudeByPath ) {
  4958. v( vert.x, vert.y, 0 );
  4959. } else {
  4960. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  4961. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  4962. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  4963. position2.copy(extrudePts[0]).addSelf(normal).addSelf(binormal);
  4964. v(position2.x, position2.y, position2.z);
  4965. }
  4966. }
  4967. // Add stepped vertices...
  4968. // Including front facing vertices
  4969. var s;
  4970. for ( s = 1; s <= steps; s ++ ) {
  4971. for ( i = 0; i < vlen; i ++ ) {
  4972. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  4973. if ( !extrudeByPath ) {
  4974. v( vert.x, vert.y, amount / steps * s );
  4975. } else {
  4976. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  4977. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  4978. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  4979. position2.copy(extrudePts[s]).addSelf(normal).addSelf(binormal);
  4980. v(position2.x, position2.y, position2.z );
  4981. }
  4982. }
  4983. }
  4984. // Add bevel segments planes
  4985. //for ( b = 1; b <= bevelSegments; b ++ ) {
  4986. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  4987. t = b / bevelSegments;
  4988. z = bevelThickness * ( 1 - t );
  4989. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  4990. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  4991. // contract shape
  4992. for ( i = 0, il = contour.length; i < il; i ++ ) {
  4993. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  4994. v( vert.x, vert.y, amount + z );
  4995. }
  4996. // expand holes
  4997. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  4998. ahole = holes[ h ];
  4999. oneHoleMovements = holesMovements[ h ];
  5000. for ( i = 0, il = ahole.length; i < il; i++ ) {
  5001. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  5002. if ( !extrudeByPath ) {
  5003. v( vert.x, vert.y, amount + z );
  5004. } else {
  5005. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  5006. }
  5007. }
  5008. }
  5009. }
  5010. // set UV generator
  5011. var uvgen = THREE.ExtrudeGeometry.WorldUVGenerator;
  5012. ////
  5013. /// Handle Faces
  5014. ////
  5015. // Top and bottom faces
  5016. buildLidFaces();
  5017. // Sides faces
  5018. buildSideFaces();
  5019. ///// Internal functions
  5020. function buildLidFaces() {
  5021. if ( bevelEnabled ) {
  5022. var layer = 0 ; // steps + 1
  5023. var offset = vlen * layer;
  5024. // Bottom faces
  5025. for ( i = 0; i < flen; i ++ ) {
  5026. face = faces[ i ];
  5027. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  5028. }
  5029. layer = steps + bevelSegments * 2;
  5030. offset = vlen * layer;
  5031. // Top faces
  5032. for ( i = 0; i < flen; i ++ ) {
  5033. face = faces[ i ];
  5034. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  5035. }
  5036. } else {
  5037. // Bottom faces
  5038. for ( i = 0; i < flen; i++ ) {
  5039. face = faces[ i ];
  5040. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  5041. }
  5042. // Top faces
  5043. for ( i = 0; i < flen; i ++ ) {
  5044. face = faces[ i ];
  5045. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  5046. }
  5047. }
  5048. }
  5049. // Create faces for the z-sides of the shape
  5050. function buildSideFaces() {
  5051. var layeroffset = 0;
  5052. sidewalls( contour, layeroffset );
  5053. layeroffset += contour.length;
  5054. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  5055. ahole = holes[ h ];
  5056. sidewalls( ahole, layeroffset );
  5057. //, true
  5058. layeroffset += ahole.length;
  5059. }
  5060. }
  5061. function sidewalls( contour, layeroffset ) {
  5062. var j, k;
  5063. i = contour.length;
  5064. while ( --i >= 0 ) {
  5065. j = i;
  5066. k = i - 1;
  5067. if ( k < 0 ) k = contour.length - 1;
  5068. //console.log('b', i,j, i-1, k,vertices.length);
  5069. var s = 0, sl = steps + bevelSegments * 2;
  5070. for ( s = 0; s < sl; s ++ ) {
  5071. var slen1 = vlen * s;
  5072. var slen2 = vlen * ( s + 1 );
  5073. var a = layeroffset + j + slen1,
  5074. b = layeroffset + k + slen1,
  5075. c = layeroffset + k + slen2,
  5076. d = layeroffset + j + slen2;
  5077. f4( a, b, c, d, contour, s, sl );
  5078. }
  5079. }
  5080. }
  5081. function v( x, y, z ) {
  5082. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  5083. }
  5084. function f3( a, b, c, isBottom ) {
  5085. a += shapesOffset;
  5086. b += shapesOffset;
  5087. c += shapesOffset;
  5088. // normal, color, material
  5089. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  5090. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c)
  5091. : uvgen.generateTopUV( scope, shape, options, a, b, c);
  5092. scope.faceVertexUvs[ 0 ].push(uvs);
  5093. }
  5094. function f4( a, b, c, d, wallContour, stepIndex, stepsLength ) {
  5095. a += shapesOffset;
  5096. b += shapesOffset;
  5097. c += shapesOffset;
  5098. d += shapesOffset;
  5099. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  5100. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d, stepIndex, stepsLength);
  5101. scope.faceVertexUvs[ 0 ].push(uvs);
  5102. }
  5103. };
  5104. THREE.ExtrudeGeometry.WorldUVGenerator = {
  5105. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  5106. var ax = geometry.vertices[ indexA ].x,
  5107. ay = geometry.vertices[ indexA ].y,
  5108. bx = geometry.vertices[ indexB ].x,
  5109. by = geometry.vertices[ indexB ].y,
  5110. cx = geometry.vertices[ indexC ].x,
  5111. cy = geometry.vertices[ indexC ].y;
  5112. return [
  5113. new THREE.UV( ax, 1 - ay ),
  5114. new THREE.UV( bx, 1 - by ),
  5115. new THREE.UV( cx, 1 - cy )
  5116. ];
  5117. },
  5118. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  5119. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  5120. },
  5121. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  5122. indexA, indexB, indexC, indexD, stepIndex, stepsLength) {
  5123. var ax = geometry.vertices[ indexA ].x,
  5124. ay = geometry.vertices[ indexA ].y,
  5125. az = geometry.vertices[ indexA ].z,
  5126. bx = geometry.vertices[ indexB ].x,
  5127. by = geometry.vertices[ indexB ].y,
  5128. bz = geometry.vertices[ indexB ].z,
  5129. cx = geometry.vertices[ indexC ].x,
  5130. cy = geometry.vertices[ indexC ].y,
  5131. cz = geometry.vertices[ indexC ].z,
  5132. dx = geometry.vertices[ indexD ].x,
  5133. dy = geometry.vertices[ indexD ].y,
  5134. dz = geometry.vertices[ indexD ].z;
  5135. if ( Math.abs( ay - by ) < 0.01 ) {
  5136. return [
  5137. new THREE.UV( ax, az ),
  5138. new THREE.UV( bx, bz ),
  5139. new THREE.UV( cx, cz ),
  5140. new THREE.UV( dx, dz )
  5141. ];
  5142. } else {
  5143. return [
  5144. new THREE.UV( ay, az ),
  5145. new THREE.UV( by, bz ),
  5146. new THREE.UV( cy, cz ),
  5147. new THREE.UV( dy, dz )
  5148. ];
  5149. }
  5150. }
  5151. };
  5152. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  5153. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  5154. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  5155. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  5156. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  5157. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  5158. /**
  5159. * @author astrodud / http://astrodud.isgreat.org/
  5160. * @author zz85 / https://github.com/zz85
  5161. */
  5162. THREE.LatheGeometry = function ( points, steps, angle ) {
  5163. THREE.Geometry.call( this );
  5164. var _steps = steps || 12;
  5165. var _angle = angle || 2 * Math.PI;
  5166. var _newV = [];
  5167. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  5168. for ( var j = 0; j < points.length; j ++ ) {
  5169. _newV[ j ] = points[ j ].clone();
  5170. this.vertices.push( _newV[ j ] );
  5171. }
  5172. var i, il = _steps + 1;
  5173. for ( i = 0; i < il; i ++ ) {
  5174. for ( var j = 0; j < _newV.length; j ++ ) {
  5175. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  5176. this.vertices.push( _newV[ j ] );
  5177. }
  5178. }
  5179. for ( i = 0; i < _steps; i ++ ) {
  5180. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  5181. var a = i * kl + k;
  5182. var b = ( ( i + 1 ) % il ) * kl + k;
  5183. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  5184. var d = i * kl + ( k + 1 ) % kl;
  5185. this.faces.push( new THREE.Face4( a, b, c, d ) );
  5186. this.faceVertexUvs[ 0 ].push( [
  5187. new THREE.UV( 1 - i / _steps, k / kl ),
  5188. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  5189. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  5190. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  5191. ] );
  5192. }
  5193. }
  5194. this.computeCentroids();
  5195. this.computeFaceNormals();
  5196. this.computeVertexNormals();
  5197. };
  5198. THREE.LatheGeometry.prototype = new THREE.Geometry();
  5199. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  5200. /**
  5201. * @author mr.doob / http://mrdoob.com/
  5202. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  5203. */
  5204. THREE.PlaneGeometry = function ( width, depth, segmentsWidth, segmentsDepth ) {
  5205. THREE.Geometry.call( this );
  5206. var ix, iz,
  5207. width_half = width / 2,
  5208. depth_half = depth / 2,
  5209. gridX = segmentsWidth || 1,
  5210. gridZ = segmentsDepth || 1,
  5211. gridX1 = gridX + 1,
  5212. gridZ1 = gridZ + 1,
  5213. segment_width = width / gridX,
  5214. segment_depth = depth / gridZ,
  5215. normal = new THREE.Vector3( 0, 1, 0 );
  5216. for ( iz = 0; iz < gridZ1; iz ++ ) {
  5217. for ( ix = 0; ix < gridX1; ix ++ ) {
  5218. var x = ix * segment_width - width_half;
  5219. var z = iz * segment_depth - depth_half;
  5220. this.vertices.push( new THREE.Vector3( x, 0, z ) );
  5221. }
  5222. }
  5223. for ( iz = 0; iz < gridZ; iz ++ ) {
  5224. for ( ix = 0; ix < gridX; ix ++ ) {
  5225. var a = ix + gridX1 * iz;
  5226. var b = ix + gridX1 * ( iz + 1 );
  5227. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  5228. var d = ( ix + 1 ) + gridX1 * iz;
  5229. var face = new THREE.Face4( a, b, c, d );
  5230. face.normal.copy( normal );
  5231. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  5232. this.faces.push( face );
  5233. this.faceVertexUvs[ 0 ].push( [
  5234. new THREE.UV( ix / gridX, iz / gridZ ),
  5235. new THREE.UV( ix / gridX, ( iz + 1 ) / gridZ ),
  5236. new THREE.UV( ( ix + 1 ) / gridX, ( iz + 1 ) / gridZ ),
  5237. new THREE.UV( ( ix + 1 ) / gridX, iz / gridZ )
  5238. ] );
  5239. }
  5240. }
  5241. this.computeCentroids();
  5242. };
  5243. THREE.PlaneGeometry.prototype = new THREE.Geometry();
  5244. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  5245. /**
  5246. * @author mr.doob / http://mrdoob.com/
  5247. */
  5248. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  5249. THREE.Geometry.call( this );
  5250. radius = radius || 50;
  5251. phiStart = phiStart !== undefined ? phiStart : 0;
  5252. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  5253. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  5254. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  5255. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  5256. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  5257. var x, y, vertices = [], uvs = [];
  5258. for ( y = 0; y <= segmentsY; y ++ ) {
  5259. var verticesRow = [];
  5260. var uvsRow = [];
  5261. for ( x = 0; x <= segmentsX; x ++ ) {
  5262. var u = x / segmentsX;
  5263. var v = y / segmentsY;
  5264. var vertex = new THREE.Vector3();
  5265. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  5266. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  5267. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  5268. this.vertices.push( vertex );
  5269. verticesRow.push( this.vertices.length - 1 );
  5270. uvsRow.push( new THREE.UV( u, v ) );
  5271. }
  5272. vertices.push( verticesRow );
  5273. uvs.push( uvsRow );
  5274. }
  5275. for ( y = 0; y < segmentsY; y ++ ) {
  5276. for ( x = 0; x < segmentsX; x ++ ) {
  5277. var v1 = vertices[ y ][ x + 1 ];
  5278. var v2 = vertices[ y ][ x ];
  5279. var v3 = vertices[ y + 1 ][ x ];
  5280. var v4 = vertices[ y + 1 ][ x + 1 ];
  5281. var n1 = this.vertices[ v1 ].clone().normalize();
  5282. var n2 = this.vertices[ v2 ].clone().normalize();
  5283. var n3 = this.vertices[ v3 ].clone().normalize();
  5284. var n4 = this.vertices[ v4 ].clone().normalize();
  5285. var uv1 = uvs[ y ][ x + 1 ].clone();
  5286. var uv2 = uvs[ y ][ x ].clone();
  5287. var uv3 = uvs[ y + 1 ][ x ].clone();
  5288. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  5289. if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
  5290. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  5291. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  5292. } else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
  5293. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  5294. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  5295. } else {
  5296. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  5297. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  5298. }
  5299. }
  5300. }
  5301. this.computeCentroids();
  5302. this.computeFaceNormals();
  5303. this.boundingSphere = { radius: radius };
  5304. };
  5305. THREE.SphereGeometry.prototype = new THREE.Geometry();
  5306. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  5307. /**
  5308. * @author zz85 / http://www.lab4games.net/zz85/blog
  5309. * @author alteredq / http://alteredqualia.com/
  5310. *
  5311. * For creating 3D text geometry in three.js
  5312. *
  5313. * Text = 3D Text
  5314. *
  5315. * parameters = {
  5316. * size: <float>, // size of the text
  5317. * height: <float>, // thickness to extrude text
  5318. * curveSegments: <int>, // number of points on the curves
  5319. *
  5320. * font: <string>, // font name
  5321. * weight: <string>, // font weight (normal, bold)
  5322. * style: <string>, // font style (normal, italics)
  5323. *
  5324. * bevelEnabled: <bool>, // turn on bevel
  5325. * bevelThickness: <float>, // how deep into text bevel goes
  5326. * bevelSize: <float>, // how far from text outline is bevel
  5327. *
  5328. * bend: <bool> // bend according to hardcoded curve (generates bendPath)
  5329. * bendPath: <curve> // wraps text according to bend Path
  5330. * }
  5331. *
  5332. * It uses techniques used in:
  5333. *
  5334. * typeface.js and canvastext
  5335. * For converting fonts and rendering with javascript
  5336. * http://typeface.neocracy.org
  5337. *
  5338. * Triangulation ported from AS3
  5339. * Simple Polygon Triangulation
  5340. * http://actionsnippet.com/?p=1462
  5341. *
  5342. * A Method to triangulate shapes with holes
  5343. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  5344. *
  5345. */
  5346. /* Usage Examples
  5347. // TextGeometry wrapper
  5348. var text3d = new TextGeometry( text, options );
  5349. // Complete manner
  5350. var textPath = new THREE.TextPath( text, options );
  5351. var textShapes = textPath.toShapes();
  5352. var text3d = new ExtrudeGeometry( textShapes, options );
  5353. */
  5354. THREE.TextGeometry = function ( text, parameters ) {
  5355. var textPath = new THREE.TextPath( text, parameters );
  5356. var textShapes = textPath.toShapes();
  5357. // translate parameters to ExtrudeGeometry API
  5358. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  5359. // defaults
  5360. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  5361. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  5362. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  5363. if ( parameters.bend ) {
  5364. var b = textShapes[ textShapes.length - 1 ].getBoundingBox();
  5365. var max = b.maxX;
  5366. parameters.bendPath = new THREE.QuadraticBezierCurve( new THREE.Vector2( 0, 0 ),
  5367. new THREE.Vector2( max / 2, 120 ),
  5368. new THREE.Vector2( max, 0 ) );
  5369. }
  5370. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  5371. };
  5372. THREE.TextGeometry.prototype = new THREE.ExtrudeGeometry();
  5373. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  5374. THREE.FontUtils = {
  5375. faces : {},
  5376. // Just for now. face[weight][style]
  5377. face : "helvetiker",
  5378. weight: "normal",
  5379. style : "normal",
  5380. size : 150,
  5381. divisions : 10,
  5382. getFace : function() {
  5383. return this.faces[ this.face ][ this.weight ][ this.style ];
  5384. },
  5385. loadFace : function( data ) {
  5386. var family = data.familyName.toLowerCase();
  5387. var ThreeFont = this;
  5388. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  5389. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  5390. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  5391. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  5392. return data;
  5393. },
  5394. drawText : function( text ) {
  5395. var characterPts = [], allPts = [];
  5396. // RenderText
  5397. var i, p,
  5398. face = this.getFace(),
  5399. scale = this.size / face.resolution,
  5400. offset = 0,
  5401. chars = String( text ).split( '' ),
  5402. length = chars.length;
  5403. var fontPaths = [];
  5404. for ( i = 0; i < length; i ++ ) {
  5405. var path = new THREE.Path();
  5406. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  5407. offset += ret.offset;
  5408. //characterPts.push( ret.points );
  5409. //allPts = allPts.concat( ret.points );
  5410. fontPaths.push( ret.path );
  5411. }
  5412. // get the width
  5413. var width = offset / 2;
  5414. //
  5415. // for ( p = 0; p < allPts.length; p++ ) {
  5416. //
  5417. // allPts[ p ].x -= width;
  5418. //
  5419. // }
  5420. //var extract = this.extractPoints( allPts, characterPts );
  5421. //extract.contour = allPts;
  5422. //extract.paths = fontPaths;
  5423. //extract.offset = width;
  5424. return { paths : fontPaths, offset : width };
  5425. },
  5426. extractGlyphPoints : function( c, face, scale, offset, path ) {
  5427. var pts = [];
  5428. var i, i2, divisions,
  5429. outline, action, length,
  5430. scaleX, scaleY,
  5431. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  5432. laste,
  5433. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  5434. if ( !glyph ) return;
  5435. if ( glyph.o ) {
  5436. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  5437. length = outline.length;
  5438. scaleX = scale;
  5439. scaleY = scale;
  5440. for ( i = 0; i < length; ) {
  5441. action = outline[ i ++ ];
  5442. //console.log( action );
  5443. switch( action ) {
  5444. case 'm':
  5445. // Move To
  5446. x = outline[ i++ ] * scaleX + offset;
  5447. y = outline[ i++ ] * scaleY;
  5448. pts.push( new THREE.Vector2( x, y ) );
  5449. path.moveTo( x, y );
  5450. break;
  5451. case 'l':
  5452. // Line To
  5453. x = outline[ i++ ] * scaleX + offset;
  5454. y = outline[ i++ ] * scaleY;
  5455. pts.push( new THREE.Vector2( x, y ) );
  5456. path.lineTo(x,y);
  5457. break;
  5458. case 'q':
  5459. // QuadraticCurveTo
  5460. cpx = outline[ i++ ] * scaleX + offset;
  5461. cpy = outline[ i++ ] * scaleY;
  5462. cpx1 = outline[ i++ ] * scaleX + offset;
  5463. cpy1 = outline[ i++ ] * scaleY;
  5464. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  5465. laste = pts[ pts.length - 1 ];
  5466. if ( laste ) {
  5467. cpx0 = laste.x;
  5468. cpy0 = laste.y;
  5469. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  5470. var t = i2 / divisions;
  5471. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  5472. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  5473. pts.push( new THREE.Vector2( tx, ty ) );
  5474. }
  5475. }
  5476. break;
  5477. case 'b':
  5478. // Cubic Bezier Curve
  5479. cpx = outline[ i++ ] * scaleX + offset;
  5480. cpy = outline[ i++ ] * scaleY;
  5481. cpx1 = outline[ i++ ] * scaleX + offset;
  5482. cpy1 = outline[ i++ ] * -scaleY;
  5483. cpx2 = outline[ i++ ] * scaleX + offset;
  5484. cpy2 = outline[ i++ ] * -scaleY;
  5485. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  5486. laste = pts[ pts.length - 1 ];
  5487. if ( laste ) {
  5488. cpx0 = laste.x;
  5489. cpy0 = laste.y;
  5490. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  5491. var t = i2 / divisions;
  5492. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  5493. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  5494. pts.push( new THREE.Vector2( tx, ty ) );
  5495. }
  5496. }
  5497. break;
  5498. }
  5499. }
  5500. }
  5501. return { offset: glyph.ha*scale, points:pts, path:path};
  5502. }
  5503. };
  5504. /**
  5505. * This code is a quick port of code written in C++ which was submitted to
  5506. * flipcode.com by John W. Ratcliff // July 22, 2000
  5507. * See original code and more information here:
  5508. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  5509. *
  5510. * ported to actionscript by Zevan Rosser
  5511. * www.actionsnippet.com
  5512. *
  5513. * ported to javascript by Joshua Koo
  5514. * http://www.lab4games.net/zz85/blog
  5515. *
  5516. */
  5517. ( function( namespace ) {
  5518. var EPSILON = 0.0000000001;
  5519. // takes in an contour array and returns
  5520. var process = function( contour, indices ) {
  5521. var n = contour.length;
  5522. if ( n < 3 ) return null;
  5523. var result = [],
  5524. verts = [],
  5525. vertIndices = [];
  5526. /* we want a counter-clockwise polygon in verts */
  5527. var u, v, w;
  5528. if ( area( contour ) > 0.0 ) {
  5529. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  5530. } else {
  5531. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  5532. }
  5533. var nv = n;
  5534. /* remove nv - 2 vertices, creating 1 triangle every time */
  5535. var count = 2 * nv; /* error detection */
  5536. for( v = nv - 1; nv > 2; ) {
  5537. /* if we loop, it is probably a non-simple polygon */
  5538. if ( ( count-- ) <= 0 ) {
  5539. //** Triangulate: ERROR - probable bad polygon!
  5540. //throw ( "Warning, unable to triangulate polygon!" );
  5541. //return null;
  5542. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  5543. console.log( "Warning, unable to triangulate polygon!" );
  5544. if ( indices ) return vertIndices;
  5545. return result;
  5546. }
  5547. /* three consecutive vertices in current polygon, <u,v,w> */
  5548. u = v; if ( nv <= u ) u = 0; /* previous */
  5549. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  5550. w = v + 1; if ( nv <= w ) w = 0; /* next */
  5551. if ( snip( contour, u, v, w, nv, verts ) ) {
  5552. var a, b, c, s, t;
  5553. /* true names of the vertices */
  5554. a = verts[ u ];
  5555. b = verts[ v ];
  5556. c = verts[ w ];
  5557. /* output Triangle */
  5558. /*
  5559. result.push( contour[ a ] );
  5560. result.push( contour[ b ] );
  5561. result.push( contour[ c ] );
  5562. */
  5563. result.push( [ contour[ a ],
  5564. contour[ b ],
  5565. contour[ c ] ] );
  5566. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  5567. /* remove v from the remaining polygon */
  5568. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  5569. verts[ s ] = verts[ t ];
  5570. }
  5571. nv--;
  5572. /* reset error detection counter */
  5573. count = 2 * nv;
  5574. }
  5575. }
  5576. if ( indices ) return vertIndices;
  5577. return result;
  5578. };
  5579. // calculate area of the contour polygon
  5580. var area = function ( contour ) {
  5581. var n = contour.length;
  5582. var a = 0.0;
  5583. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  5584. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  5585. }
  5586. return a * 0.5;
  5587. };
  5588. // see if p is inside triangle abc
  5589. var insideTriangle = function( ax, ay,
  5590. bx, by,
  5591. cx, cy,
  5592. px, py ) {
  5593. var aX, aY, bX, bY;
  5594. var cX, cY, apx, apy;
  5595. var bpx, bpy, cpx, cpy;
  5596. var cCROSSap, bCROSScp, aCROSSbp;
  5597. aX = cx - bx; aY = cy - by;
  5598. bX = ax - cx; bY = ay - cy;
  5599. cX = bx - ax; cY = by - ay;
  5600. apx= px -ax; apy= py - ay;
  5601. bpx= px - bx; bpy= py - by;
  5602. cpx= px - cx; cpy= py - cy;
  5603. aCROSSbp = aX*bpy - aY*bpx;
  5604. cCROSSap = cX*apy - cY*apx;
  5605. bCROSScp = bX*cpy - bY*cpx;
  5606. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  5607. };
  5608. var snip = function ( contour, u, v, w, n, verts ) {
  5609. var p;
  5610. var ax, ay, bx, by;
  5611. var cx, cy, px, py;
  5612. ax = contour[ verts[ u ] ].x;
  5613. ay = contour[ verts[ u ] ].y;
  5614. bx = contour[ verts[ v ] ].x;
  5615. by = contour[ verts[ v ] ].y;
  5616. cx = contour[ verts[ w ] ].x;
  5617. cy = contour[ verts[ w ] ].y;
  5618. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  5619. for ( p = 0; p < n; p++ ) {
  5620. if( (p == u) || (p == v) || (p == w) ) continue;
  5621. px = contour[ verts[ p ] ].x
  5622. py = contour[ verts[ p ] ].y
  5623. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  5624. }
  5625. return true;
  5626. };
  5627. namespace.Triangulate = process;
  5628. namespace.Triangulate.area = area;
  5629. return namespace;
  5630. })(THREE.FontUtils);
  5631. // To use the typeface.js face files, hook up the API
  5632. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  5633. /**
  5634. * @author oosmoxiecode
  5635. * @author mr.doob / http://mrdoob.com/
  5636. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  5637. */
  5638. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  5639. THREE.Geometry.call( this );
  5640. var scope = this;
  5641. this.radius = radius || 100;
  5642. this.tube = tube || 40;
  5643. this.segmentsR = segmentsR || 8;
  5644. this.segmentsT = segmentsT || 6;
  5645. this.arc = arc || Math.PI * 2;
  5646. var center = new THREE.Vector3(), uvs = [], normals = [];
  5647. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  5648. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  5649. var u = i / this.segmentsT * this.arc;
  5650. var v = j / this.segmentsR * Math.PI * 2;
  5651. center.x = this.radius * Math.cos( u );
  5652. center.y = this.radius * Math.sin( u );
  5653. var vertex = new THREE.Vector3();
  5654. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  5655. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  5656. vertex.z = this.tube * Math.sin( v );
  5657. this.vertices.push( vertex );
  5658. uvs.push( new THREE.UV( i / this.segmentsT, 1 - j / this.segmentsR ) );
  5659. normals.push( vertex.clone().subSelf( center ).normalize() );
  5660. }
  5661. }
  5662. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  5663. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  5664. var a = ( this.segmentsT + 1 ) * j + i - 1;
  5665. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  5666. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  5667. var d = ( this.segmentsT + 1 ) * j + i;
  5668. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  5669. face.normal.addSelf( normals[ a ] );
  5670. face.normal.addSelf( normals[ b ] );
  5671. face.normal.addSelf( normals[ c ] );
  5672. face.normal.addSelf( normals[ d ] );
  5673. face.normal.normalize();
  5674. this.faces.push( face );
  5675. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  5676. }
  5677. }
  5678. this.computeCentroids();
  5679. };
  5680. THREE.TorusGeometry.prototype = new THREE.Geometry();
  5681. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  5682. /**
  5683. * @author oosmoxiecode
  5684. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  5685. */
  5686. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  5687. THREE.Geometry.call( this );
  5688. var scope = this;
  5689. this.radius = radius || 200;
  5690. this.tube = tube || 40;
  5691. this.segmentsR = segmentsR || 64;
  5692. this.segmentsT = segmentsT || 8;
  5693. this.p = p || 2;
  5694. this.q = q || 3;
  5695. this.heightScale = heightScale || 1;
  5696. this.grid = new Array(this.segmentsR);
  5697. var tang = new THREE.Vector3();
  5698. var n = new THREE.Vector3();
  5699. var bitan = new THREE.Vector3();
  5700. for ( var i = 0; i < this.segmentsR; ++ i ) {
  5701. this.grid[ i ] = new Array( this.segmentsT );
  5702. for ( var j = 0; j < this.segmentsT; ++ j ) {
  5703. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  5704. var v = j / this.segmentsT * 2 * Math.PI;
  5705. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  5706. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  5707. var cx, cy;
  5708. tang.sub( p2, p1 );
  5709. n.add( p2, p1 );
  5710. bitan.cross( tang, n );
  5711. n.cross( bitan, tang );
  5712. bitan.normalize();
  5713. n.normalize();
  5714. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  5715. cy = this.tube * Math.sin( v );
  5716. p1.x += cx * n.x + cy * bitan.x;
  5717. p1.y += cx * n.y + cy * bitan.y;
  5718. p1.z += cx * n.z + cy * bitan.z;
  5719. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  5720. }
  5721. }
  5722. for ( var i = 0; i < this.segmentsR; ++ i ) {
  5723. for ( var j = 0; j < this.segmentsT; ++ j ) {
  5724. var ip = ( i + 1 ) % this.segmentsR;
  5725. var jp = ( j + 1 ) % this.segmentsT;
  5726. var a = this.grid[ i ][ j ];
  5727. var b = this.grid[ ip ][ j ];
  5728. var c = this.grid[ ip ][ jp ];
  5729. var d = this.grid[ i ][ jp ];
  5730. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  5731. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  5732. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  5733. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  5734. this.faces.push( new THREE.Face4( a, b, c, d ) );
  5735. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  5736. }
  5737. }
  5738. this.computeCentroids();
  5739. this.computeFaceNormals();
  5740. this.computeVertexNormals();
  5741. function vert( x, y, z ) {
  5742. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  5743. }
  5744. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  5745. var cu = Math.cos( u );
  5746. var cv = Math.cos( v );
  5747. var su = Math.sin( u );
  5748. var quOverP = in_q / in_p * u;
  5749. var cs = Math.cos( quOverP );
  5750. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  5751. var ty = radius * ( 2 + cs ) * su * 0.5;
  5752. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  5753. return new THREE.Vector3( tx, ty, tz );
  5754. }
  5755. };
  5756. THREE.TorusKnotGeometry.prototype = new THREE.Geometry();
  5757. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  5758. /**
  5759. * @author WestLangley / https://github.com/WestLangley
  5760. * @author zz85 / https://github.com/zz85
  5761. * @author miningold / https://github.com/miningold
  5762. *
  5763. * Modified from the TorusKnotGeometry by @oosmoxiecode
  5764. *
  5765. * Creates a tube which extrudes along a 3d spline
  5766. *
  5767. * Uses parallel transport frames as described in
  5768. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  5769. */
  5770. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  5771. THREE.Geometry.call( this );
  5772. this.path = path;
  5773. this.segments = segments || 64;
  5774. this.radius = radius || 1;
  5775. this.segmentsRadius = segmentsRadius || 8;
  5776. this.closed = closed || false;
  5777. if ( debug ) this.debug = new THREE.Object3D();
  5778. this.grid = [];
  5779. var scope = this,
  5780. tangent,
  5781. normal,
  5782. binormal,
  5783. numpoints = this.segments + 1,
  5784. x, y, z,
  5785. tx, ty, tz,
  5786. u, v,
  5787. cx, cy,
  5788. pos, pos2 = new THREE.Vector3(),
  5789. i, j,
  5790. ip, jp,
  5791. a, b, c, d,
  5792. uva, uvb, uvc, uvd;
  5793. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  5794. tangents = frames.tangents,
  5795. normals = frames.normals,
  5796. binormals = frames.binormals;
  5797. // proxy internals
  5798. this.tangents = tangents;
  5799. this.normals = normals;
  5800. this.binormals = binormals;
  5801. function vert( x, y, z ) {
  5802. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  5803. }
  5804. // consruct the grid
  5805. for ( i = 0; i < numpoints; i++ ) {
  5806. this.grid[ i ] = [];
  5807. u = i / ( numpoints - 1 );
  5808. pos = path.getPointAt( u );
  5809. tangent = tangents[ i ];
  5810. normal = normals[ i ];
  5811. binormal = binormals[ i ];
  5812. if ( this.debug ) {
  5813. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  5814. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  5815. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  5816. }
  5817. for ( j = 0; j < this.segmentsRadius; j++ ) {
  5818. v = j / this.segmentsRadius * 2 * Math.PI;
  5819. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  5820. cy = this.radius * Math.sin( v );
  5821. pos2.copy( pos );
  5822. pos2.x += cx * normal.x + cy * binormal.x;
  5823. pos2.y += cx * normal.y + cy * binormal.y;
  5824. pos2.z += cx * normal.z + cy * binormal.z;
  5825. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  5826. }
  5827. }
  5828. // construct the mesh
  5829. for ( i = 0; i < this.segments; i++ ) {
  5830. for ( j = 0; j < this.segmentsRadius; j++ ) {
  5831. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  5832. jp = (j + 1) % this.segmentsRadius;
  5833. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  5834. b = this.grid[ ip ][ j ];
  5835. c = this.grid[ ip ][ jp ];
  5836. d = this.grid[ i ][ jp ];
  5837. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  5838. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  5839. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  5840. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  5841. this.faces.push( new THREE.Face4( a, b, c, d ) );
  5842. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  5843. }
  5844. }
  5845. this.computeCentroids();
  5846. this.computeFaceNormals();
  5847. this.computeVertexNormals();
  5848. };
  5849. THREE.TubeGeometry.prototype = new THREE.Geometry();
  5850. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  5851. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  5852. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  5853. var
  5854. tangent = new THREE.Vector3(),
  5855. normal = new THREE.Vector3(),
  5856. binormal = new THREE.Vector3(),
  5857. tangents = [],
  5858. normals = [],
  5859. binormals = [],
  5860. vec = new THREE.Vector3(),
  5861. mat = new THREE.Matrix4(),
  5862. numpoints = segments + 1,
  5863. theta,
  5864. epsilon = 0.0001,
  5865. smallest,
  5866. tx, ty, tz,
  5867. i, u, v;
  5868. // expose internals
  5869. this.tangents = tangents;
  5870. this.normals = normals;
  5871. this.binormals = binormals;
  5872. // compute the tangent vectors for each segment on the path
  5873. for ( i = 0; i < numpoints; i++ ) {
  5874. u = i / ( numpoints - 1 );
  5875. tangents[ i ] = path.getTangentAt( u );
  5876. tangents[ i ].normalize();
  5877. }
  5878. initialNormal3();
  5879. function initialNormal1(lastBinormal) {
  5880. // fixed start binormal. Has dangers of 0 vectors
  5881. normals[ 0 ] = new THREE.Vector3();
  5882. binormals[ 0 ] = new THREE.Vector3();
  5883. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  5884. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  5885. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  5886. }
  5887. function initialNormal2() {
  5888. // This uses the Frenet-Serret formula for deriving binormal
  5889. var t2 = path.getTangentAt( epsilon );
  5890. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  5891. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  5892. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  5893. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  5894. }
  5895. function initialNormal3() {
  5896. // select an initial normal vector perpenicular to the first tangent vector,
  5897. // and in the direction of the smallest tangent xyz component
  5898. normals[ 0 ] = new THREE.Vector3();
  5899. binormals[ 0 ] = new THREE.Vector3();
  5900. smallest = Number.MAX_VALUE;
  5901. tx = Math.abs( tangents[ 0 ].x );
  5902. ty = Math.abs( tangents[ 0 ].y );
  5903. tz = Math.abs( tangents[ 0 ].z );
  5904. if ( tx <= smallest ) {
  5905. smallest = tx;
  5906. normal.set( 1, 0, 0 );
  5907. }
  5908. if ( ty <= smallest ) {
  5909. smallest = ty;
  5910. normal.set( 0, 1, 0 );
  5911. }
  5912. if ( tz <= smallest ) {
  5913. normal.set( 0, 0, 1 );
  5914. }
  5915. vec.cross( tangents[ 0 ], normal ).normalize();
  5916. normals[ 0 ].cross( tangents[ 0 ], vec );
  5917. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  5918. }
  5919. // compute the slowly-varying normal and binormal vectors for each segment on the path
  5920. for ( i = 1; i < numpoints; i++ ) {
  5921. normals[ i ] = normals[ i-1 ].clone();
  5922. binormals[ i ] = binormals[ i-1 ].clone();
  5923. vec.cross( tangents[ i-1 ], tangents[ i ] );
  5924. if ( vec.length() > epsilon ) {
  5925. vec.normalize();
  5926. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  5927. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  5928. }
  5929. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  5930. }
  5931. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  5932. if ( closed ) {
  5933. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  5934. theta /= ( numpoints - 1 );
  5935. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  5936. theta = -theta;
  5937. }
  5938. for ( i = 1; i < numpoints; i++ ) {
  5939. // twist a little...
  5940. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  5941. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  5942. }
  5943. }
  5944. };
  5945. /**
  5946. * @author clockworkgeek / https://github.com/clockworkgeek
  5947. * @author timothypratley / https://github.com/timothypratley
  5948. */
  5949. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  5950. THREE.Geometry.call( this );
  5951. radius = radius || 1;
  5952. detail = detail || 0;
  5953. var that = this;
  5954. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  5955. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  5956. }
  5957. var midpoints = [], p = this.vertices;
  5958. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  5959. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  5960. }
  5961. this.mergeVertices();
  5962. // Apply radius
  5963. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  5964. this.vertices[ i ].multiplyScalar( radius );
  5965. }
  5966. /**
  5967. * Project vector onto sphere's surface
  5968. */
  5969. function prepare( vector ) {
  5970. var vertex = vector.normalize().clone();
  5971. vertex.index = that.vertices.push( vertex ) - 1;
  5972. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  5973. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  5974. var v = inclination( vector ) / Math.PI + 0.5;
  5975. vertex.uv = new THREE.UV( u, v );
  5976. return vertex;
  5977. }
  5978. /**
  5979. * Approximate a curved face with recursively sub-divided triangles.
  5980. */
  5981. function make( v1, v2, v3, detail ) {
  5982. if ( detail < 1 ) {
  5983. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  5984. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  5985. face.normal = face.centroid.clone().normalize();
  5986. that.faces.push( face );
  5987. var azi = azimuth( face.centroid );
  5988. that.faceVertexUvs[ 0 ].push( [
  5989. correctUV( v1.uv, v1, azi ),
  5990. correctUV( v2.uv, v2, azi ),
  5991. correctUV( v3.uv, v3, azi )
  5992. ] );
  5993. }
  5994. else {
  5995. detail -= 1;
  5996. // split triangle into 4 smaller triangles
  5997. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  5998. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  5999. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  6000. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  6001. }
  6002. }
  6003. function midpoint( v1, v2 ) {
  6004. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  6005. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  6006. var mid = midpoints[ v1.index ][ v2.index ];
  6007. if ( mid === undefined ) {
  6008. // generate mean point and project to surface with prepare()
  6009. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  6010. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  6011. );
  6012. }
  6013. return mid;
  6014. }
  6015. /**
  6016. * Angle around the Y axis, counter-clockwise when looking from above.
  6017. */
  6018. function azimuth( vector ) {
  6019. return Math.atan2( vector.z, -vector.x );
  6020. }
  6021. /**
  6022. * Angle above the XZ plane.
  6023. */
  6024. function inclination( vector ) {
  6025. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  6026. }
  6027. /**
  6028. * Texture fixing helper. Spheres have some odd behaviours.
  6029. */
  6030. function correctUV( uv, vector, azimuth ) {
  6031. if ( (azimuth < 0) && (uv.u === 1) ) uv = new THREE.UV( uv.u - 1, uv.v );
  6032. if ( (vector.x === 0) && (vector.z === 0) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  6033. return uv;
  6034. }
  6035. this.computeCentroids();
  6036. this.boundingSphere = { radius: radius };
  6037. };
  6038. THREE.PolyhedronGeometry.prototype = new THREE.Geometry();
  6039. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  6040. /**
  6041. * @author timothypratley / https://github.com/timothypratley
  6042. */
  6043. THREE.IcosahedronGeometry = function ( radius, detail ) {
  6044. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  6045. var vertices = [
  6046. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  6047. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  6048. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  6049. ];
  6050. var faces = [
  6051. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  6052. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  6053. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  6054. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  6055. ];
  6056. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  6057. };
  6058. THREE.IcosahedronGeometry.prototype = new THREE.Geometry();
  6059. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  6060. /**
  6061. * @author timothypratley / https://github.com/timothypratley
  6062. */
  6063. THREE.OctahedronGeometry = function ( radius, detail ) {
  6064. var vertices = [
  6065. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  6066. ];
  6067. var faces = [
  6068. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  6069. ];
  6070. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  6071. };
  6072. THREE.OctahedronGeometry.prototype = new THREE.Geometry();
  6073. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  6074. /**
  6075. * @author timothypratley / https://github.com/timothypratley
  6076. */
  6077. THREE.TetrahedronGeometry = function ( radius, detail ) {
  6078. var vertices = [
  6079. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  6080. ];
  6081. var faces = [
  6082. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  6083. ];
  6084. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  6085. };
  6086. THREE.TetrahedronGeometry.prototype = new THREE.Geometry();
  6087. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  6088. /**
  6089. * @author sroucheray / http://sroucheray.org/
  6090. * @author mr.doob / http://mrdoob.com/
  6091. */
  6092. THREE.AxisHelper = function () {
  6093. THREE.Object3D.call( this );
  6094. var lineGeometry = new THREE.Geometry();
  6095. lineGeometry.vertices.push( new THREE.Vector3() );
  6096. lineGeometry.vertices.push( new THREE.Vector3( 0, 100, 0 ) );
  6097. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  6098. var line, cone;
  6099. // x
  6100. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  6101. line.rotation.z = - Math.PI / 2;
  6102. this.add( line );
  6103. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  6104. cone.position.x = 100;
  6105. cone.rotation.z = - Math.PI / 2;
  6106. this.add( cone );
  6107. // y
  6108. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  6109. this.add( line );
  6110. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  6111. cone.position.y = 100;
  6112. this.add( cone );
  6113. // z
  6114. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  6115. line.rotation.x = Math.PI / 2;
  6116. this.add( line );
  6117. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  6118. cone.position.z = 100;
  6119. cone.rotation.x = Math.PI / 2;
  6120. this.add( cone );
  6121. };
  6122. THREE.AxisHelper.prototype = new THREE.Object3D();
  6123. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  6124. /**
  6125. * @author WestLangley / https://github.com/WestLangley
  6126. * @author zz85 / https://github.com/zz85
  6127. *
  6128. * Creates an arrow for visualizing directions
  6129. *
  6130. * Parameters:
  6131. * dir - Vector3
  6132. * origin - Vector3
  6133. * length - Number
  6134. * hex - color in hex value
  6135. */
  6136. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  6137. THREE.Object3D.call( this );
  6138. if ( hex === undefined ) hex = 0xffff00;
  6139. if ( length === undefined ) length = 20;
  6140. var lineGeometry = new THREE.Geometry();
  6141. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  6142. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  6143. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  6144. this.add( this.line );
  6145. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  6146. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  6147. this.cone.position.set( 0, 1, 0 );
  6148. this.add( this.cone );
  6149. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  6150. this.setDirection( dir );
  6151. this.setLength( length );
  6152. };
  6153. THREE.ArrowHelper.prototype = new THREE.Object3D();
  6154. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  6155. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  6156. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  6157. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  6158. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  6159. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  6160. };
  6161. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  6162. this.scale.set( length, length, length );
  6163. };
  6164. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  6165. this.line.material.color.setHex( hex );
  6166. this.cone.material.color.setHex( hex );
  6167. };
  6168. /**
  6169. * @author alteredq / http://alteredqualia.com/
  6170. *
  6171. * - shows frustum, line of sight and up of the camera
  6172. * - suitable for fast updates
  6173. * - based on frustum visualization in lightgl.js shadowmap example
  6174. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  6175. */
  6176. THREE.CameraHelper = function ( camera ) {
  6177. THREE.Object3D.call( this );
  6178. var _this = this;
  6179. this.lineGeometry = new THREE.Geometry();
  6180. this.lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  6181. this.pointMap = {};
  6182. // colors
  6183. var hexFrustum = 0xffaa00,
  6184. hexCone = 0xff0000,
  6185. hexUp = 0x00aaff,
  6186. hexTarget = 0xffffff,
  6187. hexCross = 0x333333;
  6188. // near
  6189. addLine( "n1", "n2", hexFrustum );
  6190. addLine( "n2", "n4", hexFrustum );
  6191. addLine( "n4", "n3", hexFrustum );
  6192. addLine( "n3", "n1", hexFrustum );
  6193. // far
  6194. addLine( "f1", "f2", hexFrustum );
  6195. addLine( "f2", "f4", hexFrustum );
  6196. addLine( "f4", "f3", hexFrustum );
  6197. addLine( "f3", "f1", hexFrustum );
  6198. // sides
  6199. addLine( "n1", "f1", hexFrustum );
  6200. addLine( "n2", "f2", hexFrustum );
  6201. addLine( "n3", "f3", hexFrustum );
  6202. addLine( "n4", "f4", hexFrustum );
  6203. // cone
  6204. addLine( "p", "n1", hexCone );
  6205. addLine( "p", "n2", hexCone );
  6206. addLine( "p", "n3", hexCone );
  6207. addLine( "p", "n4", hexCone );
  6208. // up
  6209. addLine( "u1", "u2", hexUp );
  6210. addLine( "u2", "u3", hexUp );
  6211. addLine( "u3", "u1", hexUp );
  6212. // target
  6213. addLine( "c", "t", hexTarget );
  6214. addLine( "p", "c", hexCross );
  6215. // cross
  6216. addLine( "cn1", "cn2", hexCross );
  6217. addLine( "cn3", "cn4", hexCross );
  6218. addLine( "cf1", "cf2", hexCross );
  6219. addLine( "cf3", "cf4", hexCross );
  6220. this.camera = camera;
  6221. function addLine( a, b, hex ) {
  6222. addPoint( a, hex );
  6223. addPoint( b, hex );
  6224. }
  6225. function addPoint( id, hex ) {
  6226. _this.lineGeometry.vertices.push( new THREE.Vector3() );
  6227. _this.lineGeometry.colors.push( new THREE.Color( hex ) );
  6228. if ( _this.pointMap[ id ] === undefined ) _this.pointMap[ id ] = [];
  6229. _this.pointMap[ id ].push( _this.lineGeometry.vertices.length - 1 );
  6230. }
  6231. this.update( camera );
  6232. this.lines = new THREE.Line( this.lineGeometry, this.lineMaterial, THREE.LinePieces );
  6233. this.add( this.lines );
  6234. };
  6235. THREE.CameraHelper.prototype = new THREE.Object3D();
  6236. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  6237. THREE.CameraHelper.prototype.update = function () {
  6238. var camera = this.camera;
  6239. var w = 1;
  6240. var h = 1;
  6241. var _this = this;
  6242. // we need just camera projection matrix
  6243. // world matrix must be identity
  6244. THREE.CameraHelper.__c.projectionMatrix.copy( camera.projectionMatrix );
  6245. // center / target
  6246. setPoint( "c", 0, 0, -1 );
  6247. setPoint( "t", 0, 0, 1 );
  6248. // near
  6249. setPoint( "n1", -w, -h, -1 );
  6250. setPoint( "n2", w, -h, -1 );
  6251. setPoint( "n3", -w, h, -1 );
  6252. setPoint( "n4", w, h, -1 );
  6253. // far
  6254. setPoint( "f1", -w, -h, 1 );
  6255. setPoint( "f2", w, -h, 1 );
  6256. setPoint( "f3", -w, h, 1 );
  6257. setPoint( "f4", w, h, 1 );
  6258. // up
  6259. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  6260. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  6261. setPoint( "u3", 0, h * 2, -1 );
  6262. // cross
  6263. setPoint( "cf1", -w, 0, 1 );
  6264. setPoint( "cf2", w, 0, 1 );
  6265. setPoint( "cf3", 0, -h, 1 );
  6266. setPoint( "cf4", 0, h, 1 );
  6267. setPoint( "cn1", -w, 0, -1 );
  6268. setPoint( "cn2", w, 0, -1 );
  6269. setPoint( "cn3", 0, -h, -1 );
  6270. setPoint( "cn4", 0, h, -1 );
  6271. function setPoint( point, x, y, z ) {
  6272. THREE.CameraHelper.__v.set( x, y, z );
  6273. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  6274. var points = _this.pointMap[ point ];
  6275. if ( points !== undefined ) {
  6276. for ( var i = 0, il = points.length; i < il; i ++ ) {
  6277. var j = points[ i ];
  6278. _this.lineGeometry.vertices[ j ].copy( THREE.CameraHelper.__v );
  6279. }
  6280. }
  6281. }
  6282. this.lineGeometry.__dirtyVertices = true;
  6283. };
  6284. THREE.CameraHelper.__projector = new THREE.Projector();
  6285. THREE.CameraHelper.__v = new THREE.Vector3();
  6286. THREE.CameraHelper.__c = new THREE.Camera();
  6287. /*
  6288. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  6289. *
  6290. * Subdivision Geometry Modifier
  6291. * using Catmull-Clark Subdivision Surfaces
  6292. * for creating smooth geometry meshes
  6293. *
  6294. * Note: a modifier modifies vertices and faces of geometry,
  6295. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  6296. *
  6297. * Readings:
  6298. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  6299. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  6300. * http://xrt.wikidot.com/blog:31
  6301. * "Subdivision Surfaces in Character Animation"
  6302. *
  6303. * Supports:
  6304. * Closed and Open geometries.
  6305. *
  6306. * TODO:
  6307. * crease vertex and "semi-sharp" features
  6308. * selective subdivision
  6309. */
  6310. THREE.SubdivisionModifier = function( subdivisions ) {
  6311. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  6312. // Settings
  6313. this.useOldVertexColors = false;
  6314. this.supportUVs = true;
  6315. this.debug = false;
  6316. };
  6317. //THREE.SubdivisionModifier.prototype = new THREE.Modifier();
  6318. THREE.SubdivisionModifier.prototype.constructor = THREE.SubdivisionModifier;
  6319. // Applies the "modify" pattern
  6320. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  6321. var repeats = this.subdivisions;
  6322. while ( repeats-- > 0 ) {
  6323. this.smooth( geometry );
  6324. }
  6325. };
  6326. // Performs an iteration of Catmull-Clark Subdivision
  6327. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  6328. //debug( 'running smooth' );
  6329. // New set of vertices, faces and uvs
  6330. var newVertices = [], newFaces = [], newUVs = [];
  6331. function v( x, y, z ) {
  6332. newVertices.push( new THREE.Vector3( x, y, z ) );
  6333. }
  6334. var scope = this;
  6335. function debug() {
  6336. if (scope.debug) console.log.apply(console, arguments);
  6337. }
  6338. function warn() {
  6339. if (console)
  6340. console.log.apply(console, arguments);
  6341. }
  6342. function f4( a, b, c, d, oldFace, orders, facei ) {
  6343. // TODO move vertex selection over here!
  6344. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.material );
  6345. if (scope.useOldVertexColors) {
  6346. newFace.vertexColors = [];
  6347. var color, tmpColor, order;
  6348. for (var i=0;i<4;i++) {
  6349. order = orders[i];
  6350. color = new THREE.Color(),
  6351. color.setRGB(0,0,0);
  6352. for (var j=0, jl=0; j<order.length;j++) {
  6353. tmpColor = oldFace.vertexColors[order[j]-1];
  6354. color.r += tmpColor.r;
  6355. color.g += tmpColor.g;
  6356. color.b += tmpColor.b;
  6357. }
  6358. color.r /= order.length;
  6359. color.g /= order.length;
  6360. color.b /= order.length;
  6361. newFace.vertexColors[i] = color;
  6362. }
  6363. }
  6364. newFaces.push( newFace );
  6365. if (scope.supportUVs) {
  6366. var aUv = [
  6367. getUV(a, ''),
  6368. getUV(b, facei),
  6369. getUV(c, facei),
  6370. getUV(d, facei)
  6371. ];
  6372. if (!aUv[0]) debug('a :( ', a+':'+facei);
  6373. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  6374. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  6375. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  6376. else
  6377. newUVs.push( aUv );
  6378. }
  6379. }
  6380. function edge_hash( a, b ) {
  6381. return Math.min( a, b ) + "_" + Math.max( a, b );
  6382. }
  6383. function computeEdgeFaces( geometry ) {
  6384. var i, il, v1, v2, j, k,
  6385. face, faceIndices, faceIndex,
  6386. edge,
  6387. hash,
  6388. edgeFaceMap = {};
  6389. function mapEdgeHash( hash, i ) {
  6390. if ( edgeFaceMap[ hash ] === undefined ) {
  6391. edgeFaceMap[ hash ] = [];
  6392. }
  6393. edgeFaceMap[ hash ].push( i );
  6394. }
  6395. // construct vertex -> face map
  6396. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  6397. face = geometry.faces[ i ];
  6398. if ( face instanceof THREE.Face3 ) {
  6399. hash = edge_hash( face.a, face.b );
  6400. mapEdgeHash( hash, i );
  6401. hash = edge_hash( face.b, face.c );
  6402. mapEdgeHash( hash, i );
  6403. hash = edge_hash( face.c, face.a );
  6404. mapEdgeHash( hash, i );
  6405. } else if ( face instanceof THREE.Face4 ) {
  6406. hash = edge_hash( face.a, face.b );
  6407. mapEdgeHash( hash, i );
  6408. hash = edge_hash( face.b, face.c );
  6409. mapEdgeHash( hash, i );
  6410. hash = edge_hash( face.c, face.d );
  6411. mapEdgeHash( hash, i );
  6412. hash = edge_hash( face.d, face.a );
  6413. mapEdgeHash( hash, i );
  6414. }
  6415. }
  6416. // extract faces
  6417. // var edges = [];
  6418. //
  6419. // var numOfEdges = 0;
  6420. // for (i in edgeFaceMap) {
  6421. // numOfEdges++;
  6422. //
  6423. // edge = edgeFaceMap[i];
  6424. // edges.push(edge);
  6425. //
  6426. // }
  6427. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  6428. return edgeFaceMap;
  6429. }
  6430. var originalPoints = oldGeometry.vertices;
  6431. var originalFaces = oldGeometry.faces;
  6432. var newPoints = originalPoints.concat(); // Vertices
  6433. var facePoints = [], edgePoints = {};
  6434. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  6435. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  6436. var originalVerticesLength = originalPoints.length;
  6437. function getUV(vertexNo, oldFaceNo) {
  6438. var j,jl;
  6439. var key = vertexNo+':'+oldFaceNo;
  6440. var theUV = uvForVertices[key];
  6441. if (!theUV) {
  6442. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  6443. debug('face pt');
  6444. } else {
  6445. debug('edge pt');
  6446. }
  6447. warn('warning, UV not found for', key);
  6448. return null;
  6449. }
  6450. return theUV;
  6451. // Original faces -> Vertex Nos.
  6452. // new Facepoint -> Vertex Nos.
  6453. // edge Points
  6454. }
  6455. function addUV(vertexNo, oldFaceNo, value) {
  6456. var key = vertexNo+':'+oldFaceNo;
  6457. if (!(key in uvForVertices)) {
  6458. uvForVertices[key] = value;
  6459. } else {
  6460. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  6461. }
  6462. }
  6463. // Step 1
  6464. // For each face, add a face point
  6465. // Set each face point to be the centroid of all original points for the respective face.
  6466. // debug(oldGeometry);
  6467. var i, il, j, jl, face;
  6468. // For Uvs
  6469. var uvs = oldGeometry.faceVertexUvs[0];
  6470. var abcd = 'abcd', vertice;
  6471. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  6472. if (scope.supportUVs)
  6473. for (i=0, il = uvs.length; i<il; i++ ) {
  6474. for (j=0,jl=uvs[i].length;j<jl;j++) {
  6475. vertice = originalFaces[i][abcd.charAt(j)];
  6476. addUV(vertice, i, uvs[i][j]);
  6477. }
  6478. }
  6479. if (uvs.length == 0) scope.supportUVs = false;
  6480. // Additional UVs check, if we index original
  6481. var uvCount = 0;
  6482. for (var u in uvForVertices) {
  6483. uvCount++;
  6484. }
  6485. if (!uvCount) {
  6486. scope.supportUVs = false;
  6487. debug('no uvs');
  6488. }
  6489. debug('-- Original Faces + Vertices UVs completed', uvForVertices, 'vs', uvs.length);
  6490. var avgUv ;
  6491. for (i=0, il = originalFaces.length; i<il ;i++) {
  6492. face = originalFaces[ i ];
  6493. facePoints.push( face.centroid );
  6494. newPoints.push( face.centroid );
  6495. if (!scope.supportUVs) continue;
  6496. // Prepare subdivided uv
  6497. avgUv = new THREE.UV();
  6498. if ( face instanceof THREE.Face3 ) {
  6499. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  6500. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  6501. avgUv.u /= 3;
  6502. avgUv.v /= 3;
  6503. } else if ( face instanceof THREE.Face4 ) {
  6504. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  6505. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  6506. avgUv.u /= 4;
  6507. avgUv.v /= 4;
  6508. }
  6509. addUV(originalVerticesLength + i, '', avgUv);
  6510. }
  6511. debug('-- added UVs for new Faces', uvForVertices);
  6512. // Step 2
  6513. // For each edge, add an edge point.
  6514. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  6515. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index
  6516. var edge, faceIndexA, faceIndexB, avg;
  6517. // debug('edgeFaceMap', edgeFaceMap);
  6518. var edgeCount = 0;
  6519. var edgeVertex, edgeVertexA, edgeVertexB;
  6520. ////
  6521. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  6522. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  6523. function addVertexEdgeMap(vertex, edge) {
  6524. if (vertexEdgeMap[vertex]===undefined) {
  6525. vertexEdgeMap[vertex] = [];
  6526. }
  6527. vertexEdgeMap[vertex].push(edge);
  6528. }
  6529. function addVertexFaceMap(vertex, face, edge) {
  6530. if (vertexFaceMap[vertex]===undefined) {
  6531. vertexFaceMap[vertex] = {};
  6532. }
  6533. vertexFaceMap[vertex][face] = edge;
  6534. // vertexFaceMap[vertex][face] = null;
  6535. }
  6536. // Prepares vertexEdgeMap and vertexFaceMap
  6537. for (i in edgeFaceMap) { // This is for every edge
  6538. edge = edgeFaceMap[i];
  6539. edgeVertex = i.split('_');
  6540. edgeVertexA = edgeVertex[0];
  6541. edgeVertexB = edgeVertex[1];
  6542. // Maps an edgeVertex to connecting edges
  6543. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  6544. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  6545. for (j=0,jl=edge.length;j<jl;j++) {
  6546. face = edge[j];
  6547. addVertexFaceMap(edgeVertexA, face, i);
  6548. addVertexFaceMap(edgeVertexB, face, i);
  6549. }
  6550. if (edge.length < 2) {
  6551. // edge is "sharp";
  6552. sharpEdges[i] = true;
  6553. sharpVertices[edgeVertexA] = true;
  6554. sharpVertices[edgeVertexB] = true;
  6555. }
  6556. }
  6557. debug('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  6558. for (i in edgeFaceMap) {
  6559. edge = edgeFaceMap[i];
  6560. faceIndexA = edge[0]; // face index a
  6561. faceIndexB = edge[1]; // face index b
  6562. edgeVertex = i.split('_');
  6563. edgeVertexA = edgeVertex[0];
  6564. edgeVertexB = edgeVertex[1];
  6565. avg = new THREE.Vector3();
  6566. //debug(i, faceIndexB,facePoints[faceIndexB]);
  6567. if (sharpEdges[i]) {
  6568. //debug('warning, ', i, 'edge has only 1 connecting face', edge);
  6569. // For a sharp edge, average the edge end points.
  6570. avg.addSelf(originalPoints[edgeVertexA]);
  6571. avg.addSelf(originalPoints[edgeVertexB]);
  6572. avg.multiplyScalar(0.5);
  6573. sharpVertices[newPoints.length] = true;
  6574. } else {
  6575. avg.addSelf(facePoints[faceIndexA]);
  6576. avg.addSelf(facePoints[faceIndexB]);
  6577. avg.addSelf(originalPoints[edgeVertexA]);
  6578. avg.addSelf(originalPoints[edgeVertexB]);
  6579. avg.multiplyScalar(0.25);
  6580. }
  6581. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  6582. newPoints.push( avg );
  6583. edgeCount ++;
  6584. if (!scope.supportUVs) {
  6585. continue;
  6586. }
  6587. // debug('faceIndexAB', faceIndexA, faceIndexB, sharpEdges[i]);
  6588. // Prepare subdivided uv
  6589. avgUv = new THREE.UV();
  6590. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  6591. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  6592. avgUv.u /= 2;
  6593. avgUv.v /= 2;
  6594. addUV(edgePoints[i], faceIndexA, avgUv);
  6595. if (!sharpEdges[i]) {
  6596. avgUv = new THREE.UV();
  6597. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  6598. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  6599. avgUv.u /= 2;
  6600. avgUv.v /= 2;
  6601. addUV(edgePoints[i], faceIndexB, avgUv);
  6602. }
  6603. }
  6604. debug('-- Step 2 done');
  6605. // Step 3
  6606. // For each face point, add an edge for every edge of the face,
  6607. // connecting the face point to each edge point for the face.
  6608. var facePt, currentVerticeIndex;
  6609. var hashAB, hashBC, hashCD, hashDA, hashCA;
  6610. var abc123 = ['123', '12', '2', '23'];
  6611. var bca123 = ['123', '23', '3', '31'];
  6612. var cab123 = ['123', '31', '1', '12'];
  6613. var abc1234 = ['1234', '12', '2', '23'];
  6614. var bcd1234 = ['1234', '23', '3', '34'];
  6615. var cda1234 = ['1234', '34', '4', '41'];
  6616. var dab1234 = ['1234', '41', '1', '12'];
  6617. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  6618. facePt = facePoints[i];
  6619. face = originalFaces[i];
  6620. currentVerticeIndex = originalVerticesLength+ i;
  6621. if ( face instanceof THREE.Face3 ) {
  6622. // create 3 face4s
  6623. hashAB = edge_hash( face.a, face.b );
  6624. hashBC = edge_hash( face.b, face.c );
  6625. hashCA = edge_hash( face.c, face.a );
  6626. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  6627. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  6628. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  6629. } else if ( face instanceof THREE.Face4 ) {
  6630. // create 4 face4s
  6631. hashAB = edge_hash( face.a, face.b );
  6632. hashBC = edge_hash( face.b, face.c );
  6633. hashCD = edge_hash( face.c, face.d );
  6634. hashDA = edge_hash( face.d, face.a );
  6635. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  6636. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  6637. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  6638. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  6639. } else {
  6640. debug('face should be a face!', face);
  6641. }
  6642. }
  6643. newVertices = newPoints;
  6644. // debug('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  6645. // debug('new points', newPoints.length, 'faces', newFaces.length );
  6646. // Step 4
  6647. // For each original point P,
  6648. // take the average F of all n face points for faces touching P,
  6649. // and take the average R of all n edge midpoints for edges touching P,
  6650. // where each edge midpoint is the average of its two endpoint vertices.
  6651. // Move each original point to the point
  6652. var F = new THREE.Vector3();
  6653. var R = new THREE.Vector3();
  6654. var n;
  6655. for (i=0, il = originalPoints.length; i<il; i++) {
  6656. // (F + 2R + (n-3)P) / n
  6657. if (vertexEdgeMap[i]===undefined) continue;
  6658. F.set(0,0,0);
  6659. R.set(0,0,0);
  6660. var newPos = new THREE.Vector3(0,0,0);
  6661. var f =0;
  6662. for (j in vertexFaceMap[i]) {
  6663. F.addSelf(facePoints[j]);
  6664. f++;
  6665. }
  6666. var sharpEdgeCount = 0;
  6667. n = vertexEdgeMap[i].length;
  6668. for (j=0;j<n;j++) {
  6669. if (
  6670. sharpEdges[
  6671. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  6672. ]) {
  6673. sharpEdgeCount++;
  6674. }
  6675. }
  6676. if ( sharpEdgeCount==2 ) {
  6677. continue;
  6678. // Do not move vertex if there's 2 connecting sharp edges.
  6679. }
  6680. /*
  6681. if (sharpEdgeCount>2) {
  6682. // TODO
  6683. }
  6684. */
  6685. F.divideScalar(f);
  6686. for (j=0; j<n;j++) {
  6687. edge = vertexEdgeMap[i][j];
  6688. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  6689. R.addSelf(midPt);
  6690. // R.addSelf(originalPoints[edge[0]]);
  6691. // R.addSelf(originalPoints[edge[1]]);
  6692. }
  6693. R.divideScalar(n);
  6694. newPos.addSelf(originalPoints[i]);
  6695. newPos.multiplyScalar(n - 3);
  6696. newPos.addSelf(F);
  6697. newPos.addSelf(R.multiplyScalar(2));
  6698. newPos.divideScalar(n);
  6699. newVertices[i] = newPos;
  6700. }
  6701. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  6702. newGeometry.vertices = newVertices;
  6703. newGeometry.faces = newFaces;
  6704. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  6705. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  6706. newGeometry.computeCentroids();
  6707. newGeometry.computeFaceNormals();
  6708. newGeometry.computeVertexNormals();
  6709. };
  6710. /**
  6711. * @author alteredq / http://alteredqualia.com/
  6712. */
  6713. THREE.Loader = function ( showStatus ) {
  6714. this.showStatus = showStatus;
  6715. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6716. this.onLoadStart = function () {};
  6717. this.onLoadProgress = function() {};
  6718. this.onLoadComplete = function () {};
  6719. };
  6720. THREE.Loader.prototype = {
  6721. constructor: THREE.Loader,
  6722. crossOrigin: 'anonymous',
  6723. addStatusElement: function () {
  6724. var e = document.createElement( "div" );
  6725. e.style.position = "absolute";
  6726. e.style.right = "0px";
  6727. e.style.top = "0px";
  6728. e.style.fontSize = "0.8em";
  6729. e.style.textAlign = "left";
  6730. e.style.background = "rgba(0,0,0,0.25)";
  6731. e.style.color = "#fff";
  6732. e.style.width = "120px";
  6733. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6734. e.style.zIndex = 1000;
  6735. e.innerHTML = "Loading ...";
  6736. return e;
  6737. },
  6738. updateProgress: function ( progress ) {
  6739. var message = "Loaded ";
  6740. if ( progress.total ) {
  6741. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6742. } else {
  6743. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6744. }
  6745. this.statusDomElement.innerHTML = message;
  6746. },
  6747. extractUrlBase: function ( url ) {
  6748. var parts = url.split( '/' );
  6749. parts.pop();
  6750. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  6751. },
  6752. initMaterials: function ( scope, materials, texturePath ) {
  6753. scope.materials = [];
  6754. for ( var i = 0; i < materials.length; ++ i ) {
  6755. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6756. }
  6757. },
  6758. hasNormals: function ( scope ) {
  6759. var m, i, il = scope.materials.length;
  6760. for( i = 0; i < il; i ++ ) {
  6761. m = scope.materials[ i ];
  6762. if ( m instanceof THREE.ShaderMaterial ) return true;
  6763. }
  6764. return false;
  6765. },
  6766. createMaterial: function ( m, texturePath ) {
  6767. var _this = this;
  6768. function is_pow2( n ) {
  6769. var l = Math.log( n ) / Math.LN2;
  6770. return Math.floor( l ) == l;
  6771. }
  6772. function nearest_pow2( n ) {
  6773. var l = Math.log( n ) / Math.LN2;
  6774. return Math.pow( 2, Math.round( l ) );
  6775. }
  6776. function load_image( where, url ) {
  6777. var image = new Image();
  6778. image.onload = function () {
  6779. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6780. var width = nearest_pow2( this.width );
  6781. var height = nearest_pow2( this.height );
  6782. where.image.width = width;
  6783. where.image.height = height;
  6784. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6785. } else {
  6786. where.image = this;
  6787. }
  6788. where.needsUpdate = true;
  6789. };
  6790. image.crossOrigin = _this.crossOrigin;
  6791. image.src = url;
  6792. }
  6793. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  6794. var texture = document.createElement( 'canvas' );
  6795. where[ name ] = new THREE.Texture( texture );
  6796. where[ name ].sourceFile = sourceFile;
  6797. if( repeat ) {
  6798. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6799. if ( repeat[ 0 ] != 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6800. if ( repeat[ 1 ] != 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6801. }
  6802. if ( offset ) {
  6803. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6804. }
  6805. if ( wrap ) {
  6806. var wrapMap = {
  6807. "repeat" : THREE.RepeatWrapping,
  6808. "mirror" : THREE.MirroredRepeatWrapping
  6809. }
  6810. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6811. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6812. }
  6813. load_image( where[ name ], texturePath + "/" + sourceFile );
  6814. }
  6815. function rgb2hex( rgb ) {
  6816. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6817. }
  6818. // defaults
  6819. var mtype = "MeshLambertMaterial";
  6820. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, wireframe: m.wireframe };
  6821. // parameters from model file
  6822. if ( m.shading ) {
  6823. var shading = m.shading.toLowerCase();
  6824. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6825. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6826. }
  6827. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6828. mpars.blending = THREE[ m.blending ];
  6829. }
  6830. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6831. mpars.transparent = m.transparent;
  6832. }
  6833. if ( m.depthTest !== undefined ) {
  6834. mpars.depthTest = m.depthTest;
  6835. }
  6836. if ( m.depthWrite !== undefined ) {
  6837. mpars.depthWrite = m.depthWrite;
  6838. }
  6839. if ( m.vertexColors !== undefined ) {
  6840. if ( m.vertexColors == "face" ) {
  6841. mpars.vertexColors = THREE.FaceColors;
  6842. } else if ( m.vertexColors ) {
  6843. mpars.vertexColors = THREE.VertexColors;
  6844. }
  6845. }
  6846. // colors
  6847. if ( m.colorDiffuse ) {
  6848. mpars.color = rgb2hex( m.colorDiffuse );
  6849. } else if ( m.DbgColor ) {
  6850. mpars.color = m.DbgColor;
  6851. }
  6852. if ( m.colorSpecular ) {
  6853. mpars.specular = rgb2hex( m.colorSpecular );
  6854. }
  6855. if ( m.colorAmbient ) {
  6856. mpars.ambient = rgb2hex( m.colorAmbient );
  6857. }
  6858. // modifiers
  6859. if ( m.transparency ) {
  6860. mpars.opacity = m.transparency;
  6861. }
  6862. if ( m.specularCoef ) {
  6863. mpars.shininess = m.specularCoef;
  6864. }
  6865. // textures
  6866. if ( m.mapDiffuse && texturePath ) {
  6867. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  6868. }
  6869. if ( m.mapLight && texturePath ) {
  6870. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  6871. }
  6872. if ( m.mapNormal && texturePath ) {
  6873. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  6874. }
  6875. if ( m.mapSpecular && texturePath ) {
  6876. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  6877. }
  6878. // special case for normal mapped material
  6879. if ( m.mapNormal ) {
  6880. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6881. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6882. uniforms[ "tNormal" ].texture = mpars.normalMap;
  6883. if ( m.mapNormalFactor ) {
  6884. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  6885. }
  6886. if ( mpars.map ) {
  6887. uniforms[ "tDiffuse" ].texture = mpars.map;
  6888. uniforms[ "enableDiffuse" ].value = true;
  6889. }
  6890. if ( mpars.specularMap ) {
  6891. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  6892. uniforms[ "enableSpecular" ].value = true;
  6893. }
  6894. if ( mpars.lightMap ) {
  6895. uniforms[ "tAO" ].texture = mpars.lightMap;
  6896. uniforms[ "enableAO" ].value = true;
  6897. }
  6898. // for the moment don't handle displacement texture
  6899. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6900. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6901. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6902. uniforms[ "uShininess" ].value = mpars.shininess;
  6903. if ( mpars.opacity !== undefined ) {
  6904. uniforms[ "uOpacity" ].value = mpars.opacity;
  6905. }
  6906. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6907. var material = new THREE.ShaderMaterial( parameters );
  6908. } else {
  6909. var material = new THREE[ mtype ]( mpars );
  6910. }
  6911. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6912. return material;
  6913. }
  6914. };
  6915. /**
  6916. * @author alteredq / http://alteredqualia.com/
  6917. */
  6918. THREE.BinaryLoader = function ( showStatus ) {
  6919. THREE.Loader.call( this, showStatus );
  6920. };
  6921. THREE.BinaryLoader.prototype = new THREE.Loader();
  6922. THREE.BinaryLoader.prototype.constructor = THREE.BinaryLoader;
  6923. THREE.BinaryLoader.prototype.supr = THREE.Loader.prototype;
  6924. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  6925. // - binary models consist of two files: JS and BIN
  6926. // - parameters
  6927. // - url (required)
  6928. // - callback (required)
  6929. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  6930. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  6931. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  6932. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  6933. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  6934. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  6935. this.onLoadStart();
  6936. // #1 load JS part via web worker
  6937. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  6938. };
  6939. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  6940. var xhr = new XMLHttpRequest();
  6941. xhr.onreadystatechange = function () {
  6942. if ( xhr.readyState == 4 ) {
  6943. if ( xhr.status == 200 || xhr.status == 0 ) {
  6944. var json = JSON.parse( xhr.responseText );
  6945. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  6946. } else {
  6947. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6948. }
  6949. }
  6950. };
  6951. xhr.open( "GET", url, true );
  6952. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  6953. xhr.setRequestHeader( "Content-Type", "text/plain" );
  6954. xhr.send( null );
  6955. };
  6956. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  6957. var xhr = new XMLHttpRequest(),
  6958. url = binaryPath + "/" + json.buffers;
  6959. var length = 0;
  6960. xhr.onreadystatechange = function () {
  6961. if ( xhr.readyState == 4 ) {
  6962. if ( xhr.status == 200 || xhr.status == 0 ) {
  6963. THREE.BinaryLoader.prototype.createBinModel( xhr.response, callback, texturePath, json.materials );
  6964. } else {
  6965. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6966. }
  6967. } else if ( xhr.readyState == 3 ) {
  6968. if ( callbackProgress ) {
  6969. if ( length == 0 ) {
  6970. length = xhr.getResponseHeader( "Content-Length" );
  6971. }
  6972. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6973. }
  6974. } else if ( xhr.readyState == 2 ) {
  6975. length = xhr.getResponseHeader( "Content-Length" );
  6976. }
  6977. };
  6978. xhr.open( "GET", url, true );
  6979. xhr.responseType = "arraybuffer";
  6980. xhr.send( null );
  6981. };
  6982. // Binary AJAX parser
  6983. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  6984. var Model = function ( texturePath ) {
  6985. var scope = this,
  6986. currentOffset = 0,
  6987. md,
  6988. normals = [],
  6989. uvs = [],
  6990. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  6991. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  6992. tri_size, quad_size,
  6993. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  6994. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  6995. THREE.Geometry.call( this );
  6996. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  6997. md = parseMetaData( data, currentOffset );
  6998. currentOffset += md.header_bytes;
  6999. /*
  7000. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  7001. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  7002. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  7003. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  7004. */
  7005. // buffers sizes
  7006. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  7007. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  7008. len_tri_flat = md.ntri_flat * ( tri_size );
  7009. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  7010. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  7011. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  7012. len_quad_flat = md.nquad_flat * ( quad_size );
  7013. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  7014. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  7015. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  7016. // read buffers
  7017. currentOffset += init_vertices( currentOffset );
  7018. currentOffset += init_normals( currentOffset );
  7019. currentOffset += handlePadding( md.nnormals * 3 );
  7020. currentOffset += init_uvs( currentOffset );
  7021. start_tri_flat = currentOffset;
  7022. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  7023. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  7024. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  7025. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  7026. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  7027. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  7028. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  7029. // have to first process faces with uvs
  7030. // so that face and uv indices match
  7031. init_triangles_flat_uv( start_tri_flat_uv );
  7032. init_triangles_smooth_uv( start_tri_smooth_uv );
  7033. init_quads_flat_uv( start_quad_flat_uv );
  7034. init_quads_smooth_uv( start_quad_smooth_uv );
  7035. // now we can process untextured faces
  7036. init_triangles_flat( start_tri_flat );
  7037. init_triangles_smooth( start_tri_smooth );
  7038. init_quads_flat( start_quad_flat );
  7039. init_quads_smooth( start_quad_smooth );
  7040. this.computeCentroids();
  7041. this.computeFaceNormals();
  7042. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  7043. function handlePadding( n ) {
  7044. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  7045. };
  7046. function parseMetaData( data, offset ) {
  7047. var metaData = {
  7048. 'signature' :parseString( data, offset, 12 ),
  7049. 'header_bytes' :parseUChar8( data, offset + 12 ),
  7050. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  7051. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  7052. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  7053. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  7054. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  7055. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  7056. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  7057. 'nvertices' :parseUInt32( data, offset + 20 ),
  7058. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  7059. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  7060. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  7061. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  7062. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  7063. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  7064. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  7065. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  7066. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  7067. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  7068. };
  7069. /*
  7070. console.log( "signature: " + metaData.signature );
  7071. console.log( "header_bytes: " + metaData.header_bytes );
  7072. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  7073. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  7074. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  7075. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  7076. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  7077. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  7078. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  7079. console.log( "nvertices: " + metaData.nvertices );
  7080. console.log( "nnormals: " + metaData.nnormals );
  7081. console.log( "nuvs: " + metaData.nuvs );
  7082. console.log( "ntri_flat: " + metaData.ntri_flat );
  7083. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  7084. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  7085. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  7086. console.log( "nquad_flat: " + metaData.nquad_flat );
  7087. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  7088. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  7089. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  7090. var total = metaData.header_bytes
  7091. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  7092. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  7093. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  7094. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  7095. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  7096. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  7097. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  7098. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  7099. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  7100. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  7101. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  7102. console.log( "total bytes: " + total );
  7103. */
  7104. return metaData;
  7105. };
  7106. function parseString( data, offset, length ) {
  7107. var charArray = new Uint8Array( data, offset, length );
  7108. var text = "";
  7109. for ( var i = 0; i < length; i ++ ) {
  7110. text += String.fromCharCode( charArray[ offset + i ] );
  7111. }
  7112. return text;
  7113. };
  7114. function parseUChar8( data, offset ) {
  7115. var charArray = new Uint8Array( data, offset, 1 );
  7116. return charArray[ 0 ];
  7117. };
  7118. function parseUInt32( data, offset ) {
  7119. var intArray = new Uint32Array( data, offset, 1 );
  7120. return intArray[ 0 ];
  7121. };
  7122. function init_vertices( start ) {
  7123. var nElements = md.nvertices;
  7124. var coordArray = new Float32Array( data, start, nElements * 3 );
  7125. var i, x, y, z;
  7126. for( i = 0; i < nElements; i ++ ) {
  7127. x = coordArray[ i * 3 ];
  7128. y = coordArray[ i * 3 + 1 ];
  7129. z = coordArray[ i * 3 + 2 ];
  7130. vertex( scope, x, y, z );
  7131. }
  7132. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  7133. };
  7134. function init_normals( start ) {
  7135. var nElements = md.nnormals;
  7136. if ( nElements ) {
  7137. var normalArray = new Int8Array( data, start, nElements * 3 );
  7138. var i, x, y, z;
  7139. for( i = 0; i < nElements; i ++ ) {
  7140. x = normalArray[ i * 3 ];
  7141. y = normalArray[ i * 3 + 1 ];
  7142. z = normalArray[ i * 3 + 2 ];
  7143. normals.push( x/127, y/127, z/127 );
  7144. }
  7145. }
  7146. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  7147. };
  7148. function init_uvs( start ) {
  7149. var nElements = md.nuvs;
  7150. if ( nElements ) {
  7151. var uvArray = new Float32Array( data, start, nElements * 2 );
  7152. var i, u, v;
  7153. for( i = 0; i < nElements; i ++ ) {
  7154. u = uvArray[ i * 2 ];
  7155. v = uvArray[ i * 2 + 1 ];
  7156. uvs.push( u, v );
  7157. }
  7158. }
  7159. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  7160. };
  7161. function init_uvs3( nElements, offset ) {
  7162. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  7163. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  7164. for( i = 0; i < nElements; i ++ ) {
  7165. uva = uvIndexBuffer[ i * 3 ];
  7166. uvb = uvIndexBuffer[ i * 3 + 1 ];
  7167. uvc = uvIndexBuffer[ i * 3 + 2 ];
  7168. u1 = uvs[ uva*2 ];
  7169. v1 = uvs[ uva*2 + 1 ];
  7170. u2 = uvs[ uvb*2 ];
  7171. v2 = uvs[ uvb*2 + 1 ];
  7172. u3 = uvs[ uvc*2 ];
  7173. v3 = uvs[ uvc*2 + 1 ];
  7174. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  7175. }
  7176. };
  7177. function init_uvs4( nElements, offset ) {
  7178. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  7179. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  7180. for( i = 0; i < nElements; i ++ ) {
  7181. uva = uvIndexBuffer[ i * 4 ];
  7182. uvb = uvIndexBuffer[ i * 4 + 1 ];
  7183. uvc = uvIndexBuffer[ i * 4 + 2 ];
  7184. uvd = uvIndexBuffer[ i * 4 + 3 ];
  7185. u1 = uvs[ uva*2 ];
  7186. v1 = uvs[ uva*2 + 1 ];
  7187. u2 = uvs[ uvb*2 ];
  7188. v2 = uvs[ uvb*2 + 1 ];
  7189. u3 = uvs[ uvc*2 ];
  7190. v3 = uvs[ uvc*2 + 1 ];
  7191. u4 = uvs[ uvd*2 ];
  7192. v4 = uvs[ uvd*2 + 1 ];
  7193. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  7194. }
  7195. };
  7196. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  7197. var i, a, b, c, m;
  7198. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  7199. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  7200. for( i = 0; i < nElements; i ++ ) {
  7201. a = vertexIndexBuffer[ i * 3 ];
  7202. b = vertexIndexBuffer[ i * 3 + 1 ];
  7203. c = vertexIndexBuffer[ i * 3 + 2 ];
  7204. m = materialIndexBuffer[ i ];
  7205. f3( scope, a, b, c, m );
  7206. }
  7207. };
  7208. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  7209. var i, a, b, c, d, m;
  7210. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  7211. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  7212. for( i = 0; i < nElements; i ++ ) {
  7213. a = vertexIndexBuffer[ i * 4 ];
  7214. b = vertexIndexBuffer[ i * 4 + 1 ];
  7215. c = vertexIndexBuffer[ i * 4 + 2 ];
  7216. d = vertexIndexBuffer[ i * 4 + 3 ];
  7217. m = materialIndexBuffer[ i ];
  7218. f4( scope, a, b, c, d, m );
  7219. }
  7220. };
  7221. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  7222. var i, a, b, c, m;
  7223. var na, nb, nc;
  7224. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  7225. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  7226. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  7227. for( i = 0; i < nElements; i ++ ) {
  7228. a = vertexIndexBuffer[ i * 3 ];
  7229. b = vertexIndexBuffer[ i * 3 + 1 ];
  7230. c = vertexIndexBuffer[ i * 3 + 2 ];
  7231. na = normalIndexBuffer[ i * 3 ];
  7232. nb = normalIndexBuffer[ i * 3 + 1 ];
  7233. nc = normalIndexBuffer[ i * 3 + 2 ];
  7234. m = materialIndexBuffer[ i ];
  7235. f3n( scope, normals, a, b, c, m, na, nb, nc );
  7236. }
  7237. };
  7238. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  7239. var i, a, b, c, d, m;
  7240. var na, nb, nc, nd;
  7241. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  7242. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  7243. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  7244. for( i = 0; i < nElements; i ++ ) {
  7245. a = vertexIndexBuffer[ i * 4 ];
  7246. b = vertexIndexBuffer[ i * 4 + 1 ];
  7247. c = vertexIndexBuffer[ i * 4 + 2 ];
  7248. d = vertexIndexBuffer[ i * 4 + 3 ];
  7249. na = normalIndexBuffer[ i * 4 ];
  7250. nb = normalIndexBuffer[ i * 4 + 1 ];
  7251. nc = normalIndexBuffer[ i * 4 + 2 ];
  7252. nd = normalIndexBuffer[ i * 4 + 3 ];
  7253. m = materialIndexBuffer[ i ];
  7254. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  7255. }
  7256. };
  7257. function init_triangles_flat( start ) {
  7258. var nElements = md.ntri_flat;
  7259. if ( nElements ) {
  7260. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7261. init_faces3_flat( nElements, start, offsetMaterials );
  7262. }
  7263. };
  7264. function init_triangles_flat_uv( start ) {
  7265. var nElements = md.ntri_flat_uv;
  7266. if ( nElements ) {
  7267. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7268. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7269. init_faces3_flat( nElements, start, offsetMaterials );
  7270. init_uvs3( nElements, offsetUvs );
  7271. }
  7272. };
  7273. function init_triangles_smooth( start ) {
  7274. var nElements = md.ntri_smooth;
  7275. if ( nElements ) {
  7276. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7277. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7278. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  7279. }
  7280. };
  7281. function init_triangles_smooth_uv( start ) {
  7282. var nElements = md.ntri_smooth_uv;
  7283. if ( nElements ) {
  7284. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7285. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7286. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7287. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  7288. init_uvs3( nElements, offsetUvs );
  7289. }
  7290. };
  7291. function init_quads_flat( start ) {
  7292. var nElements = md.nquad_flat;
  7293. if ( nElements ) {
  7294. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7295. init_faces4_flat( nElements, start, offsetMaterials );
  7296. }
  7297. };
  7298. function init_quads_flat_uv( start ) {
  7299. var nElements = md.nquad_flat_uv;
  7300. if ( nElements ) {
  7301. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7302. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7303. init_faces4_flat( nElements, start, offsetMaterials );
  7304. init_uvs4( nElements, offsetUvs );
  7305. }
  7306. };
  7307. function init_quads_smooth( start ) {
  7308. var nElements = md.nquad_smooth;
  7309. if ( nElements ) {
  7310. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7311. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7312. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  7313. }
  7314. };
  7315. function init_quads_smooth_uv( start ) {
  7316. var nElements = md.nquad_smooth_uv;
  7317. if ( nElements ) {
  7318. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7319. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7320. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7321. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  7322. init_uvs4( nElements, offsetUvs );
  7323. }
  7324. };
  7325. };
  7326. function vertex ( scope, x, y, z ) {
  7327. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  7328. };
  7329. function f3 ( scope, a, b, c, mi ) {
  7330. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  7331. };
  7332. function f4 ( scope, a, b, c, d, mi ) {
  7333. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  7334. };
  7335. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  7336. var nax = normals[ na*3 ],
  7337. nay = normals[ na*3 + 1 ],
  7338. naz = normals[ na*3 + 2 ],
  7339. nbx = normals[ nb*3 ],
  7340. nby = normals[ nb*3 + 1 ],
  7341. nbz = normals[ nb*3 + 2 ],
  7342. ncx = normals[ nc*3 ],
  7343. ncy = normals[ nc*3 + 1 ],
  7344. ncz = normals[ nc*3 + 2 ];
  7345. scope.faces.push( new THREE.Face3( a, b, c,
  7346. [new THREE.Vector3( nax, nay, naz ),
  7347. new THREE.Vector3( nbx, nby, nbz ),
  7348. new THREE.Vector3( ncx, ncy, ncz )],
  7349. null,
  7350. mi ) );
  7351. };
  7352. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  7353. var nax = normals[ na*3 ],
  7354. nay = normals[ na*3 + 1 ],
  7355. naz = normals[ na*3 + 2 ],
  7356. nbx = normals[ nb*3 ],
  7357. nby = normals[ nb*3 + 1 ],
  7358. nbz = normals[ nb*3 + 2 ],
  7359. ncx = normals[ nc*3 ],
  7360. ncy = normals[ nc*3 + 1 ],
  7361. ncz = normals[ nc*3 + 2 ],
  7362. ndx = normals[ nd*3 ],
  7363. ndy = normals[ nd*3 + 1 ],
  7364. ndz = normals[ nd*3 + 2 ];
  7365. scope.faces.push( new THREE.Face4( a, b, c, d,
  7366. [new THREE.Vector3( nax, nay, naz ),
  7367. new THREE.Vector3( nbx, nby, nbz ),
  7368. new THREE.Vector3( ncx, ncy, ncz ),
  7369. new THREE.Vector3( ndx, ndy, ndz )],
  7370. null,
  7371. mi ) );
  7372. };
  7373. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  7374. var uv = [];
  7375. uv.push( new THREE.UV( u1, v1 ) );
  7376. uv.push( new THREE.UV( u2, v2 ) );
  7377. uv.push( new THREE.UV( u3, v3 ) );
  7378. where.push( uv );
  7379. };
  7380. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  7381. var uv = [];
  7382. uv.push( new THREE.UV( u1, v1 ) );
  7383. uv.push( new THREE.UV( u2, v2 ) );
  7384. uv.push( new THREE.UV( u3, v3 ) );
  7385. uv.push( new THREE.UV( u4, v4 ) );
  7386. where.push( uv );
  7387. };
  7388. Model.prototype = new THREE.Geometry();
  7389. Model.prototype.constructor = Model;
  7390. callback( new Model( texturePath ) );
  7391. };
  7392. /**
  7393. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  7394. */
  7395. THREE.ColladaLoader = function () {
  7396. var COLLADA = null;
  7397. var scene = null;
  7398. var daeScene;
  7399. var readyCallbackFunc = null;
  7400. var sources = {};
  7401. var images = {};
  7402. var animations = {};
  7403. var controllers = {};
  7404. var geometries = {};
  7405. var materials = {};
  7406. var effects = {};
  7407. var cameras = {};
  7408. var animData;
  7409. var visualScenes;
  7410. var baseUrl;
  7411. var morphs;
  7412. var skins;
  7413. var flip_uv = true;
  7414. var preferredShading = THREE.SmoothShading;
  7415. var options = {
  7416. // Force Geometry to always be centered at the local origin of the
  7417. // containing Mesh.
  7418. centerGeometry: false,
  7419. // Axis conversion is done for geometries, animations, and controllers.
  7420. // If we ever pull cameras or lights out of the COLLADA file, they'll
  7421. // need extra work.
  7422. convertUpAxis: false,
  7423. subdivideFaces: true,
  7424. upAxis: 'Y'
  7425. };
  7426. // TODO: support unit conversion as well
  7427. var colladaUnit = 1.0;
  7428. var colladaUp = 'Y';
  7429. var upConversion = null;
  7430. var TO_RADIANS = Math.PI / 180;
  7431. function load ( url, readyCallback, progressCallback ) {
  7432. var length = 0;
  7433. if ( document.implementation && document.implementation.createDocument ) {
  7434. var req = new XMLHttpRequest();
  7435. if ( req.overrideMimeType ) req.overrideMimeType( "text/xml" );
  7436. req.onreadystatechange = function() {
  7437. if( req.readyState == 4 ) {
  7438. if( req.status == 0 || req.status == 200 ) {
  7439. if ( req.responseXML ) {
  7440. readyCallbackFunc = readyCallback;
  7441. parse( req.responseXML, undefined, url );
  7442. } else {
  7443. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  7444. }
  7445. }
  7446. } else if ( req.readyState == 3 ) {
  7447. if ( progressCallback ) {
  7448. if ( length == 0 ) {
  7449. length = req.getResponseHeader( "Content-Length" );
  7450. }
  7451. progressCallback( { total: length, loaded: req.responseText.length } );
  7452. }
  7453. }
  7454. }
  7455. req.open( "GET", url, true );
  7456. req.send( null );
  7457. } else {
  7458. alert( "Don't know how to parse XML!" );
  7459. }
  7460. };
  7461. function parse( doc, callBack, url ) {
  7462. COLLADA = doc;
  7463. callBack = callBack || readyCallbackFunc;
  7464. if ( url !== undefined ) {
  7465. var parts = url.split( '/' );
  7466. parts.pop();
  7467. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  7468. }
  7469. parseAsset();
  7470. setUpConversion();
  7471. images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
  7472. materials = parseLib( "//dae:library_materials/dae:material", Material, "material") ;
  7473. effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
  7474. geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
  7475. cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
  7476. controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
  7477. animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
  7478. visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
  7479. morphs = [];
  7480. skins = [];
  7481. daeScene = parseScene();
  7482. scene = new THREE.Object3D();
  7483. for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
  7484. scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
  7485. }
  7486. createAnimations();
  7487. var result = {
  7488. scene: scene,
  7489. morphs: morphs,
  7490. skins: skins,
  7491. animations: animData,
  7492. dae: {
  7493. images: images,
  7494. materials: materials,
  7495. cameras: cameras,
  7496. effects: effects,
  7497. geometries: geometries,
  7498. controllers: controllers,
  7499. animations: animations,
  7500. visualScenes: visualScenes,
  7501. scene: daeScene
  7502. }
  7503. };
  7504. if ( callBack ) {
  7505. callBack( result );
  7506. }
  7507. return result;
  7508. };
  7509. function setPreferredShading ( shading ) {
  7510. preferredShading = shading;
  7511. };
  7512. function parseAsset () {
  7513. var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  7514. var element = elements.iterateNext();
  7515. if ( element && element.childNodes ) {
  7516. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  7517. var child = element.childNodes[ i ];
  7518. switch ( child.nodeName ) {
  7519. case 'unit':
  7520. var meter = child.getAttribute( 'meter' );
  7521. if ( meter ) {
  7522. colladaUnit = parseFloat( meter );
  7523. }
  7524. break;
  7525. case 'up_axis':
  7526. colladaUp = child.textContent.charAt(0);
  7527. break;
  7528. }
  7529. }
  7530. }
  7531. };
  7532. function parseLib ( q, classSpec, prefix ) {
  7533. var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
  7534. var lib = {};
  7535. var element = elements.iterateNext();
  7536. var i = 0;
  7537. while ( element ) {
  7538. var daeElement = ( new classSpec() ).parse( element );
  7539. if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
  7540. lib[ daeElement.id ] = daeElement;
  7541. element = elements.iterateNext();
  7542. }
  7543. return lib;
  7544. };
  7545. function parseScene() {
  7546. var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  7547. if ( sceneElement ) {
  7548. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  7549. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  7550. } else {
  7551. return null;
  7552. }
  7553. };
  7554. function createAnimations() {
  7555. animData = [];
  7556. // fill in the keys
  7557. recurseHierarchy( scene );
  7558. };
  7559. function recurseHierarchy( node ) {
  7560. var n = daeScene.getChildById( node.name, true ),
  7561. newData = null;
  7562. if ( n && n.keys ) {
  7563. newData = {
  7564. fps: 60,
  7565. hierarchy: [ {
  7566. node: n,
  7567. keys: n.keys,
  7568. sids: n.sids
  7569. } ],
  7570. node: node,
  7571. name: 'animation_' + node.name,
  7572. length: 0
  7573. };
  7574. animData.push(newData);
  7575. for ( var i = 0, il = n.keys.length; i < il; i++ ) {
  7576. newData.length = Math.max( newData.length, n.keys[i].time );
  7577. }
  7578. } else {
  7579. newData = {
  7580. hierarchy: [ {
  7581. keys: [],
  7582. sids: []
  7583. } ]
  7584. }
  7585. }
  7586. for ( var i = 0, il = node.children.length; i < il; i++ ) {
  7587. var d = recurseHierarchy( node.children[i] );
  7588. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  7589. newData.hierarchy.push( {
  7590. keys: [],
  7591. sids: []
  7592. } );
  7593. }
  7594. }
  7595. return newData;
  7596. };
  7597. function calcAnimationBounds () {
  7598. var start = 1000000;
  7599. var end = -start;
  7600. var frames = 0;
  7601. for ( var id in animations ) {
  7602. var animation = animations[ id ];
  7603. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  7604. var sampler = animation.sampler[ i ];
  7605. sampler.create();
  7606. start = Math.min( start, sampler.startTime );
  7607. end = Math.max( end, sampler.endTime );
  7608. frames = Math.max( frames, sampler.input.length );
  7609. }
  7610. }
  7611. return { start:start, end:end, frames:frames };
  7612. };
  7613. function createMorph ( geometry, ctrl ) {
  7614. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  7615. if ( !morphCtrl || !morphCtrl.morph ) {
  7616. console.log("could not find morph controller!");
  7617. return;
  7618. }
  7619. var morph = morphCtrl.morph;
  7620. for ( var i = 0; i < morph.targets.length; i ++ ) {
  7621. var target_id = morph.targets[ i ];
  7622. var daeGeometry = geometries[ target_id ];
  7623. if ( !daeGeometry.mesh ||
  7624. !daeGeometry.mesh.primitives ||
  7625. !daeGeometry.mesh.primitives.length ) {
  7626. continue;
  7627. }
  7628. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  7629. if ( target.vertices.length === geometry.vertices.length ) {
  7630. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  7631. }
  7632. }
  7633. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  7634. };
  7635. function createSkin ( geometry, ctrl, applyBindShape ) {
  7636. var skinCtrl = controllers[ ctrl.url ];
  7637. if ( !skinCtrl || !skinCtrl.skin ) {
  7638. console.log( "could not find skin controller!" );
  7639. return;
  7640. }
  7641. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  7642. console.log( "could not find the skeleton for the skin!" );
  7643. return;
  7644. }
  7645. var skin = skinCtrl.skin;
  7646. var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
  7647. var hierarchy = [];
  7648. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  7649. var bones = [];
  7650. geometry.skinWeights = [];
  7651. geometry.skinIndices = [];
  7652. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  7653. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  7654. /*
  7655. geometry.animation = {
  7656. name: 'take_001',
  7657. fps: 30,
  7658. length: 2,
  7659. JIT: true,
  7660. hierarchy: hierarchy
  7661. };
  7662. */
  7663. if ( applyBindShape ) {
  7664. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  7665. skin.bindShapeMatrix.multiplyVector3( geometry.vertices[ i ] );
  7666. }
  7667. }
  7668. };
  7669. function setupSkeleton ( node, bones, frame, parent ) {
  7670. node.world = node.world || new THREE.Matrix4();
  7671. node.world.copy( node.matrix );
  7672. if ( node.channels && node.channels.length ) {
  7673. var channel = node.channels[ 0 ];
  7674. var m = channel.sampler.output[ frame ];
  7675. if ( m instanceof THREE.Matrix4 ) {
  7676. node.world.copy( m );
  7677. }
  7678. }
  7679. if ( parent ) {
  7680. node.world.multiply( parent, node.world );
  7681. }
  7682. bones.push( node );
  7683. for ( var i = 0; i < node.nodes.length; i ++ ) {
  7684. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  7685. }
  7686. };
  7687. function setupSkinningMatrices ( bones, skin ) {
  7688. // FIXME: this is dumb...
  7689. for ( var i = 0; i < bones.length; i ++ ) {
  7690. var bone = bones[ i ];
  7691. var found = -1;
  7692. if ( bone.type != 'JOINT' ) continue;
  7693. for ( var j = 0; j < skin.joints.length; j ++ ) {
  7694. if ( bone.sid == skin.joints[ j ] ) {
  7695. found = j;
  7696. break;
  7697. }
  7698. }
  7699. if ( found >= 0 ) {
  7700. var inv = skin.invBindMatrices[ found ];
  7701. bone.invBindMatrix = inv;
  7702. bone.skinningMatrix = new THREE.Matrix4();
  7703. bone.skinningMatrix.multiply(bone.world, inv); // (IBMi * JMi)
  7704. bone.weights = [];
  7705. for ( var j = 0; j < skin.weights.length; j ++ ) {
  7706. for (var k = 0; k < skin.weights[ j ].length; k ++) {
  7707. var w = skin.weights[ j ][ k ];
  7708. if ( w.joint == found ) {
  7709. bone.weights.push( w );
  7710. }
  7711. }
  7712. }
  7713. } else {
  7714. throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
  7715. }
  7716. }
  7717. };
  7718. function applySkin ( geometry, instanceCtrl, frame ) {
  7719. var skinController = controllers[ instanceCtrl.url ];
  7720. frame = frame !== undefined ? frame : 40;
  7721. if ( !skinController || !skinController.skin ) {
  7722. console.log( 'ColladaLoader: Could not find skin controller.' );
  7723. return;
  7724. }
  7725. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  7726. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  7727. return;
  7728. }
  7729. var animationBounds = calcAnimationBounds();
  7730. var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
  7731. daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
  7732. var i, j, w, vidx, weight;
  7733. var v = new THREE.Vector3(), o, s;
  7734. // move vertices to bind shape
  7735. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  7736. skinController.skin.bindShapeMatrix.multiplyVector3( geometry.vertices[i] );
  7737. }
  7738. // process animation, or simply pose the rig if no animation
  7739. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  7740. var bones = [];
  7741. var skinned = [];
  7742. // zero skinned vertices
  7743. for ( i = 0; i < geometry.vertices.length; i++ ) {
  7744. skinned.push( new THREE.Vector3() );
  7745. }
  7746. // process the frame and setup the rig with a fresh
  7747. // transform, possibly from the bone's animation channel(s)
  7748. setupSkeleton( skeleton, bones, frame );
  7749. setupSkinningMatrices( bones, skinController.skin );
  7750. // skin 'm
  7751. for ( i = 0; i < bones.length; i ++ ) {
  7752. if ( bones[ i ].type != 'JOINT' ) continue;
  7753. for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
  7754. w = bones[ i ].weights[ j ];
  7755. vidx = w.index;
  7756. weight = w.weight;
  7757. o = geometry.vertices[vidx];
  7758. s = skinned[vidx];
  7759. v.x = o.x;
  7760. v.y = o.y;
  7761. v.z = o.z;
  7762. bones[i].skinningMatrix.multiplyVector3(v);
  7763. s.x += (v.x * weight);
  7764. s.y += (v.y * weight);
  7765. s.z += (v.z * weight);
  7766. }
  7767. }
  7768. geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
  7769. }
  7770. };
  7771. function createSceneGraph ( node, parent ) {
  7772. var obj = new THREE.Object3D();
  7773. var skinned = false;
  7774. var skinController;
  7775. var morphController;
  7776. var i, j;
  7777. // FIXME: controllers
  7778. for ( i = 0; i < node.controllers.length; i ++ ) {
  7779. var controller = controllers[ node.controllers[ i ].url ];
  7780. switch ( controller.type ) {
  7781. case 'skin':
  7782. if ( geometries[ controller.skin.source ] ) {
  7783. var inst_geom = new InstanceGeometry();
  7784. inst_geom.url = controller.skin.source;
  7785. inst_geom.instance_material = node.controllers[ i ].instance_material;
  7786. node.geometries.push( inst_geom );
  7787. skinned = true;
  7788. skinController = node.controllers[ i ];
  7789. } else if ( controllers[ controller.skin.source ] ) {
  7790. // urgh: controller can be chained
  7791. // handle the most basic case...
  7792. var second = controllers[ controller.skin.source ];
  7793. morphController = second;
  7794. // skinController = node.controllers[i];
  7795. if ( second.morph && geometries[ second.morph.source ] ) {
  7796. var inst_geom = new InstanceGeometry();
  7797. inst_geom.url = second.morph.source;
  7798. inst_geom.instance_material = node.controllers[ i ].instance_material;
  7799. node.geometries.push( inst_geom );
  7800. }
  7801. }
  7802. break;
  7803. case 'morph':
  7804. if ( geometries[ controller.morph.source ] ) {
  7805. var inst_geom = new InstanceGeometry();
  7806. inst_geom.url = controller.morph.source;
  7807. inst_geom.instance_material = node.controllers[ i ].instance_material;
  7808. node.geometries.push( inst_geom );
  7809. morphController = node.controllers[ i ];
  7810. }
  7811. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  7812. default:
  7813. break;
  7814. }
  7815. }
  7816. // FIXME: multi-material mesh?
  7817. // geometries
  7818. for ( i = 0; i < node.geometries.length; i ++ ) {
  7819. var instance_geometry = node.geometries[i];
  7820. var instance_materials = instance_geometry.instance_material;
  7821. var geometry = geometries[instance_geometry.url];
  7822. var used_materials = {};
  7823. var used_materials_array = [];
  7824. var num_materials = 0;
  7825. var first_material;
  7826. if ( geometry ) {
  7827. if ( !geometry.mesh || !geometry.mesh.primitives )
  7828. continue;
  7829. if ( obj.name.length == 0 ) {
  7830. obj.name = geometry.id;
  7831. }
  7832. // collect used fx for this geometry-instance
  7833. if ( instance_materials ) {
  7834. for ( j = 0; j < instance_materials.length; j ++ ) {
  7835. var instance_material = instance_materials[ j ];
  7836. var mat = materials[ instance_material.target ];
  7837. var effect_id = mat.instance_effect.url;
  7838. var shader = effects[ effect_id ].shader;
  7839. shader.material.opacity = !shader.material.opacity ? 1 : shader.material.opacity;
  7840. used_materials[ instance_material.symbol ] = num_materials;
  7841. used_materials_array.push( shader.material )
  7842. first_material = shader.material;
  7843. first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
  7844. num_materials ++;
  7845. }
  7846. }
  7847. var mesh;
  7848. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading } );
  7849. var geom = geometry.mesh.geometry3js;
  7850. if ( num_materials > 1 ) {
  7851. material = new THREE.MeshFaceMaterial();
  7852. geom.materials = used_materials_array;
  7853. for ( j = 0; j < geom.faces.length; j ++ ) {
  7854. var face = geom.faces[ j ];
  7855. face.materialIndex = used_materials[ face.daeMaterial ]
  7856. }
  7857. }
  7858. if ( skinController !== undefined) {
  7859. applySkin( geom, skinController );
  7860. material.morphTargets = true;
  7861. mesh = new THREE.SkinnedMesh( geom, material );
  7862. mesh.skeleton = skinController.skeleton;
  7863. mesh.skinController = controllers[ skinController.url ];
  7864. mesh.skinInstanceController = skinController;
  7865. mesh.name = 'skin_' + skins.length;
  7866. skins.push( mesh );
  7867. } else if ( morphController !== undefined ) {
  7868. createMorph( geom, morphController );
  7869. material.morphTargets = true;
  7870. mesh = new THREE.Mesh( geom, material );
  7871. mesh.name = 'morph_' + morphs.length;
  7872. morphs.push( mesh );
  7873. } else {
  7874. mesh = new THREE.Mesh( geom, material );
  7875. // mesh.geom.name = geometry.id;
  7876. }
  7877. node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
  7878. }
  7879. }
  7880. for ( i = 0; i < node.cameras.length; i ++ ) {
  7881. var instance_camera = node.cameras[i];
  7882. var cparams = cameras[instance_camera.url];
  7883. obj = new THREE.PerspectiveCamera(cparams.fov, cparams.aspect_ratio, cparams.znear, cparams.zfar);
  7884. }
  7885. obj.name = node.id || "";
  7886. obj.matrix = node.matrix;
  7887. var props = node.matrix.decompose();
  7888. obj.position = props[ 0 ];
  7889. obj.quaternion = props[ 1 ];
  7890. obj.useQuaternion = true;
  7891. obj.scale = props[ 2 ];
  7892. if ( options.centerGeometry && obj.geometry ) {
  7893. var delta = THREE.GeometryUtils.center( obj.geometry );
  7894. obj.quaternion.multiplyVector3( delta.multiplySelf( obj.scale ) );
  7895. obj.position.subSelf( delta );
  7896. }
  7897. for ( i = 0; i < node.nodes.length; i ++ ) {
  7898. obj.add( createSceneGraph( node.nodes[i], node ) );
  7899. }
  7900. return obj;
  7901. };
  7902. function getJointId( skin, id ) {
  7903. for ( var i = 0; i < skin.joints.length; i ++ ) {
  7904. if ( skin.joints[ i ] == id ) {
  7905. return i;
  7906. }
  7907. }
  7908. };
  7909. function getLibraryNode( id ) {
  7910. return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  7911. };
  7912. function getChannelsForNode (node ) {
  7913. var channels = [];
  7914. var startTime = 1000000;
  7915. var endTime = -1000000;
  7916. for ( var id in animations ) {
  7917. var animation = animations[id];
  7918. for ( var i = 0; i < animation.channel.length; i ++ ) {
  7919. var channel = animation.channel[i];
  7920. var sampler = animation.sampler[i];
  7921. var id = channel.target.split('/')[0];
  7922. if ( id == node.id ) {
  7923. sampler.create();
  7924. channel.sampler = sampler;
  7925. startTime = Math.min(startTime, sampler.startTime);
  7926. endTime = Math.max(endTime, sampler.endTime);
  7927. channels.push(channel);
  7928. }
  7929. }
  7930. }
  7931. if ( channels.length ) {
  7932. node.startTime = startTime;
  7933. node.endTime = endTime;
  7934. }
  7935. return channels;
  7936. };
  7937. function calcFrameDuration( node ) {
  7938. var minT = 10000000;
  7939. for ( var i = 0; i < node.channels.length; i ++ ) {
  7940. var sampler = node.channels[i].sampler;
  7941. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  7942. var t0 = sampler.input[ j ];
  7943. var t1 = sampler.input[ j + 1 ];
  7944. minT = Math.min( minT, t1 - t0 );
  7945. }
  7946. }
  7947. return minT;
  7948. };
  7949. function calcMatrixAt( node, t ) {
  7950. var animated = {};
  7951. var i, j;
  7952. for ( i = 0; i < node.channels.length; i ++ ) {
  7953. var channel = node.channels[ i ];
  7954. animated[ channel.sid ] = channel;
  7955. }
  7956. var matrix = new THREE.Matrix4();
  7957. for ( i = 0; i < node.transforms.length; i ++ ) {
  7958. var transform = node.transforms[ i ];
  7959. var channel = animated[ transform.sid ];
  7960. if ( channel !== undefined ) {
  7961. var sampler = channel.sampler;
  7962. var value;
  7963. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  7964. if ( sampler.input[ j + 1 ] > t ) {
  7965. value = sampler.output[ j ];
  7966. //console.log(value.flatten)
  7967. break;
  7968. }
  7969. }
  7970. if ( value !== undefined ) {
  7971. if ( value instanceof THREE.Matrix4 ) {
  7972. matrix = matrix.multiply( matrix, value );
  7973. } else {
  7974. // FIXME: handle other types
  7975. matrix = matrix.multiply( matrix, transform.matrix );
  7976. }
  7977. } else {
  7978. matrix = matrix.multiply( matrix, transform.matrix );
  7979. }
  7980. } else {
  7981. matrix = matrix.multiply( matrix, transform.matrix );
  7982. }
  7983. }
  7984. return matrix;
  7985. };
  7986. function bakeAnimations ( node ) {
  7987. if ( node.channels && node.channels.length ) {
  7988. var keys = [],
  7989. sids = [];
  7990. for ( var i = 0, il = node.channels.length; i < il; i++ ) {
  7991. var channel = node.channels[i],
  7992. fullSid = channel.fullSid,
  7993. sampler = channel.sampler,
  7994. input = sampler.input,
  7995. transform = node.getTransformBySid( channel.sid ),
  7996. member;
  7997. if ( channel.arrIndices ) {
  7998. member = [];
  7999. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j++ ) {
  8000. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  8001. }
  8002. } else {
  8003. member = getConvertedMember( channel.member );
  8004. }
  8005. if ( transform ) {
  8006. if ( sids.indexOf( fullSid ) === -1 ) {
  8007. sids.push( fullSid );
  8008. }
  8009. for ( var j = 0, jl = input.length; j < jl; j++ ) {
  8010. var time = input[j],
  8011. data = sampler.getData( transform.type, j ),
  8012. key = findKey( keys, time );
  8013. if ( !key ) {
  8014. key = new Key( time );
  8015. var timeNdx = findTimeNdx( keys, time );
  8016. keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
  8017. }
  8018. key.addTarget( fullSid, transform, member, data );
  8019. }
  8020. } else {
  8021. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  8022. }
  8023. }
  8024. // post process
  8025. for ( var i = 0; i < sids.length; i++ ) {
  8026. var sid = sids[ i ];
  8027. for ( var j = 0; j < keys.length; j++ ) {
  8028. var key = keys[ j ];
  8029. if ( !key.hasTarget( sid ) ) {
  8030. interpolateKeys( keys, key, j, sid );
  8031. }
  8032. }
  8033. }
  8034. node.keys = keys;
  8035. node.sids = sids;
  8036. }
  8037. };
  8038. function findKey ( keys, time) {
  8039. var retVal = null;
  8040. for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
  8041. var key = keys[i];
  8042. if ( key.time === time ) {
  8043. retVal = key;
  8044. } else if ( key.time > time ) {
  8045. break;
  8046. }
  8047. }
  8048. return retVal;
  8049. };
  8050. function findTimeNdx ( keys, time) {
  8051. var ndx = -1;
  8052. for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
  8053. var key = keys[i];
  8054. if ( key.time >= time ) {
  8055. ndx = i;
  8056. }
  8057. }
  8058. return ndx;
  8059. };
  8060. function interpolateKeys ( keys, key, ndx, fullSid ) {
  8061. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
  8062. nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
  8063. if ( prevKey && nextKey ) {
  8064. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  8065. prevTarget = prevKey.getTarget( fullSid ),
  8066. nextData = nextKey.getTarget( fullSid ).data,
  8067. prevData = prevTarget.data,
  8068. data;
  8069. if ( prevTarget.type === 'matrix' ) {
  8070. data = prevData;
  8071. } else if ( prevData.length ) {
  8072. data = [];
  8073. for ( var i = 0; i < prevData.length; ++i ) {
  8074. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  8075. }
  8076. } else {
  8077. data = prevData + ( nextData - prevData ) * scale;
  8078. }
  8079. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  8080. }
  8081. };
  8082. // Get next key with given sid
  8083. function getNextKeyWith( keys, fullSid, ndx ) {
  8084. for ( ; ndx < keys.length; ndx++ ) {
  8085. var key = keys[ ndx ];
  8086. if ( key.hasTarget( fullSid ) ) {
  8087. return key;
  8088. }
  8089. }
  8090. return null;
  8091. };
  8092. // Get previous key with given sid
  8093. function getPrevKeyWith( keys, fullSid, ndx ) {
  8094. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  8095. for ( ; ndx >= 0; ndx-- ) {
  8096. var key = keys[ ndx ];
  8097. if ( key.hasTarget( fullSid ) ) {
  8098. return key;
  8099. }
  8100. }
  8101. return null;
  8102. };
  8103. function _Image() {
  8104. this.id = "";
  8105. this.init_from = "";
  8106. };
  8107. _Image.prototype.parse = function(element) {
  8108. this.id = element.getAttribute('id');
  8109. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8110. var child = element.childNodes[ i ];
  8111. if ( child.nodeName == 'init_from' ) {
  8112. this.init_from = child.textContent;
  8113. }
  8114. }
  8115. return this;
  8116. };
  8117. function Controller() {
  8118. this.id = "";
  8119. this.name = "";
  8120. this.type = "";
  8121. this.skin = null;
  8122. this.morph = null;
  8123. };
  8124. Controller.prototype.parse = function( element ) {
  8125. this.id = element.getAttribute('id');
  8126. this.name = element.getAttribute('name');
  8127. this.type = "none";
  8128. for ( var i = 0; i < element.childNodes.length; i++ ) {
  8129. var child = element.childNodes[ i ];
  8130. switch ( child.nodeName ) {
  8131. case 'skin':
  8132. this.skin = (new Skin()).parse(child);
  8133. this.type = child.nodeName;
  8134. break;
  8135. case 'morph':
  8136. this.morph = (new Morph()).parse(child);
  8137. this.type = child.nodeName;
  8138. break;
  8139. default:
  8140. break;
  8141. }
  8142. }
  8143. return this;
  8144. };
  8145. function Morph() {
  8146. this.method = null;
  8147. this.source = null;
  8148. this.targets = null;
  8149. this.weights = null;
  8150. };
  8151. Morph.prototype.parse = function( element ) {
  8152. var sources = {};
  8153. var inputs = [];
  8154. var i;
  8155. this.method = element.getAttribute( 'method' );
  8156. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  8157. for ( i = 0; i < element.childNodes.length; i ++ ) {
  8158. var child = element.childNodes[ i ];
  8159. if ( child.nodeType != 1 ) continue;
  8160. switch ( child.nodeName ) {
  8161. case 'source':
  8162. var source = ( new Source() ).parse( child );
  8163. sources[ source.id ] = source;
  8164. break;
  8165. case 'targets':
  8166. inputs = this.parseInputs( child );
  8167. break;
  8168. default:
  8169. console.log( child.nodeName );
  8170. break;
  8171. }
  8172. }
  8173. for ( i = 0; i < inputs.length; i ++ ) {
  8174. var input = inputs[ i ];
  8175. var source = sources[ input.source ];
  8176. switch ( input.semantic ) {
  8177. case 'MORPH_TARGET':
  8178. this.targets = source.read();
  8179. break;
  8180. case 'MORPH_WEIGHT':
  8181. this.weights = source.read();
  8182. break;
  8183. default:
  8184. break;
  8185. }
  8186. }
  8187. return this;
  8188. };
  8189. Morph.prototype.parseInputs = function(element) {
  8190. var inputs = [];
  8191. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8192. var child = element.childNodes[i];
  8193. if ( child.nodeType != 1) continue;
  8194. switch ( child.nodeName ) {
  8195. case 'input':
  8196. inputs.push( (new Input()).parse(child) );
  8197. break;
  8198. default:
  8199. break;
  8200. }
  8201. }
  8202. return inputs;
  8203. };
  8204. function Skin() {
  8205. this.source = "";
  8206. this.bindShapeMatrix = null;
  8207. this.invBindMatrices = [];
  8208. this.joints = [];
  8209. this.weights = [];
  8210. };
  8211. Skin.prototype.parse = function( element ) {
  8212. var sources = {};
  8213. var joints, weights;
  8214. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  8215. this.invBindMatrices = [];
  8216. this.joints = [];
  8217. this.weights = [];
  8218. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8219. var child = element.childNodes[i];
  8220. if ( child.nodeType != 1 ) continue;
  8221. switch ( child.nodeName ) {
  8222. case 'bind_shape_matrix':
  8223. var f = _floats(child.textContent);
  8224. this.bindShapeMatrix = getConvertedMat4( f );
  8225. break;
  8226. case 'source':
  8227. var src = new Source().parse(child);
  8228. sources[ src.id ] = src;
  8229. break;
  8230. case 'joints':
  8231. joints = child;
  8232. break;
  8233. case 'vertex_weights':
  8234. weights = child;
  8235. break;
  8236. default:
  8237. console.log( child.nodeName );
  8238. break;
  8239. }
  8240. }
  8241. this.parseJoints( joints, sources );
  8242. this.parseWeights( weights, sources );
  8243. return this;
  8244. };
  8245. Skin.prototype.parseJoints = function ( element, sources ) {
  8246. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8247. var child = element.childNodes[ i ];
  8248. if ( child.nodeType != 1 ) continue;
  8249. switch ( child.nodeName ) {
  8250. case 'input':
  8251. var input = ( new Input() ).parse( child );
  8252. var source = sources[ input.source ];
  8253. if ( input.semantic == 'JOINT' ) {
  8254. this.joints = source.read();
  8255. } else if ( input.semantic == 'INV_BIND_MATRIX' ) {
  8256. this.invBindMatrices = source.read();
  8257. }
  8258. break;
  8259. default:
  8260. break;
  8261. }
  8262. }
  8263. };
  8264. Skin.prototype.parseWeights = function ( element, sources ) {
  8265. var v, vcount, inputs = [];
  8266. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8267. var child = element.childNodes[ i ];
  8268. if ( child.nodeType != 1 ) continue;
  8269. switch ( child.nodeName ) {
  8270. case 'input':
  8271. inputs.push( ( new Input() ).parse( child ) );
  8272. break;
  8273. case 'v':
  8274. v = _ints( child.textContent );
  8275. break;
  8276. case 'vcount':
  8277. vcount = _ints( child.textContent );
  8278. break;
  8279. default:
  8280. break;
  8281. }
  8282. }
  8283. var index = 0;
  8284. for ( var i = 0; i < vcount.length; i ++ ) {
  8285. var numBones = vcount[i];
  8286. var vertex_weights = [];
  8287. for ( var j = 0; j < numBones; j++ ) {
  8288. var influence = {};
  8289. for ( var k = 0; k < inputs.length; k ++ ) {
  8290. var input = inputs[ k ];
  8291. var value = v[ index + input.offset ];
  8292. switch ( input.semantic ) {
  8293. case 'JOINT':
  8294. influence.joint = value;//this.joints[value];
  8295. break;
  8296. case 'WEIGHT':
  8297. influence.weight = sources[ input.source ].data[ value ];
  8298. break;
  8299. default:
  8300. break;
  8301. }
  8302. }
  8303. vertex_weights.push( influence );
  8304. index += inputs.length;
  8305. }
  8306. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  8307. vertex_weights[ j ].index = i;
  8308. }
  8309. this.weights.push( vertex_weights );
  8310. }
  8311. };
  8312. function VisualScene () {
  8313. this.id = "";
  8314. this.name = "";
  8315. this.nodes = [];
  8316. this.scene = new THREE.Object3D();
  8317. };
  8318. VisualScene.prototype.getChildById = function( id, recursive ) {
  8319. for ( var i = 0; i < this.nodes.length; i ++ ) {
  8320. var node = this.nodes[ i ].getChildById( id, recursive );
  8321. if ( node ) {
  8322. return node;
  8323. }
  8324. }
  8325. return null;
  8326. };
  8327. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  8328. for ( var i = 0; i < this.nodes.length; i ++ ) {
  8329. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  8330. if ( node ) {
  8331. return node;
  8332. }
  8333. }
  8334. return null;
  8335. };
  8336. VisualScene.prototype.parse = function( element ) {
  8337. this.id = element.getAttribute( 'id' );
  8338. this.name = element.getAttribute( 'name' );
  8339. this.nodes = [];
  8340. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8341. var child = element.childNodes[ i ];
  8342. if ( child.nodeType != 1 ) continue;
  8343. switch ( child.nodeName ) {
  8344. case 'node':
  8345. this.nodes.push( ( new Node() ).parse( child ) );
  8346. break;
  8347. default:
  8348. break;
  8349. }
  8350. }
  8351. return this;
  8352. };
  8353. function Node() {
  8354. this.id = "";
  8355. this.name = "";
  8356. this.sid = "";
  8357. this.nodes = [];
  8358. this.controllers = [];
  8359. this.transforms = [];
  8360. this.geometries = [];
  8361. this.channels = [];
  8362. this.matrix = new THREE.Matrix4();
  8363. };
  8364. Node.prototype.getChannelForTransform = function( transformSid ) {
  8365. for ( var i = 0; i < this.channels.length; i ++ ) {
  8366. var channel = this.channels[i];
  8367. var parts = channel.target.split('/');
  8368. var id = parts.shift();
  8369. var sid = parts.shift();
  8370. var dotSyntax = (sid.indexOf(".") >= 0);
  8371. var arrSyntax = (sid.indexOf("(") >= 0);
  8372. var arrIndices;
  8373. var member;
  8374. if ( dotSyntax ) {
  8375. parts = sid.split(".");
  8376. sid = parts.shift();
  8377. member = parts.shift();
  8378. } else if ( arrSyntax ) {
  8379. arrIndices = sid.split("(");
  8380. sid = arrIndices.shift();
  8381. for ( var j = 0; j < arrIndices.length; j ++ ) {
  8382. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  8383. }
  8384. }
  8385. if ( sid == transformSid ) {
  8386. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  8387. return channel;
  8388. }
  8389. }
  8390. return null;
  8391. };
  8392. Node.prototype.getChildById = function ( id, recursive ) {
  8393. if ( this.id == id ) {
  8394. return this;
  8395. }
  8396. if ( recursive ) {
  8397. for ( var i = 0; i < this.nodes.length; i ++ ) {
  8398. var n = this.nodes[ i ].getChildById( id, recursive );
  8399. if ( n ) {
  8400. return n;
  8401. }
  8402. }
  8403. }
  8404. return null;
  8405. };
  8406. Node.prototype.getChildBySid = function ( sid, recursive ) {
  8407. if ( this.sid == sid ) {
  8408. return this;
  8409. }
  8410. if ( recursive ) {
  8411. for ( var i = 0; i < this.nodes.length; i ++ ) {
  8412. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  8413. if ( n ) {
  8414. return n;
  8415. }
  8416. }
  8417. }
  8418. return null;
  8419. };
  8420. Node.prototype.getTransformBySid = function ( sid ) {
  8421. for ( var i = 0; i < this.transforms.length; i ++ ) {
  8422. if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
  8423. }
  8424. return null;
  8425. };
  8426. Node.prototype.parse = function( element ) {
  8427. var url;
  8428. this.id = element.getAttribute('id');
  8429. this.sid = element.getAttribute('sid');
  8430. this.name = element.getAttribute('name');
  8431. this.type = element.getAttribute('type');
  8432. this.type = this.type == 'JOINT' ? this.type : 'NODE';
  8433. this.nodes = [];
  8434. this.transforms = [];
  8435. this.geometries = [];
  8436. this.cameras = [];
  8437. this.controllers = [];
  8438. this.matrix = new THREE.Matrix4();
  8439. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8440. var child = element.childNodes[ i ];
  8441. if ( child.nodeType != 1 ) continue;
  8442. switch ( child.nodeName ) {
  8443. case 'node':
  8444. this.nodes.push( ( new Node() ).parse( child ) );
  8445. break;
  8446. case 'instance_camera':
  8447. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  8448. break;
  8449. case 'instance_controller':
  8450. this.controllers.push( ( new InstanceController() ).parse( child ) );
  8451. break;
  8452. case 'instance_geometry':
  8453. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  8454. break;
  8455. case 'instance_light':
  8456. break;
  8457. case 'instance_node':
  8458. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  8459. var iNode = getLibraryNode( url );
  8460. if ( iNode ) {
  8461. this.nodes.push( ( new Node() ).parse( iNode )) ;
  8462. }
  8463. break;
  8464. case 'rotate':
  8465. case 'translate':
  8466. case 'scale':
  8467. case 'matrix':
  8468. case 'lookat':
  8469. case 'skew':
  8470. this.transforms.push( ( new Transform() ).parse( child ) );
  8471. break;
  8472. case 'extra':
  8473. break;
  8474. default:
  8475. console.log( child.nodeName );
  8476. break;
  8477. }
  8478. }
  8479. this.channels = getChannelsForNode( this );
  8480. bakeAnimations( this );
  8481. this.updateMatrix();
  8482. return this;
  8483. };
  8484. Node.prototype.updateMatrix = function () {
  8485. this.matrix.identity();
  8486. for ( var i = 0; i < this.transforms.length; i ++ ) {
  8487. this.transforms[ i ].apply( this.matrix );
  8488. }
  8489. };
  8490. function Transform () {
  8491. this.sid = "";
  8492. this.type = "";
  8493. this.data = [];
  8494. this.obj = null;
  8495. };
  8496. Transform.prototype.parse = function ( element ) {
  8497. this.sid = element.getAttribute( 'sid' );
  8498. this.type = element.nodeName;
  8499. this.data = _floats( element.textContent );
  8500. this.convert();
  8501. return this;
  8502. };
  8503. Transform.prototype.convert = function () {
  8504. switch ( this.type ) {
  8505. case 'matrix':
  8506. this.obj = getConvertedMat4( this.data );
  8507. break;
  8508. case 'rotate':
  8509. this.angle = this.data[3] * TO_RADIANS;
  8510. case 'translate':
  8511. fixCoords( this.data, -1 );
  8512. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  8513. break;
  8514. case 'scale':
  8515. fixCoords( this.data, 1 );
  8516. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  8517. break;
  8518. default:
  8519. console.log( 'Can not convert Transform of type ' + this.type );
  8520. break;
  8521. }
  8522. };
  8523. Transform.prototype.apply = function ( matrix ) {
  8524. switch ( this.type ) {
  8525. case 'matrix':
  8526. matrix.multiplySelf( this.obj );
  8527. break;
  8528. case 'translate':
  8529. matrix.translate( this.obj );
  8530. break;
  8531. case 'rotate':
  8532. matrix.rotateByAxis( this.obj, this.angle );
  8533. break;
  8534. case 'scale':
  8535. matrix.scale( this.obj );
  8536. break;
  8537. }
  8538. };
  8539. Transform.prototype.update = function ( data, member ) {
  8540. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  8541. switch ( this.type ) {
  8542. case 'matrix':
  8543. if ( ! member ) {
  8544. this.obj.copy( data );
  8545. } else if ( member.length === 1 ) {
  8546. switch ( member[ 0 ] ) {
  8547. case 0:
  8548. this.obj.n11 = data[ 0 ];
  8549. this.obj.n21 = data[ 1 ];
  8550. this.obj.n31 = data[ 2 ];
  8551. this.obj.n41 = data[ 3 ];
  8552. break;
  8553. case 1:
  8554. this.obj.n12 = data[ 0 ];
  8555. this.obj.n22 = data[ 1 ];
  8556. this.obj.n32 = data[ 2 ];
  8557. this.obj.n42 = data[ 3 ];
  8558. break;
  8559. case 2:
  8560. this.obj.n13 = data[ 0 ];
  8561. this.obj.n23 = data[ 1 ];
  8562. this.obj.n33 = data[ 2 ];
  8563. this.obj.n43 = data[ 3 ];
  8564. break;
  8565. case 3:
  8566. this.obj.n14 = data[ 0 ];
  8567. this.obj.n24 = data[ 1 ];
  8568. this.obj.n34 = data[ 2 ];
  8569. this.obj.n44 = data[ 3 ];
  8570. break;
  8571. }
  8572. } else if ( member.length === 2 ) {
  8573. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  8574. this.obj[ propName ] = data;
  8575. } else {
  8576. console.log('Incorrect addressing of matrix in transform.');
  8577. }
  8578. break;
  8579. case 'translate':
  8580. case 'scale':
  8581. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  8582. member = members[ member[ 0 ] ];
  8583. }
  8584. switch ( member ) {
  8585. case 'X':
  8586. this.obj.x = data;
  8587. break;
  8588. case 'Y':
  8589. this.obj.y = data;
  8590. break;
  8591. case 'Z':
  8592. this.obj.z = data;
  8593. break;
  8594. default:
  8595. this.obj.x = data[ 0 ];
  8596. this.obj.y = data[ 1 ];
  8597. this.obj.z = data[ 2 ];
  8598. break;
  8599. }
  8600. break;
  8601. case 'rotate':
  8602. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  8603. member = members[ member[ 0 ] ];
  8604. }
  8605. switch ( member ) {
  8606. case 'X':
  8607. this.obj.x = data;
  8608. break;
  8609. case 'Y':
  8610. this.obj.y = data;
  8611. break;
  8612. case 'Z':
  8613. this.obj.z = data;
  8614. break;
  8615. case 'ANGLE':
  8616. this.angle = data * TO_RADIANS;
  8617. break;
  8618. default:
  8619. this.obj.x = data[ 0 ];
  8620. this.obj.y = data[ 1 ];
  8621. this.obj.z = data[ 2 ];
  8622. this.angle = data[ 3 ] * TO_RADIANS;
  8623. break;
  8624. }
  8625. break;
  8626. }
  8627. };
  8628. function InstanceController() {
  8629. this.url = "";
  8630. this.skeleton = [];
  8631. this.instance_material = [];
  8632. };
  8633. InstanceController.prototype.parse = function ( element ) {
  8634. this.url = element.getAttribute('url').replace(/^#/, '');
  8635. this.skeleton = [];
  8636. this.instance_material = [];
  8637. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8638. var child = element.childNodes[i];
  8639. if (child.nodeType != 1) continue;
  8640. switch ( child.nodeName ) {
  8641. case 'skeleton':
  8642. this.skeleton.push( child.textContent.replace(/^#/, '') );
  8643. break;
  8644. case 'bind_material':
  8645. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  8646. if ( instances ) {
  8647. var instance = instances.iterateNext();
  8648. while ( instance ) {
  8649. this.instance_material.push((new InstanceMaterial()).parse(instance));
  8650. instance = instances.iterateNext();
  8651. }
  8652. }
  8653. break;
  8654. case 'extra':
  8655. break;
  8656. default:
  8657. break;
  8658. }
  8659. }
  8660. return this;
  8661. };
  8662. function InstanceMaterial () {
  8663. this.symbol = "";
  8664. this.target = "";
  8665. };
  8666. InstanceMaterial.prototype.parse = function ( element ) {
  8667. this.symbol = element.getAttribute('symbol');
  8668. this.target = element.getAttribute('target').replace(/^#/, '');
  8669. return this;
  8670. };
  8671. function InstanceGeometry() {
  8672. this.url = "";
  8673. this.instance_material = [];
  8674. };
  8675. InstanceGeometry.prototype.parse = function ( element ) {
  8676. this.url = element.getAttribute('url').replace(/^#/, '');
  8677. this.instance_material = [];
  8678. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8679. var child = element.childNodes[i];
  8680. if ( child.nodeType != 1 ) continue;
  8681. if ( child.nodeName == 'bind_material' ) {
  8682. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  8683. if ( instances ) {
  8684. var instance = instances.iterateNext();
  8685. while ( instance ) {
  8686. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  8687. instance = instances.iterateNext();
  8688. }
  8689. }
  8690. break;
  8691. }
  8692. }
  8693. return this;
  8694. };
  8695. function Geometry() {
  8696. this.id = "";
  8697. this.mesh = null;
  8698. };
  8699. Geometry.prototype.parse = function ( element ) {
  8700. this.id = element.getAttribute('id');
  8701. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8702. var child = element.childNodes[i];
  8703. switch ( child.nodeName ) {
  8704. case 'mesh':
  8705. this.mesh = (new Mesh(this)).parse(child);
  8706. break;
  8707. case 'extra':
  8708. // console.log( child );
  8709. break;
  8710. default:
  8711. break;
  8712. }
  8713. }
  8714. return this;
  8715. };
  8716. function Mesh( geometry ) {
  8717. this.geometry = geometry.id;
  8718. this.primitives = [];
  8719. this.vertices = null;
  8720. this.geometry3js = null;
  8721. };
  8722. Mesh.prototype.parse = function( element ) {
  8723. this.primitives = [];
  8724. var i, j;
  8725. for ( i = 0; i < element.childNodes.length; i ++ ) {
  8726. var child = element.childNodes[ i ];
  8727. switch ( child.nodeName ) {
  8728. case 'source':
  8729. _source( child );
  8730. break;
  8731. case 'vertices':
  8732. this.vertices = ( new Vertices() ).parse( child );
  8733. break;
  8734. case 'triangles':
  8735. this.primitives.push( ( new Triangles().parse( child ) ) );
  8736. break;
  8737. case 'polygons':
  8738. this.primitives.push( ( new Polygons().parse( child ) ) );
  8739. break;
  8740. case 'polylist':
  8741. this.primitives.push( ( new Polylist().parse( child ) ) );
  8742. break;
  8743. default:
  8744. break;
  8745. }
  8746. }
  8747. this.geometry3js = new THREE.Geometry();
  8748. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  8749. for ( i = 0; i < vertexData.length; i += 3 ) {
  8750. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  8751. }
  8752. for ( i = 0; i < this.primitives.length; i ++ ) {
  8753. var primitive = this.primitives[ i ];
  8754. primitive.setVertices( this.vertices );
  8755. this.handlePrimitive( primitive, this.geometry3js );
  8756. }
  8757. this.geometry3js.computeCentroids();
  8758. this.geometry3js.computeFaceNormals();
  8759. if ( this.geometry3js.calcNormals ) {
  8760. this.geometry3js.computeVertexNormals();
  8761. delete this.geometry3js.calcNormals;
  8762. }
  8763. this.geometry3js.computeBoundingBox();
  8764. return this;
  8765. };
  8766. Mesh.prototype.handlePrimitive = function( primitive, geom ) {
  8767. var j, k, pList = primitive.p, inputs = primitive.inputs;
  8768. var input, index, idx32;
  8769. var source, numParams;
  8770. var vcIndex = 0, vcount = 3, maxOffset = 0;
  8771. var texture_sets = [];
  8772. for ( j = 0; j < inputs.length; j ++ ) {
  8773. input = inputs[ j ];
  8774. var offset = input.offset + 1;
  8775. maxOffset = (maxOffset < offset)? offset : maxOffset;
  8776. switch ( input.semantic ) {
  8777. case 'TEXCOORD':
  8778. texture_sets.push( input.set );
  8779. break;
  8780. }
  8781. }
  8782. for ( var pCount = 0; pCount < pList.length; ++pCount ) {
  8783. var p = pList[pCount], i = 0;
  8784. while ( i < p.length ) {
  8785. var vs = [];
  8786. var ns = [];
  8787. var ts = {};
  8788. var cs = [];
  8789. if ( primitive.vcount ) {
  8790. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  8791. } else {
  8792. vcount = p.length / maxOffset;
  8793. }
  8794. for ( j = 0; j < vcount; j ++ ) {
  8795. for ( k = 0; k < inputs.length; k ++ ) {
  8796. input = inputs[ k ];
  8797. source = sources[ input.source ];
  8798. index = p[ i + ( j * maxOffset ) + input.offset ];
  8799. numParams = source.accessor.params.length;
  8800. idx32 = index * numParams;
  8801. switch ( input.semantic ) {
  8802. case 'VERTEX':
  8803. vs.push( index );
  8804. break;
  8805. case 'NORMAL':
  8806. ns.push( getConvertedVec3( source.data, idx32 ) );
  8807. break;
  8808. case 'TEXCOORD':
  8809. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  8810. // invert the V
  8811. ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  8812. break;
  8813. case 'COLOR':
  8814. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  8815. break;
  8816. default:
  8817. break;
  8818. }
  8819. }
  8820. }
  8821. var face = null, faces = [], uv, uvArr;
  8822. if ( ns.length == 0 ) {
  8823. // check the vertices source
  8824. input = this.vertices.input.NORMAL;
  8825. if ( input ) {
  8826. source = sources[ input.source ];
  8827. numParams = source.accessor.params.length;
  8828. for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
  8829. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  8830. }
  8831. }
  8832. else {
  8833. geom.calcNormals = true;
  8834. }
  8835. }
  8836. if ( vcount === 3 ) {
  8837. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  8838. } else if ( vcount === 4 ) {
  8839. faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
  8840. } else if ( vcount > 4 && options.subdivideFaces ) {
  8841. var clr = cs.length ? cs : new THREE.Color(),
  8842. vec1, vec2, vec3, v1, v2, norm;
  8843. // subdivide into multiple Face3s
  8844. for ( k = 1; k < vcount-1; ) {
  8845. // FIXME: normals don't seem to be quite right
  8846. faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
  8847. }
  8848. }
  8849. if ( faces.length ) {
  8850. for (var ndx = 0, len = faces.length; ndx < len; ndx++) {
  8851. face = faces[ndx];
  8852. face.daeMaterial = primitive.material;
  8853. geom.faces.push( face );
  8854. for ( k = 0; k < texture_sets.length; k++ ) {
  8855. uv = ts[ texture_sets[k] ];
  8856. if ( vcount > 4 ) {
  8857. // Grab the right UVs for the vertices in this face
  8858. uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
  8859. } else if ( vcount === 4 ) {
  8860. uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
  8861. } else {
  8862. uvArr = [ uv[0], uv[1], uv[2] ];
  8863. }
  8864. if ( !geom.faceVertexUvs[k] ) {
  8865. geom.faceVertexUvs[k] = [];
  8866. }
  8867. geom.faceVertexUvs[k].push( uvArr );
  8868. }
  8869. }
  8870. } else {
  8871. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  8872. }
  8873. i += maxOffset * vcount;
  8874. }
  8875. }
  8876. };
  8877. function Polygons () {
  8878. this.material = "";
  8879. this.count = 0;
  8880. this.inputs = [];
  8881. this.vcount = null;
  8882. this.p = [];
  8883. this.geometry = new THREE.Geometry();
  8884. };
  8885. Polygons.prototype.setVertices = function ( vertices ) {
  8886. for ( var i = 0; i < this.inputs.length; i ++ ) {
  8887. if ( this.inputs[ i ].source == vertices.id ) {
  8888. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  8889. }
  8890. }
  8891. };
  8892. Polygons.prototype.parse = function ( element ) {
  8893. this.material = element.getAttribute( 'material' );
  8894. this.count = _attr_as_int( element, 'count', 0 );
  8895. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8896. var child = element.childNodes[ i ];
  8897. switch ( child.nodeName ) {
  8898. case 'input':
  8899. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  8900. break;
  8901. case 'vcount':
  8902. this.vcount = _ints( child.textContent );
  8903. break;
  8904. case 'p':
  8905. this.p.push( _ints( child.textContent ) );
  8906. break;
  8907. case 'ph':
  8908. console.warn( 'polygon holes not yet supported!' );
  8909. break;
  8910. default:
  8911. break;
  8912. }
  8913. }
  8914. return this;
  8915. };
  8916. function Polylist () {
  8917. Polygons.call( this );
  8918. this.vcount = [];
  8919. };
  8920. Polylist.prototype = new Polygons();
  8921. Polylist.prototype.constructor = Polylist;
  8922. function Triangles () {
  8923. Polygons.call( this );
  8924. this.vcount = 3;
  8925. };
  8926. Triangles.prototype = new Polygons();
  8927. Triangles.prototype.constructor = Triangles;
  8928. function Accessor() {
  8929. this.source = "";
  8930. this.count = 0;
  8931. this.stride = 0;
  8932. this.params = [];
  8933. };
  8934. Accessor.prototype.parse = function ( element ) {
  8935. this.params = [];
  8936. this.source = element.getAttribute( 'source' );
  8937. this.count = _attr_as_int( element, 'count', 0 );
  8938. this.stride = _attr_as_int( element, 'stride', 0 );
  8939. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8940. var child = element.childNodes[ i ];
  8941. if ( child.nodeName == 'param' ) {
  8942. var param = {};
  8943. param[ 'name' ] = child.getAttribute( 'name' );
  8944. param[ 'type' ] = child.getAttribute( 'type' );
  8945. this.params.push( param );
  8946. }
  8947. }
  8948. return this;
  8949. };
  8950. function Vertices() {
  8951. this.input = {};
  8952. };
  8953. Vertices.prototype.parse = function ( element ) {
  8954. this.id = element.getAttribute('id');
  8955. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8956. if ( element.childNodes[i].nodeName == 'input' ) {
  8957. var input = ( new Input() ).parse( element.childNodes[ i ] );
  8958. this.input[ input.semantic ] = input;
  8959. }
  8960. }
  8961. return this;
  8962. };
  8963. function Input () {
  8964. this.semantic = "";
  8965. this.offset = 0;
  8966. this.source = "";
  8967. this.set = 0;
  8968. };
  8969. Input.prototype.parse = function ( element ) {
  8970. this.semantic = element.getAttribute('semantic');
  8971. this.source = element.getAttribute('source').replace(/^#/, '');
  8972. this.set = _attr_as_int(element, 'set', -1);
  8973. this.offset = _attr_as_int(element, 'offset', 0);
  8974. if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
  8975. this.set = 0;
  8976. }
  8977. return this;
  8978. };
  8979. function Source ( id ) {
  8980. this.id = id;
  8981. this.type = null;
  8982. };
  8983. Source.prototype.parse = function ( element ) {
  8984. this.id = element.getAttribute( 'id' );
  8985. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8986. var child = element.childNodes[i];
  8987. switch ( child.nodeName ) {
  8988. case 'bool_array':
  8989. this.data = _bools( child.textContent );
  8990. this.type = child.nodeName;
  8991. break;
  8992. case 'float_array':
  8993. this.data = _floats( child.textContent );
  8994. this.type = child.nodeName;
  8995. break;
  8996. case 'int_array':
  8997. this.data = _ints( child.textContent );
  8998. this.type = child.nodeName;
  8999. break;
  9000. case 'IDREF_array':
  9001. case 'Name_array':
  9002. this.data = _strings( child.textContent );
  9003. this.type = child.nodeName;
  9004. break;
  9005. case 'technique_common':
  9006. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  9007. if ( child.childNodes[ j ].nodeName == 'accessor' ) {
  9008. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  9009. break;
  9010. }
  9011. }
  9012. break;
  9013. default:
  9014. // console.log(child.nodeName);
  9015. break;
  9016. }
  9017. }
  9018. return this;
  9019. };
  9020. Source.prototype.read = function () {
  9021. var result = [];
  9022. //for (var i = 0; i < this.accessor.params.length; i++) {
  9023. var param = this.accessor.params[ 0 ];
  9024. //console.log(param.name + " " + param.type);
  9025. switch ( param.type ) {
  9026. case 'IDREF':
  9027. case 'Name': case 'name':
  9028. case 'float':
  9029. return this.data;
  9030. case 'float4x4':
  9031. for ( var j = 0; j < this.data.length; j += 16 ) {
  9032. var s = this.data.slice( j, j + 16 );
  9033. var m = getConvertedMat4( s );
  9034. result.push( m );
  9035. }
  9036. break;
  9037. default:
  9038. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  9039. break;
  9040. }
  9041. //}
  9042. return result;
  9043. };
  9044. function Material () {
  9045. this.id = "";
  9046. this.name = "";
  9047. this.instance_effect = null;
  9048. };
  9049. Material.prototype.parse = function ( element ) {
  9050. this.id = element.getAttribute( 'id' );
  9051. this.name = element.getAttribute( 'name' );
  9052. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9053. if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
  9054. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  9055. break;
  9056. }
  9057. }
  9058. return this;
  9059. };
  9060. function ColorOrTexture () {
  9061. this.color = new THREE.Color( 0 );
  9062. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  9063. this.color.a = 1.0;
  9064. this.texture = null;
  9065. this.texcoord = null;
  9066. this.texOpts = null;
  9067. };
  9068. ColorOrTexture.prototype.isColor = function () {
  9069. return ( this.texture == null );
  9070. };
  9071. ColorOrTexture.prototype.isTexture = function () {
  9072. return ( this.texture != null );
  9073. };
  9074. ColorOrTexture.prototype.parse = function ( element ) {
  9075. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9076. var child = element.childNodes[ i ];
  9077. if ( child.nodeType != 1 ) continue;
  9078. switch ( child.nodeName ) {
  9079. case 'color':
  9080. var rgba = _floats( child.textContent );
  9081. this.color = new THREE.Color(0);
  9082. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  9083. this.color.a = rgba[3];
  9084. break;
  9085. case 'texture':
  9086. this.texture = child.getAttribute('texture');
  9087. this.texcoord = child.getAttribute('texcoord');
  9088. // Defaults from:
  9089. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  9090. this.texOpts = {
  9091. offsetU: 0,
  9092. offsetV: 0,
  9093. repeatU: 1,
  9094. repeatV: 1,
  9095. wrapU: 1,
  9096. wrapV: 1,
  9097. };
  9098. this.parseTexture( child );
  9099. break;
  9100. default:
  9101. break;
  9102. }
  9103. }
  9104. return this;
  9105. };
  9106. ColorOrTexture.prototype.parseTexture = function ( element ) {
  9107. if ( ! element.childNodes ) return this;
  9108. // This should be supported by Maya, 3dsMax, and MotionBuilder
  9109. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  9110. element = element.childNodes[1];
  9111. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  9112. element = element.childNodes[1];
  9113. }
  9114. }
  9115. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9116. var child = element.childNodes[ i ];
  9117. switch ( child.nodeName ) {
  9118. case 'offsetU':
  9119. case 'offsetV':
  9120. case 'repeatU':
  9121. case 'repeatV':
  9122. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  9123. break;
  9124. case 'wrapU':
  9125. case 'wrapV':
  9126. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  9127. break;
  9128. default:
  9129. this.texOpts[ child.nodeName ] = child.textContent;
  9130. break;
  9131. }
  9132. }
  9133. return this;
  9134. };
  9135. function Shader ( type, effect ) {
  9136. this.type = type;
  9137. this.effect = effect;
  9138. this.material = null;
  9139. };
  9140. Shader.prototype.parse = function ( element ) {
  9141. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9142. var child = element.childNodes[ i ];
  9143. if ( child.nodeType != 1 ) continue;
  9144. switch ( child.nodeName ) {
  9145. case 'ambient':
  9146. case 'emission':
  9147. case 'diffuse':
  9148. case 'specular':
  9149. case 'transparent':
  9150. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  9151. break;
  9152. case 'shininess':
  9153. case 'reflectivity':
  9154. case 'transparency':
  9155. var f = evaluateXPath( child, './/dae:float' );
  9156. if ( f.length > 0 )
  9157. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  9158. break;
  9159. default:
  9160. break;
  9161. }
  9162. }
  9163. this.create();
  9164. return this;
  9165. };
  9166. Shader.prototype.create = function() {
  9167. var props = {};
  9168. var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
  9169. for ( var prop in this ) {
  9170. switch ( prop ) {
  9171. case 'ambient':
  9172. case 'emission':
  9173. case 'diffuse':
  9174. case 'specular':
  9175. var cot = this[prop];
  9176. if ( cot instanceof ColorOrTexture ) {
  9177. if ( cot.isTexture() ) {
  9178. if ( this.effect.sampler && this.effect.surface ) {
  9179. if ( this.effect.sampler.source == this.effect.surface.sid ) {
  9180. var image = images[this.effect.surface.init_from];
  9181. if ( image ) {
  9182. var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
  9183. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  9184. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  9185. texture.offset.x = cot.texOpts.offsetU;
  9186. texture.offset.y = cot.texOpts.offsetV;
  9187. texture.repeat.x = cot.texOpts.repeatU;
  9188. texture.repeat.y = cot.texOpts.repeatV;
  9189. props['map'] = texture;
  9190. // Texture with baked lighting?
  9191. if ( prop == 'emission' ) props[ 'emissive' ] = 0xffffff;
  9192. }
  9193. }
  9194. }
  9195. } else if ( prop == 'diffuse' || !transparent ) {
  9196. if ( prop == 'emission' ) {
  9197. props[ 'emissive' ] = cot.color.getHex();
  9198. } else {
  9199. props[ prop ] = cot.color.getHex();
  9200. }
  9201. }
  9202. }
  9203. break;
  9204. case 'shininess':
  9205. case 'reflectivity':
  9206. props[ prop ] = this[ prop ];
  9207. break;
  9208. case 'transparency':
  9209. if ( transparent ) {
  9210. props[ 'transparent' ] = true;
  9211. props[ 'opacity' ] = this[ prop ];
  9212. transparent = true;
  9213. }
  9214. break;
  9215. default:
  9216. break;
  9217. }
  9218. }
  9219. props[ 'shading' ] = preferredShading;
  9220. switch ( this.type ) {
  9221. case 'constant':
  9222. props.color = props.emission;
  9223. this.material = new THREE.MeshBasicMaterial( props );
  9224. break;
  9225. case 'phong':
  9226. case 'blinn':
  9227. props.color = props.diffuse;
  9228. this.material = new THREE.MeshPhongMaterial( props );
  9229. break;
  9230. case 'lambert':
  9231. default:
  9232. props.color = props.diffuse;
  9233. this.material = new THREE.MeshLambertMaterial( props );
  9234. break;
  9235. }
  9236. return this.material;
  9237. };
  9238. function Surface ( effect ) {
  9239. this.effect = effect;
  9240. this.init_from = null;
  9241. this.format = null;
  9242. };
  9243. Surface.prototype.parse = function ( element ) {
  9244. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9245. var child = element.childNodes[ i ];
  9246. if ( child.nodeType != 1 ) continue;
  9247. switch ( child.nodeName ) {
  9248. case 'init_from':
  9249. this.init_from = child.textContent;
  9250. break;
  9251. case 'format':
  9252. this.format = child.textContent;
  9253. break;
  9254. default:
  9255. console.log( "unhandled Surface prop: " + child.nodeName );
  9256. break;
  9257. }
  9258. }
  9259. return this;
  9260. };
  9261. function Sampler2D ( effect ) {
  9262. this.effect = effect;
  9263. this.source = null;
  9264. this.wrap_s = null;
  9265. this.wrap_t = null;
  9266. this.minfilter = null;
  9267. this.magfilter = null;
  9268. this.mipfilter = null;
  9269. };
  9270. Sampler2D.prototype.parse = function ( element ) {
  9271. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9272. var child = element.childNodes[ i ];
  9273. if ( child.nodeType != 1 ) continue;
  9274. switch ( child.nodeName ) {
  9275. case 'source':
  9276. this.source = child.textContent;
  9277. break;
  9278. case 'minfilter':
  9279. this.minfilter = child.textContent;
  9280. break;
  9281. case 'magfilter':
  9282. this.magfilter = child.textContent;
  9283. break;
  9284. case 'mipfilter':
  9285. this.mipfilter = child.textContent;
  9286. break;
  9287. case 'wrap_s':
  9288. this.wrap_s = child.textContent;
  9289. break;
  9290. case 'wrap_t':
  9291. this.wrap_t = child.textContent;
  9292. break;
  9293. default:
  9294. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  9295. break;
  9296. }
  9297. }
  9298. return this;
  9299. };
  9300. function Effect () {
  9301. this.id = "";
  9302. this.name = "";
  9303. this.shader = null;
  9304. this.surface = null;
  9305. this.sampler = null;
  9306. };
  9307. Effect.prototype.create = function () {
  9308. if ( this.shader == null ) {
  9309. return null;
  9310. }
  9311. };
  9312. Effect.prototype.parse = function ( element ) {
  9313. this.id = element.getAttribute( 'id' );
  9314. this.name = element.getAttribute( 'name' );
  9315. this.shader = null;
  9316. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9317. var child = element.childNodes[ i ];
  9318. if ( child.nodeType != 1 ) continue;
  9319. switch ( child.nodeName ) {
  9320. case 'profile_COMMON':
  9321. this.parseTechnique( this.parseProfileCOMMON( child ) );
  9322. break;
  9323. default:
  9324. break;
  9325. }
  9326. }
  9327. return this;
  9328. };
  9329. Effect.prototype.parseNewparam = function ( element ) {
  9330. var sid = element.getAttribute( 'sid' );
  9331. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9332. var child = element.childNodes[ i ];
  9333. if ( child.nodeType != 1 ) continue;
  9334. switch ( child.nodeName ) {
  9335. case 'surface':
  9336. this.surface = ( new Surface( this ) ).parse( child );
  9337. this.surface.sid = sid;
  9338. break;
  9339. case 'sampler2D':
  9340. this.sampler = ( new Sampler2D( this ) ).parse( child );
  9341. this.sampler.sid = sid;
  9342. break;
  9343. case 'extra':
  9344. break;
  9345. default:
  9346. console.log( child.nodeName );
  9347. break;
  9348. }
  9349. }
  9350. };
  9351. Effect.prototype.parseProfileCOMMON = function ( element ) {
  9352. var technique;
  9353. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9354. var child = element.childNodes[ i ];
  9355. if ( child.nodeType != 1 ) continue;
  9356. switch ( child.nodeName ) {
  9357. case 'profile_COMMON':
  9358. this.parseProfileCOMMON( child );
  9359. break;
  9360. case 'technique':
  9361. technique = child;
  9362. break;
  9363. case 'newparam':
  9364. this.parseNewparam( child );
  9365. break;
  9366. case 'image':
  9367. var _image = ( new _Image() ).parse( child );
  9368. images[ _image.id ] = _image;
  9369. break;
  9370. case 'extra':
  9371. break;
  9372. default:
  9373. console.log( child.nodeName );
  9374. break;
  9375. }
  9376. }
  9377. return technique;
  9378. };
  9379. Effect.prototype.parseTechnique= function ( element ) {
  9380. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9381. var child = element.childNodes[i];
  9382. if ( child.nodeType != 1 ) continue;
  9383. switch ( child.nodeName ) {
  9384. case 'constant':
  9385. case 'lambert':
  9386. case 'blinn':
  9387. case 'phong':
  9388. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  9389. break;
  9390. default:
  9391. break;
  9392. }
  9393. }
  9394. };
  9395. function InstanceEffect () {
  9396. this.url = "";
  9397. };
  9398. InstanceEffect.prototype.parse = function ( element ) {
  9399. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  9400. return this;
  9401. };
  9402. function Animation() {
  9403. this.id = "";
  9404. this.name = "";
  9405. this.source = {};
  9406. this.sampler = [];
  9407. this.channel = [];
  9408. };
  9409. Animation.prototype.parse = function ( element ) {
  9410. this.id = element.getAttribute( 'id' );
  9411. this.name = element.getAttribute( 'name' );
  9412. this.source = {};
  9413. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9414. var child = element.childNodes[ i ];
  9415. if ( child.nodeType != 1 ) continue;
  9416. switch ( child.nodeName ) {
  9417. case 'animation':
  9418. var anim = ( new Animation() ).parse( child );
  9419. for ( var src in anim.source ) {
  9420. this.source[ src ] = anim.source[ src ];
  9421. }
  9422. for ( var j = 0; j < anim.channel.length; j ++ ) {
  9423. this.channel.push( anim.channel[ j ] );
  9424. this.sampler.push( anim.sampler[ j ] );
  9425. }
  9426. break;
  9427. case 'source':
  9428. var src = ( new Source() ).parse( child );
  9429. this.source[ src.id ] = src;
  9430. break;
  9431. case 'sampler':
  9432. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  9433. break;
  9434. case 'channel':
  9435. this.channel.push( ( new Channel( this ) ).parse( child ) );
  9436. break;
  9437. default:
  9438. break;
  9439. }
  9440. }
  9441. return this;
  9442. };
  9443. function Channel( animation ) {
  9444. this.animation = animation;
  9445. this.source = "";
  9446. this.target = "";
  9447. this.fullSid = null;
  9448. this.sid = null;
  9449. this.dotSyntax = null;
  9450. this.arrSyntax = null;
  9451. this.arrIndices = null;
  9452. this.member = null;
  9453. };
  9454. Channel.prototype.parse = function ( element ) {
  9455. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  9456. this.target = element.getAttribute( 'target' );
  9457. var parts = this.target.split( '/' );
  9458. var id = parts.shift();
  9459. var sid = parts.shift();
  9460. var dotSyntax = ( sid.indexOf(".") >= 0 );
  9461. var arrSyntax = ( sid.indexOf("(") >= 0 );
  9462. if ( dotSyntax ) {
  9463. parts = sid.split(".");
  9464. this.sid = parts.shift();
  9465. this.member = parts.shift();
  9466. } else if ( arrSyntax ) {
  9467. var arrIndices = sid.split("(");
  9468. this.sid = arrIndices.shift();
  9469. for (var j = 0; j < arrIndices.length; j ++ ) {
  9470. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  9471. }
  9472. this.arrIndices = arrIndices;
  9473. } else {
  9474. this.sid = sid;
  9475. }
  9476. this.fullSid = sid;
  9477. this.dotSyntax = dotSyntax;
  9478. this.arrSyntax = arrSyntax;
  9479. return this;
  9480. };
  9481. function Sampler ( animation ) {
  9482. this.id = "";
  9483. this.animation = animation;
  9484. this.inputs = [];
  9485. this.input = null;
  9486. this.output = null;
  9487. this.strideOut = null;
  9488. this.interpolation = null;
  9489. this.startTime = null;
  9490. this.endTime = null;
  9491. this.duration = 0;
  9492. };
  9493. Sampler.prototype.parse = function ( element ) {
  9494. this.id = element.getAttribute( 'id' );
  9495. this.inputs = [];
  9496. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9497. var child = element.childNodes[ i ];
  9498. if ( child.nodeType != 1 ) continue;
  9499. switch ( child.nodeName ) {
  9500. case 'input':
  9501. this.inputs.push( (new Input()).parse( child ) );
  9502. break;
  9503. default:
  9504. break;
  9505. }
  9506. }
  9507. return this;
  9508. };
  9509. Sampler.prototype.create = function () {
  9510. for ( var i = 0; i < this.inputs.length; i ++ ) {
  9511. var input = this.inputs[ i ];
  9512. var source = this.animation.source[ input.source ];
  9513. switch ( input.semantic ) {
  9514. case 'INPUT':
  9515. this.input = source.read();
  9516. break;
  9517. case 'OUTPUT':
  9518. this.output = source.read();
  9519. this.strideOut = source.accessor.stride;
  9520. break;
  9521. case 'INTERPOLATION':
  9522. this.interpolation = source.read();
  9523. break;
  9524. case 'IN_TANGENT':
  9525. break;
  9526. case 'OUT_TANGENT':
  9527. break;
  9528. default:
  9529. console.log(input.semantic);
  9530. break;
  9531. }
  9532. }
  9533. this.startTime = 0;
  9534. this.endTime = 0;
  9535. this.duration = 0;
  9536. if ( this.input.length ) {
  9537. this.startTime = 100000000;
  9538. this.endTime = -100000000;
  9539. for ( var i = 0; i < this.input.length; i ++ ) {
  9540. this.startTime = Math.min( this.startTime, this.input[ i ] );
  9541. this.endTime = Math.max( this.endTime, this.input[ i ] );
  9542. }
  9543. this.duration = this.endTime - this.startTime;
  9544. }
  9545. };
  9546. Sampler.prototype.getData = function ( type, ndx ) {
  9547. var data;
  9548. if ( type === 'matrix' && this.strideOut === 16 ) {
  9549. data = this.output[ ndx ];
  9550. } else if ( this.strideOut > 1 ) {
  9551. data = [];
  9552. ndx *= this.strideOut;
  9553. for ( var i = 0; i < this.strideOut; ++i ) {
  9554. data[ i ] = this.output[ ndx + i ];
  9555. }
  9556. if ( this.strideOut === 3 ) {
  9557. switch ( type ) {
  9558. case 'rotate':
  9559. case 'translate':
  9560. fixCoords( data, -1 );
  9561. break;
  9562. case 'scale':
  9563. fixCoords( data, 1 );
  9564. break;
  9565. }
  9566. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  9567. fixCoords( data, -1 );
  9568. }
  9569. } else {
  9570. data = this.output[ ndx ];
  9571. }
  9572. return data;
  9573. };
  9574. function Key ( time ) {
  9575. this.targets = [];
  9576. this.time = time;
  9577. };
  9578. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  9579. this.targets.push( {
  9580. sid: fullSid,
  9581. member: member,
  9582. transform: transform,
  9583. data: data
  9584. } );
  9585. };
  9586. Key.prototype.apply = function ( opt_sid ) {
  9587. for ( var i = 0; i < this.targets.length; ++i ) {
  9588. var target = this.targets[ i ];
  9589. if ( !opt_sid || target.sid === opt_sid ) {
  9590. target.transform.update( target.data, target.member );
  9591. }
  9592. }
  9593. };
  9594. Key.prototype.getTarget = function ( fullSid ) {
  9595. for ( var i = 0; i < this.targets.length; ++i ) {
  9596. if ( this.targets[ i ].sid === fullSid ) {
  9597. return this.targets[ i ];
  9598. }
  9599. }
  9600. return null;
  9601. };
  9602. Key.prototype.hasTarget = function ( fullSid ) {
  9603. for ( var i = 0; i < this.targets.length; ++i ) {
  9604. if ( this.targets[ i ].sid === fullSid ) {
  9605. return true;
  9606. }
  9607. }
  9608. return false;
  9609. };
  9610. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  9611. Key.prototype.interpolate = function ( nextKey, time ) {
  9612. for ( var i = 0; i < this.targets.length; ++i ) {
  9613. var target = this.targets[ i ],
  9614. nextTarget = nextKey.getTarget( target.sid ),
  9615. data;
  9616. if ( target.transform.type !== 'matrix' && nextTarget ) {
  9617. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  9618. nextData = nextTarget.data,
  9619. prevData = target.data;
  9620. // check scale error
  9621. if ( scale < 0 || scale > 1 ) {
  9622. console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
  9623. scale = scale < 0 ? 0 : 1;
  9624. }
  9625. if ( prevData.length ) {
  9626. data = [];
  9627. for ( var j = 0; j < prevData.length; ++j ) {
  9628. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  9629. }
  9630. } else {
  9631. data = prevData + ( nextData - prevData ) * scale;
  9632. }
  9633. } else {
  9634. data = target.data;
  9635. }
  9636. target.transform.update( data, target.member );
  9637. }
  9638. };
  9639. function Camera() {
  9640. this.id = "";
  9641. this.name = "";
  9642. this.technique = "";
  9643. };
  9644. Camera.prototype.parse = function ( element ) {
  9645. this.id = element.getAttribute( 'id' );
  9646. this.name = element.getAttribute( 'name' );
  9647. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9648. var child = element.childNodes[ i ];
  9649. if ( child.nodeType != 1 ) continue;
  9650. switch ( child.nodeName ) {
  9651. case 'optics':
  9652. this.parseOptics( child );
  9653. break;
  9654. default:
  9655. break;
  9656. }
  9657. }
  9658. return this;
  9659. };
  9660. Camera.prototype.parseOptics = function ( element ) {
  9661. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9662. if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
  9663. var technique = element.childNodes[ i ];
  9664. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  9665. this.technique = technique.childNodes[ j ].nodeName;
  9666. if ( this.technique == 'perspective' ) {
  9667. var perspective = technique.childNodes[ j ];
  9668. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  9669. var param = perspective.childNodes[ k ];
  9670. switch ( param.nodeName ) {
  9671. case 'yfov':
  9672. this.yfov = param.textContent;
  9673. break;
  9674. case 'xfov':
  9675. this.xfov = param.textContent;
  9676. break;
  9677. case 'znear':
  9678. this.znear = param.textContent;
  9679. break;
  9680. case 'zfar':
  9681. this.zfar = param.textContent;
  9682. break;
  9683. case 'aspect_ratio':
  9684. this.aspect_ratio = param.textContent;
  9685. break;
  9686. }
  9687. }
  9688. } else if ( this.technique == 'orthographic' ) {
  9689. var orthographic = technique.childNodes[ j ];
  9690. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  9691. var param = orthographic.childNodes[ k ];
  9692. switch ( param.nodeName ) {
  9693. case 'xmag':
  9694. this.xmag = param.textContent;
  9695. break;
  9696. case 'ymag':
  9697. this.ymag = param.textContent;
  9698. break;
  9699. case 'znear':
  9700. this.znear = param.textContent;
  9701. break;
  9702. case 'zfar':
  9703. this.zfar = param.textContent;
  9704. break;
  9705. case 'aspect_ratio':
  9706. this.aspect_ratio = param.textContent;
  9707. break;
  9708. }
  9709. }
  9710. }
  9711. }
  9712. }
  9713. }
  9714. return this;
  9715. };
  9716. function InstanceCamera() {
  9717. this.url = "";
  9718. };
  9719. InstanceCamera.prototype.parse = function ( element ) {
  9720. this.url = element.getAttribute('url').replace(/^#/, '');
  9721. return this;
  9722. };
  9723. function _source( element ) {
  9724. var id = element.getAttribute( 'id' );
  9725. if ( sources[ id ] != undefined ) {
  9726. return sources[ id ];
  9727. }
  9728. sources[ id ] = ( new Source(id )).parse( element );
  9729. return sources[ id ];
  9730. };
  9731. function _nsResolver( nsPrefix ) {
  9732. if ( nsPrefix == "dae" ) {
  9733. return "http://www.collada.org/2005/11/COLLADASchema";
  9734. }
  9735. return null;
  9736. };
  9737. function _bools( str ) {
  9738. var raw = _strings( str );
  9739. var data = [];
  9740. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  9741. data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
  9742. }
  9743. return data;
  9744. };
  9745. function _floats( str ) {
  9746. var raw = _strings(str);
  9747. var data = [];
  9748. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  9749. data.push( parseFloat( raw[ i ] ) );
  9750. }
  9751. return data;
  9752. };
  9753. function _ints( str ) {
  9754. var raw = _strings( str );
  9755. var data = [];
  9756. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  9757. data.push( parseInt( raw[ i ], 10 ) );
  9758. }
  9759. return data;
  9760. };
  9761. function _strings( str ) {
  9762. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  9763. };
  9764. function _trimString( str ) {
  9765. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  9766. };
  9767. function _attr_as_float( element, name, defaultValue ) {
  9768. if ( element.hasAttribute( name ) ) {
  9769. return parseFloat( element.getAttribute( name ) );
  9770. } else {
  9771. return defaultValue;
  9772. }
  9773. };
  9774. function _attr_as_int( element, name, defaultValue ) {
  9775. if ( element.hasAttribute( name ) ) {
  9776. return parseInt( element.getAttribute( name ), 10) ;
  9777. } else {
  9778. return defaultValue;
  9779. }
  9780. };
  9781. function _attr_as_string( element, name, defaultValue ) {
  9782. if ( element.hasAttribute( name ) ) {
  9783. return element.getAttribute( name );
  9784. } else {
  9785. return defaultValue;
  9786. }
  9787. };
  9788. function _format_float( f, num ) {
  9789. if ( f === undefined ) {
  9790. var s = '0.';
  9791. while ( s.length < num + 2 ) {
  9792. s += '0';
  9793. }
  9794. return s;
  9795. }
  9796. num = num || 2;
  9797. var parts = f.toString().split( '.' );
  9798. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  9799. while( parts[ 1 ].length < num ) {
  9800. parts[ 1 ] += '0';
  9801. }
  9802. return parts.join( '.' );
  9803. };
  9804. function evaluateXPath( node, query ) {
  9805. var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  9806. var inst = instances.iterateNext();
  9807. var result = [];
  9808. while ( inst ) {
  9809. result.push( inst );
  9810. inst = instances.iterateNext();
  9811. }
  9812. return result;
  9813. };
  9814. // Up axis conversion
  9815. function setUpConversion() {
  9816. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  9817. upConversion = null;
  9818. } else {
  9819. switch ( colladaUp ) {
  9820. case 'X':
  9821. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  9822. break;
  9823. case 'Y':
  9824. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  9825. break;
  9826. case 'Z':
  9827. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  9828. break;
  9829. }
  9830. }
  9831. };
  9832. function fixCoords( data, sign ) {
  9833. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  9834. return;
  9835. }
  9836. switch ( upConversion ) {
  9837. case 'XtoY':
  9838. var tmp = data[ 0 ];
  9839. data[ 0 ] = sign * data[ 1 ];
  9840. data[ 1 ] = tmp;
  9841. break;
  9842. case 'XtoZ':
  9843. var tmp = data[ 2 ];
  9844. data[ 2 ] = data[ 1 ];
  9845. data[ 1 ] = data[ 0 ];
  9846. data[ 0 ] = tmp;
  9847. break;
  9848. case 'YtoX':
  9849. var tmp = data[ 0 ];
  9850. data[ 0 ] = data[ 1 ];
  9851. data[ 1 ] = sign * tmp;
  9852. break;
  9853. case 'YtoZ':
  9854. var tmp = data[ 1 ];
  9855. data[ 1 ] = sign * data[ 2 ];
  9856. data[ 2 ] = tmp;
  9857. break;
  9858. case 'ZtoX':
  9859. var tmp = data[ 0 ];
  9860. data[ 0 ] = data[ 1 ];
  9861. data[ 1 ] = data[ 2 ];
  9862. data[ 2 ] = tmp;
  9863. break;
  9864. case 'ZtoY':
  9865. var tmp = data[ 1 ];
  9866. data[ 1 ] = data[ 2 ];
  9867. data[ 2 ] = sign * tmp;
  9868. break;
  9869. }
  9870. };
  9871. function getConvertedVec3( data, offset ) {
  9872. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  9873. fixCoords( arr, -1 );
  9874. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  9875. };
  9876. function getConvertedMat4( data ) {
  9877. if ( options.convertUpAxis ) {
  9878. // First fix rotation and scale
  9879. // Columns first
  9880. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  9881. fixCoords( arr, -1 );
  9882. data[ 0 ] = arr[ 0 ];
  9883. data[ 4 ] = arr[ 1 ];
  9884. data[ 8 ] = arr[ 2 ];
  9885. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  9886. fixCoords( arr, -1 );
  9887. data[ 1 ] = arr[ 0 ];
  9888. data[ 5 ] = arr[ 1 ];
  9889. data[ 9 ] = arr[ 2 ];
  9890. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  9891. fixCoords( arr, -1 );
  9892. data[ 2 ] = arr[ 0 ];
  9893. data[ 6 ] = arr[ 1 ];
  9894. data[ 10 ] = arr[ 2 ];
  9895. // Rows second
  9896. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  9897. fixCoords( arr, -1 );
  9898. data[ 0 ] = arr[ 0 ];
  9899. data[ 1 ] = arr[ 1 ];
  9900. data[ 2 ] = arr[ 2 ];
  9901. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  9902. fixCoords( arr, -1 );
  9903. data[ 4 ] = arr[ 0 ];
  9904. data[ 5 ] = arr[ 1 ];
  9905. data[ 6 ] = arr[ 2 ];
  9906. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  9907. fixCoords( arr, -1 );
  9908. data[ 8 ] = arr[ 0 ];
  9909. data[ 9 ] = arr[ 1 ];
  9910. data[ 10 ] = arr[ 2 ];
  9911. // Now fix translation
  9912. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  9913. fixCoords( arr, -1 );
  9914. data[ 3 ] = arr[ 0 ];
  9915. data[ 7 ] = arr[ 1 ];
  9916. data[ 11 ] = arr[ 2 ];
  9917. }
  9918. return new THREE.Matrix4(
  9919. data[0], data[1], data[2], data[3],
  9920. data[4], data[5], data[6], data[7],
  9921. data[8], data[9], data[10], data[11],
  9922. data[12], data[13], data[14], data[15]
  9923. );
  9924. };
  9925. function getConvertedIndex( index ) {
  9926. if ( index > -1 && index < 3 ) {
  9927. var members = ['X', 'Y', 'Z'],
  9928. indices = { X: 0, Y: 1, Z: 2 };
  9929. index = getConvertedMember( members[ index ] );
  9930. index = indices[ index ];
  9931. }
  9932. return index;
  9933. };
  9934. function getConvertedMember( member ) {
  9935. if ( options.convertUpAxis ) {
  9936. switch ( member ) {
  9937. case 'X':
  9938. switch ( upConversion ) {
  9939. case 'XtoY':
  9940. case 'XtoZ':
  9941. case 'YtoX':
  9942. member = 'Y';
  9943. break;
  9944. case 'ZtoX':
  9945. member = 'Z';
  9946. break;
  9947. }
  9948. break;
  9949. case 'Y':
  9950. switch ( upConversion ) {
  9951. case 'XtoY':
  9952. case 'YtoX':
  9953. case 'ZtoX':
  9954. member = 'X';
  9955. break;
  9956. case 'XtoZ':
  9957. case 'YtoZ':
  9958. case 'ZtoY':
  9959. member = 'Z';
  9960. break;
  9961. }
  9962. break;
  9963. case 'Z':
  9964. switch ( upConversion ) {
  9965. case 'XtoZ':
  9966. member = 'X';
  9967. break;
  9968. case 'YtoZ':
  9969. case 'ZtoX':
  9970. case 'ZtoY':
  9971. member = 'Y';
  9972. break;
  9973. }
  9974. break;
  9975. }
  9976. }
  9977. return member;
  9978. };
  9979. return {
  9980. load: load,
  9981. parse: parse,
  9982. setPreferredShading: setPreferredShading,
  9983. applySkin: applySkin,
  9984. geometries : geometries,
  9985. options: options
  9986. };
  9987. };
  9988. /**
  9989. * @author mrdoob / http://mrdoob.com/
  9990. * @author alteredq / http://alteredqualia.com/
  9991. */
  9992. THREE.JSONLoader = function ( showStatus ) {
  9993. THREE.Loader.call( this, showStatus );
  9994. };
  9995. THREE.JSONLoader.prototype = new THREE.Loader();
  9996. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  9997. THREE.JSONLoader.prototype.supr = THREE.Loader.prototype;
  9998. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  9999. var worker, scope = this;
  10000. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  10001. this.onLoadStart();
  10002. this.loadAjaxJSON( this, url, callback, texturePath );
  10003. };
  10004. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  10005. var xhr = new XMLHttpRequest();
  10006. var length = 0;
  10007. xhr.onreadystatechange = function () {
  10008. if ( xhr.readyState === xhr.DONE ) {
  10009. if ( xhr.status === 200 || xhr.status === 0 ) {
  10010. if ( xhr.responseText ) {
  10011. var json = JSON.parse( xhr.responseText );
  10012. context.createModel( json, callback, texturePath );
  10013. } else {
  10014. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  10015. }
  10016. // in context of more complex asset initialization
  10017. // do not block on single failed file
  10018. // maybe should go even one more level up
  10019. context.onLoadComplete();
  10020. } else {
  10021. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  10022. }
  10023. } else if ( xhr.readyState === xhr.LOADING ) {
  10024. if ( callbackProgress ) {
  10025. if ( length === 0 ) {
  10026. length = xhr.getResponseHeader( "Content-Length" );
  10027. }
  10028. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  10029. }
  10030. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  10031. length = xhr.getResponseHeader( "Content-Length" );
  10032. }
  10033. };
  10034. xhr.open( "GET", url, true );
  10035. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  10036. xhr.setRequestHeader( "Content-Type", "text/plain" );
  10037. xhr.send( null );
  10038. };
  10039. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  10040. var scope = this,
  10041. geometry = new THREE.Geometry(),
  10042. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  10043. this.initMaterials( geometry, json.materials, texturePath );
  10044. parseModel( scale );
  10045. parseSkin();
  10046. parseMorphing( scale );
  10047. geometry.computeCentroids();
  10048. geometry.computeFaceNormals();
  10049. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  10050. function parseModel( scale ) {
  10051. function isBitSet( value, position ) {
  10052. return value & ( 1 << position );
  10053. }
  10054. var i, j, fi,
  10055. offset, zLength, nVertices,
  10056. colorIndex, normalIndex, uvIndex, materialIndex,
  10057. type,
  10058. isQuad,
  10059. hasMaterial,
  10060. hasFaceUv, hasFaceVertexUv,
  10061. hasFaceNormal, hasFaceVertexNormal,
  10062. hasFaceColor, hasFaceVertexColor,
  10063. vertex, face, color, normal,
  10064. uvLayer, uvs, u, v,
  10065. faces = json.faces,
  10066. vertices = json.vertices,
  10067. normals = json.normals,
  10068. colors = json.colors,
  10069. nUvLayers = 0;
  10070. // disregard empty arrays
  10071. for ( i = 0; i < json.uvs.length; i++ ) {
  10072. if ( json.uvs[ i ].length ) nUvLayers ++;
  10073. }
  10074. for ( i = 0; i < nUvLayers; i++ ) {
  10075. geometry.faceUvs[ i ] = [];
  10076. geometry.faceVertexUvs[ i ] = [];
  10077. }
  10078. offset = 0;
  10079. zLength = vertices.length;
  10080. while ( offset < zLength ) {
  10081. vertex = new THREE.Vector3();
  10082. vertex.x = vertices[ offset ++ ] * scale;
  10083. vertex.y = vertices[ offset ++ ] * scale;
  10084. vertex.z = vertices[ offset ++ ] * scale;
  10085. geometry.vertices.push( vertex );
  10086. }
  10087. offset = 0;
  10088. zLength = faces.length;
  10089. while ( offset < zLength ) {
  10090. type = faces[ offset ++ ];
  10091. isQuad = isBitSet( type, 0 );
  10092. hasMaterial = isBitSet( type, 1 );
  10093. hasFaceUv = isBitSet( type, 2 );
  10094. hasFaceVertexUv = isBitSet( type, 3 );
  10095. hasFaceNormal = isBitSet( type, 4 );
  10096. hasFaceVertexNormal = isBitSet( type, 5 );
  10097. hasFaceColor = isBitSet( type, 6 );
  10098. hasFaceVertexColor = isBitSet( type, 7 );
  10099. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  10100. if ( isQuad ) {
  10101. face = new THREE.Face4();
  10102. face.a = faces[ offset ++ ];
  10103. face.b = faces[ offset ++ ];
  10104. face.c = faces[ offset ++ ];
  10105. face.d = faces[ offset ++ ];
  10106. nVertices = 4;
  10107. } else {
  10108. face = new THREE.Face3();
  10109. face.a = faces[ offset ++ ];
  10110. face.b = faces[ offset ++ ];
  10111. face.c = faces[ offset ++ ];
  10112. nVertices = 3;
  10113. }
  10114. if ( hasMaterial ) {
  10115. materialIndex = faces[ offset ++ ];
  10116. face.materialIndex = materialIndex;
  10117. }
  10118. // to get face <=> uv index correspondence
  10119. fi = geometry.faces.length;
  10120. if ( hasFaceUv ) {
  10121. for ( i = 0; i < nUvLayers; i++ ) {
  10122. uvLayer = json.uvs[ i ];
  10123. uvIndex = faces[ offset ++ ];
  10124. u = uvLayer[ uvIndex * 2 ];
  10125. v = uvLayer[ uvIndex * 2 + 1 ];
  10126. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  10127. }
  10128. }
  10129. if ( hasFaceVertexUv ) {
  10130. for ( i = 0; i < nUvLayers; i++ ) {
  10131. uvLayer = json.uvs[ i ];
  10132. uvs = [];
  10133. for ( j = 0; j < nVertices; j ++ ) {
  10134. uvIndex = faces[ offset ++ ];
  10135. u = uvLayer[ uvIndex * 2 ];
  10136. v = uvLayer[ uvIndex * 2 + 1 ];
  10137. uvs[ j ] = new THREE.UV( u, v );
  10138. }
  10139. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  10140. }
  10141. }
  10142. if ( hasFaceNormal ) {
  10143. normalIndex = faces[ offset ++ ] * 3;
  10144. normal = new THREE.Vector3();
  10145. normal.x = normals[ normalIndex ++ ];
  10146. normal.y = normals[ normalIndex ++ ];
  10147. normal.z = normals[ normalIndex ];
  10148. face.normal = normal;
  10149. }
  10150. if ( hasFaceVertexNormal ) {
  10151. for ( i = 0; i < nVertices; i++ ) {
  10152. normalIndex = faces[ offset ++ ] * 3;
  10153. normal = new THREE.Vector3();
  10154. normal.x = normals[ normalIndex ++ ];
  10155. normal.y = normals[ normalIndex ++ ];
  10156. normal.z = normals[ normalIndex ];
  10157. face.vertexNormals.push( normal );
  10158. }
  10159. }
  10160. if ( hasFaceColor ) {
  10161. colorIndex = faces[ offset ++ ];
  10162. color = new THREE.Color( colors[ colorIndex ] );
  10163. face.color = color;
  10164. }
  10165. if ( hasFaceVertexColor ) {
  10166. for ( i = 0; i < nVertices; i++ ) {
  10167. colorIndex = faces[ offset ++ ];
  10168. color = new THREE.Color( colors[ colorIndex ] );
  10169. face.vertexColors.push( color );
  10170. }
  10171. }
  10172. geometry.faces.push( face );
  10173. }
  10174. };
  10175. function parseSkin() {
  10176. var i, l, x, y, z, w, a, b, c, d;
  10177. if ( json.skinWeights ) {
  10178. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  10179. x = json.skinWeights[ i ];
  10180. y = json.skinWeights[ i + 1 ];
  10181. z = 0;
  10182. w = 0;
  10183. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  10184. }
  10185. }
  10186. if ( json.skinIndices ) {
  10187. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  10188. a = json.skinIndices[ i ];
  10189. b = json.skinIndices[ i + 1 ];
  10190. c = 0;
  10191. d = 0;
  10192. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  10193. }
  10194. }
  10195. geometry.bones = json.bones;
  10196. geometry.animation = json.animation;
  10197. };
  10198. function parseMorphing( scale ) {
  10199. if ( json.morphTargets !== undefined ) {
  10200. var i, l, v, vl, dstVertices, srcVertices;
  10201. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  10202. geometry.morphTargets[ i ] = {};
  10203. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  10204. geometry.morphTargets[ i ].vertices = [];
  10205. dstVertices = geometry.morphTargets[ i ].vertices;
  10206. srcVertices = json.morphTargets [ i ].vertices;
  10207. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  10208. var vertex = new THREE.Vector3();
  10209. vertex.x = srcVertices[ v ] * scale;
  10210. vertex.y = srcVertices[ v + 1 ] * scale;
  10211. vertex.z = srcVertices[ v + 2 ] * scale;
  10212. dstVertices.push( vertex );
  10213. }
  10214. }
  10215. }
  10216. if ( json.morphColors !== undefined ) {
  10217. var i, l, c, cl, dstColors, srcColors, color;
  10218. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  10219. geometry.morphColors[ i ] = {};
  10220. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  10221. geometry.morphColors[ i ].colors = [];
  10222. dstColors = geometry.morphColors[ i ].colors;
  10223. srcColors = json.morphColors [ i ].colors;
  10224. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  10225. color = new THREE.Color( 0xffaa00 );
  10226. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  10227. dstColors.push( color );
  10228. }
  10229. }
  10230. }
  10231. };
  10232. callback( geometry );
  10233. };
  10234. /**
  10235. * @author alteredq / http://alteredqualia.com/
  10236. */
  10237. THREE.SceneLoader = function () {
  10238. this.onLoadStart = function () {};
  10239. this.onLoadProgress = function() {};
  10240. this.onLoadComplete = function () {};
  10241. this.callbackSync = function () {};
  10242. this.callbackProgress = function () {};
  10243. };
  10244. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  10245. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  10246. var context = this;
  10247. var xhr = new XMLHttpRequest();
  10248. xhr.onreadystatechange = function () {
  10249. if ( xhr.readyState == 4 ) {
  10250. if ( xhr.status == 200 || xhr.status == 0 ) {
  10251. var json = JSON.parse( xhr.responseText );
  10252. context.createScene( json, callbackFinished, url );
  10253. } else {
  10254. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  10255. }
  10256. }
  10257. };
  10258. xhr.open( "GET", url, true );
  10259. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  10260. xhr.setRequestHeader( "Content-Type", "text/plain" );
  10261. xhr.send( null );
  10262. };
  10263. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  10264. var scope = this;
  10265. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  10266. var dg, dm, dd, dl, dc, df, dt,
  10267. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  10268. geometry, material, camera, fog,
  10269. texture, images,
  10270. light,
  10271. data, binLoader, jsonLoader,
  10272. counter_models, counter_textures,
  10273. total_models, total_textures,
  10274. result;
  10275. data = json;
  10276. binLoader = new THREE.BinaryLoader();
  10277. jsonLoader = new THREE.JSONLoader();
  10278. counter_models = 0;
  10279. counter_textures = 0;
  10280. result = {
  10281. scene: new THREE.Scene(),
  10282. geometries: {},
  10283. materials: {},
  10284. textures: {},
  10285. objects: {},
  10286. cameras: {},
  10287. lights: {},
  10288. fogs: {},
  10289. empties: {}
  10290. };
  10291. if ( data.transform ) {
  10292. var position = data.transform.position,
  10293. rotation = data.transform.rotation,
  10294. scale = data.transform.scale;
  10295. if ( position )
  10296. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  10297. if ( rotation )
  10298. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  10299. if ( scale )
  10300. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  10301. if ( position || rotation || scale ) {
  10302. result.scene.updateMatrix();
  10303. result.scene.updateMatrixWorld();
  10304. }
  10305. }
  10306. function get_url( source_url, url_type ) {
  10307. if ( url_type == "relativeToHTML" ) {
  10308. return source_url;
  10309. } else {
  10310. return urlBase + "/" + source_url;
  10311. }
  10312. };
  10313. function handle_objects() {
  10314. var object;
  10315. for( dd in data.objects ) {
  10316. if ( !result.objects[ dd ] ) {
  10317. o = data.objects[ dd ];
  10318. if ( o.geometry !== undefined ) {
  10319. geometry = result.geometries[ o.geometry ];
  10320. // geometry already loaded
  10321. if ( geometry ) {
  10322. var hasNormals = false;
  10323. // not anymore support for multiple materials
  10324. // shouldn't really be array
  10325. material = result.materials[ o.materials[ 0 ] ];
  10326. hasNormals = material instanceof THREE.ShaderMaterial;
  10327. if ( hasNormals ) {
  10328. geometry.computeTangents();
  10329. }
  10330. p = o.position;
  10331. r = o.rotation;
  10332. q = o.quaternion;
  10333. s = o.scale;
  10334. m = o.matrix;
  10335. // turn off quaternions, for the moment
  10336. q = 0;
  10337. if ( o.materials.length == 0 ) {
  10338. material = new THREE.MeshFaceMaterial();
  10339. }
  10340. // dirty hack to handle meshes with multiple materials
  10341. // just use face materials defined in model
  10342. if ( o.materials.length > 1 ) {
  10343. material = new THREE.MeshFaceMaterial();
  10344. }
  10345. object = new THREE.Mesh( geometry, material );
  10346. object.name = dd;
  10347. if ( m ) {
  10348. object.matrixAutoUpdate = false;
  10349. object.matrix.set( m[0], m[1], m[2], m[3],
  10350. m[4], m[5], m[6], m[7],
  10351. m[8], m[9], m[10], m[11],
  10352. m[12], m[13], m[14], m[15]);
  10353. } else {
  10354. object.position.set( p[0], p[1], p[2] );
  10355. if ( q ) {
  10356. object.quaternion.set( q[0], q[1], q[2], q[3] );
  10357. object.useQuaternion = true;
  10358. } else {
  10359. object.rotation.set( r[0], r[1], r[2] );
  10360. }
  10361. object.scale.set( s[0], s[1], s[2] );
  10362. }
  10363. object.visible = o.visible;
  10364. object.doubleSided = o.doubleSided;
  10365. object.castShadow = o.castShadow;
  10366. object.receiveShadow = o.receiveShadow;
  10367. result.scene.add( object );
  10368. result.objects[ dd ] = object;
  10369. }
  10370. // pure Object3D
  10371. } else {
  10372. p = o.position;
  10373. r = o.rotation;
  10374. q = o.quaternion;
  10375. s = o.scale;
  10376. // turn off quaternions, for the moment
  10377. q = 0;
  10378. object = new THREE.Object3D();
  10379. object.name = dd;
  10380. object.position.set( p[0], p[1], p[2] );
  10381. if ( q ) {
  10382. object.quaternion.set( q[0], q[1], q[2], q[3] );
  10383. object.useQuaternion = true;
  10384. } else {
  10385. object.rotation.set( r[0], r[1], r[2] );
  10386. }
  10387. object.scale.set( s[0], s[1], s[2] );
  10388. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  10389. result.scene.add( object );
  10390. result.objects[ dd ] = object;
  10391. result.empties[ dd ] = object;
  10392. }
  10393. }
  10394. }
  10395. };
  10396. function handle_mesh( geo, id ) {
  10397. result.geometries[ id ] = geo;
  10398. handle_objects();
  10399. };
  10400. function create_callback( id ) {
  10401. return function( geo ) {
  10402. handle_mesh( geo, id );
  10403. counter_models -= 1;
  10404. scope.onLoadComplete();
  10405. async_callback_gate();
  10406. }
  10407. };
  10408. function create_callback_embed( id ) {
  10409. return function( geo ) {
  10410. result.geometries[ id ] = geo;
  10411. }
  10412. };
  10413. function async_callback_gate() {
  10414. var progress = {
  10415. totalModels : total_models,
  10416. totalTextures : total_textures,
  10417. loadedModels : total_models - counter_models,
  10418. loadedTextures : total_textures - counter_textures
  10419. };
  10420. scope.callbackProgress( progress, result );
  10421. scope.onLoadProgress();
  10422. if( counter_models == 0 && counter_textures == 0 ) {
  10423. callbackFinished( result );
  10424. }
  10425. };
  10426. var callbackTexture = function( images ) {
  10427. counter_textures -= 1;
  10428. async_callback_gate();
  10429. scope.onLoadComplete();
  10430. };
  10431. // first go synchronous elements
  10432. // cameras
  10433. for( dc in data.cameras ) {
  10434. c = data.cameras[ dc ];
  10435. if ( c.type == "perspective" ) {
  10436. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  10437. } else if ( c.type == "ortho" ) {
  10438. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  10439. }
  10440. p = c.position;
  10441. t = c.target;
  10442. u = c.up;
  10443. camera.position.set( p[0], p[1], p[2] );
  10444. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  10445. if ( u ) camera.up.set( u[0], u[1], u[2] );
  10446. result.cameras[ dc ] = camera;
  10447. }
  10448. // lights
  10449. var hex, intensity;
  10450. for ( dl in data.lights ) {
  10451. l = data.lights[ dl ];
  10452. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  10453. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  10454. if ( l.type == "directional" ) {
  10455. p = l.direction;
  10456. light = new THREE.DirectionalLight( hex, intensity );
  10457. light.position.set( p[0], p[1], p[2] );
  10458. light.position.normalize();
  10459. } else if ( l.type == "point" ) {
  10460. p = l.position;
  10461. d = l.distance;
  10462. light = new THREE.PointLight( hex, intensity, d );
  10463. light.position.set( p[0], p[1], p[2] );
  10464. } else if ( l.type == "ambient" ) {
  10465. light = new THREE.AmbientLight( hex );
  10466. }
  10467. result.scene.add( light );
  10468. result.lights[ dl ] = light;
  10469. }
  10470. // fogs
  10471. for( df in data.fogs ) {
  10472. f = data.fogs[ df ];
  10473. if ( f.type == "linear" ) {
  10474. fog = new THREE.Fog( 0x000000, f.near, f.far );
  10475. } else if ( f.type == "exp2" ) {
  10476. fog = new THREE.FogExp2( 0x000000, f.density );
  10477. }
  10478. c = f.color;
  10479. fog.color.setRGB( c[0], c[1], c[2] );
  10480. result.fogs[ df ] = fog;
  10481. }
  10482. // defaults
  10483. if ( result.cameras && data.defaults.camera ) {
  10484. result.currentCamera = result.cameras[ data.defaults.camera ];
  10485. }
  10486. if ( result.fogs && data.defaults.fog ) {
  10487. result.scene.fog = result.fogs[ data.defaults.fog ];
  10488. }
  10489. c = data.defaults.bgcolor;
  10490. result.bgColor = new THREE.Color();
  10491. result.bgColor.setRGB( c[0], c[1], c[2] );
  10492. result.bgColorAlpha = data.defaults.bgalpha;
  10493. // now come potentially asynchronous elements
  10494. // geometries
  10495. // count how many models will be loaded asynchronously
  10496. for( dg in data.geometries ) {
  10497. g = data.geometries[ dg ];
  10498. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  10499. counter_models += 1;
  10500. scope.onLoadStart();
  10501. }
  10502. }
  10503. total_models = counter_models;
  10504. for ( dg in data.geometries ) {
  10505. g = data.geometries[ dg ];
  10506. if ( g.type == "cube" ) {
  10507. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  10508. result.geometries[ dg ] = geometry;
  10509. } else if ( g.type == "plane" ) {
  10510. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  10511. result.geometries[ dg ] = geometry;
  10512. } else if ( g.type == "sphere" ) {
  10513. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  10514. result.geometries[ dg ] = geometry;
  10515. } else if ( g.type == "cylinder" ) {
  10516. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  10517. result.geometries[ dg ] = geometry;
  10518. } else if ( g.type == "torus" ) {
  10519. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  10520. result.geometries[ dg ] = geometry;
  10521. } else if ( g.type == "icosahedron" ) {
  10522. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  10523. result.geometries[ dg ] = geometry;
  10524. } else if ( g.type == "bin_mesh" ) {
  10525. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  10526. } else if ( g.type == "ascii_mesh" ) {
  10527. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  10528. } else if ( g.type == "embedded_mesh" ) {
  10529. var modelJson = data.embeds[ g.id ],
  10530. texture_path = "";
  10531. // Pass metadata along to jsonLoader so it knows the format version.
  10532. modelJson.metadata = data.metadata;
  10533. if ( modelJson ) {
  10534. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  10535. }
  10536. }
  10537. }
  10538. // textures
  10539. // count how many textures will be loaded asynchronously
  10540. for( dt in data.textures ) {
  10541. tt = data.textures[ dt ];
  10542. if( tt.url instanceof Array ) {
  10543. counter_textures += tt.url.length;
  10544. for( var n = 0; n < tt.url.length; n ++ ) {
  10545. scope.onLoadStart();
  10546. }
  10547. } else {
  10548. counter_textures += 1;
  10549. scope.onLoadStart();
  10550. }
  10551. }
  10552. total_textures = counter_textures;
  10553. for( dt in data.textures ) {
  10554. tt = data.textures[ dt ];
  10555. if ( tt.mapping != undefined && THREE[ tt.mapping ] != undefined ) {
  10556. tt.mapping = new THREE[ tt.mapping ]();
  10557. }
  10558. if( tt.url instanceof Array ) {
  10559. var url_array = [];
  10560. for( var i = 0; i < tt.url.length; i ++ ) {
  10561. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  10562. }
  10563. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, callbackTexture );
  10564. } else {
  10565. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, callbackTexture );
  10566. if ( THREE[ tt.minFilter ] != undefined )
  10567. texture.minFilter = THREE[ tt.minFilter ];
  10568. if ( THREE[ tt.magFilter ] != undefined )
  10569. texture.magFilter = THREE[ tt.magFilter ];
  10570. if ( tt.repeat ) {
  10571. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  10572. if ( tt.repeat[ 0 ] != 1 ) texture.wrapS = THREE.RepeatWrapping;
  10573. if ( tt.repeat[ 1 ] != 1 ) texture.wrapT = THREE.RepeatWrapping;
  10574. }
  10575. if ( tt.offset ) {
  10576. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  10577. }
  10578. // handle wrap after repeat so that default repeat can be overriden
  10579. if ( tt.wrap ) {
  10580. var wrapMap = {
  10581. "repeat" : THREE.RepeatWrapping,
  10582. "mirror" : THREE.MirroredRepeatWrapping
  10583. }
  10584. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  10585. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  10586. }
  10587. }
  10588. result.textures[ dt ] = texture;
  10589. }
  10590. // materials
  10591. for ( dm in data.materials ) {
  10592. m = data.materials[ dm ];
  10593. for ( pp in m.parameters ) {
  10594. if ( pp == "envMap" || pp == "map" || pp == "lightMap" ) {
  10595. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  10596. } else if ( pp == "shading" ) {
  10597. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  10598. } else if ( pp == "blending" ) {
  10599. m.parameters[ pp ] = THREE[ m.parameters[ pp ] ] ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  10600. } else if ( pp == "combine" ) {
  10601. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  10602. } else if ( pp == "vertexColors" ) {
  10603. if ( m.parameters[ pp ] == "face" ) {
  10604. m.parameters[ pp ] = THREE.FaceColors;
  10605. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  10606. } else if ( m.parameters[ pp ] ) {
  10607. m.parameters[ pp ] = THREE.VertexColors;
  10608. }
  10609. }
  10610. }
  10611. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  10612. m.parameters.transparent = true;
  10613. }
  10614. if ( m.parameters.normalMap ) {
  10615. var shader = THREE.ShaderUtils.lib[ "normal" ];
  10616. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  10617. var diffuse = m.parameters.color;
  10618. var specular = m.parameters.specular;
  10619. var ambient = m.parameters.ambient;
  10620. var shininess = m.parameters.shininess;
  10621. uniforms[ "tNormal" ].texture = result.textures[ m.parameters.normalMap ];
  10622. if ( m.parameters.normalMapFactor ) {
  10623. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  10624. }
  10625. if ( m.parameters.map ) {
  10626. uniforms[ "tDiffuse" ].texture = m.parameters.map;
  10627. uniforms[ "enableDiffuse" ].value = true;
  10628. }
  10629. if ( m.parameters.lightMap ) {
  10630. uniforms[ "tAO" ].texture = m.parameters.lightMap;
  10631. uniforms[ "enableAO" ].value = true;
  10632. }
  10633. if ( m.parameters.specularMap ) {
  10634. uniforms[ "tSpecular" ].texture = result.textures[ m.parameters.specularMap ];
  10635. uniforms[ "enableSpecular" ].value = true;
  10636. }
  10637. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  10638. uniforms[ "uSpecularColor" ].value.setHex( specular );
  10639. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  10640. uniforms[ "uShininess" ].value = shininess;
  10641. if ( m.parameters.opacity ) {
  10642. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  10643. }
  10644. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  10645. material = new THREE.ShaderMaterial( parameters );
  10646. } else {
  10647. material = new THREE[ m.type ]( m.parameters );
  10648. }
  10649. result.materials[ dm ] = material;
  10650. }
  10651. // objects ( synchronous init of procedural primitives )
  10652. handle_objects();
  10653. // synchronous callback
  10654. scope.callbackSync( result );
  10655. // just in case there are no async elements:
  10656. async_callback_gate();
  10657. };
  10658. /**
  10659. * Loader for UTF8 encoded models generated by:
  10660. * http://code.google.com/p/webgl-loader/
  10661. *
  10662. * Limitations:
  10663. * - number of vertices < 65536 (this is after optimizations in compressor, input OBJ may have even less)
  10664. * - models must have normals and texture coordinates
  10665. * - texture coordinates must be only from <0,1>
  10666. * - no materials support yet
  10667. * - models are scaled and offset (copy numbers from compressor and use them as parameters in UTF8Loader.load() )
  10668. *
  10669. * @author alteredq / http://alteredqualia.com/
  10670. * @author won3d / http://twitter.com/won3d
  10671. */
  10672. THREE.UTF8Loader = function () {};
  10673. THREE.UTF8Loader.prototype.load = function ( url, callback, metadata ) {
  10674. var xhr = new XMLHttpRequest(),
  10675. callbackProgress = null,
  10676. scale = metadata.scale !== undefined ? metadata.scale : 1,
  10677. offsetX = metadata.offsetX !== undefined ? metadata.offsetX : 0,
  10678. offsetY = metadata.offsetY !== undefined ? metadata.offsetY : 0,
  10679. offsetZ = metadata.offsetZ !== undefined ? metadata.offsetZ : 0;
  10680. var length = 0;
  10681. xhr.onreadystatechange = function() {
  10682. if ( xhr.readyState == 4 ) {
  10683. if ( xhr.status == 200 || xhr.status == 0 ) {
  10684. THREE.UTF8Loader.prototype.createModel( xhr.responseText, callback, scale, offsetX, offsetY, offsetZ );
  10685. } else {
  10686. console.error( "THREE.UTF8Loader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  10687. }
  10688. } else if ( xhr.readyState == 3 ) {
  10689. if ( callbackProgress ) {
  10690. if ( length == 0 ) {
  10691. length = xhr.getResponseHeader( "Content-Length" );
  10692. }
  10693. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  10694. }
  10695. } else if ( xhr.readyState == 2 ) {
  10696. length = xhr.getResponseHeader( "Content-Length" );
  10697. }
  10698. }
  10699. xhr.open( "GET", url, true );
  10700. xhr.send( null );
  10701. };
  10702. // UTF-8 decoder from webgl-loader
  10703. // http://code.google.com/p/webgl-loader/
  10704. // Copyright 2011 Google Inc. All Rights Reserved.
  10705. //
  10706. // Licensed under the Apache License, Version 2.0 (the "License"); you
  10707. // may not use this file except in compliance with the License. You
  10708. // may obtain a copy of the License at
  10709. //
  10710. // http://www.apache.org/licenses/LICENSE-2.0
  10711. //
  10712. // Unless required by applicable law or agreed to in writing, software
  10713. // distributed under the License is distributed on an "AS IS" BASIS,
  10714. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  10715. // implied. See the License for the specific language governing
  10716. // permissions and limitations under the License.
  10717. THREE.UTF8Loader.prototype.decompressMesh = function ( str ) {
  10718. var num_verts = str.charCodeAt( 0 );
  10719. if ( num_verts >= 0xE000 ) {
  10720. num_verts -= 0x0800;
  10721. }
  10722. num_verts ++;
  10723. var attribs_out = new Float32Array( 8 * num_verts );
  10724. var offset = 1;
  10725. for ( var i = 0; i < 8; i ++ ) {
  10726. var prev_attrib = 0;
  10727. for ( var j = 0; j < num_verts; ++ j ) {
  10728. var code = str.charCodeAt( j + offset );
  10729. prev_attrib += ( code >> 1 ) ^ ( - ( code & 1 ) );
  10730. attribs_out[ 8 * j + i ] = prev_attrib;
  10731. }
  10732. offset += num_verts;
  10733. }
  10734. var num_indices = str.length - offset;
  10735. var indices_out = new Uint16Array( num_indices );
  10736. var index_high_water_mark = 0;
  10737. for ( var i = 0; i < num_indices; i ++ ) {
  10738. var code = str.charCodeAt( i + offset );
  10739. indices_out[ i ] = index_high_water_mark - code;
  10740. if ( code == 0 ) {
  10741. index_high_water_mark ++;
  10742. }
  10743. }
  10744. return [ attribs_out, indices_out ];
  10745. };
  10746. THREE.UTF8Loader.prototype.createModel = function ( data, callback, scale, offsetX, offsetY, offsetZ ) {
  10747. var Model = function ( texture_path ) {
  10748. //var s = (new Date).getTime();
  10749. var scope = this;
  10750. scope.materials = [];
  10751. THREE.Geometry.call( this );
  10752. var buffers = THREE.UTF8Loader.prototype.decompressMesh( data );
  10753. var normals = [],
  10754. uvs = [];
  10755. init_vertices( buffers[ 0 ], 8, 0 );
  10756. init_uvs( buffers[ 0 ], 8, 3 );
  10757. init_normals( buffers[ 0 ], 8, 5 );
  10758. init_faces( buffers[ 1 ] );
  10759. this.computeCentroids();
  10760. this.computeFaceNormals();
  10761. //this.computeTangents();
  10762. //var e = (new Date).getTime();
  10763. //console.log( "utf8 data parse time: " + (e-s) + " ms" );
  10764. function init_vertices( data, stride, offset ) {
  10765. var i, x, y, z,
  10766. end = data.length;
  10767. for( i = offset; i < end; i += stride ) {
  10768. x = data[ i ];
  10769. y = data[ i + 1 ];
  10770. z = data[ i + 2 ];
  10771. // fix scale and offsets
  10772. x = ( x / 16383 ) * scale;
  10773. y = ( y / 16383 ) * scale;
  10774. z = ( z / 16383 ) * scale;
  10775. x += offsetX;
  10776. y += offsetY;
  10777. z += offsetZ;
  10778. vertex( scope, x, y, z );
  10779. }
  10780. };
  10781. function init_normals( data, stride, offset ) {
  10782. var i, x, y, z,
  10783. end = data.length;
  10784. for( i = offset; i < end; i += stride ) {
  10785. x = data[ i ];
  10786. y = data[ i + 1 ];
  10787. z = data[ i + 2 ];
  10788. // normalize to <-1,1>
  10789. x = ( x - 512 ) / 511;
  10790. y = ( y - 512 ) / 511;
  10791. z = ( z - 512 ) / 511;
  10792. normals.push( x, y, z );
  10793. }
  10794. };
  10795. function init_uvs( data, stride, offset ) {
  10796. var i, u, v,
  10797. end = data.length;
  10798. for( i = offset; i < end; i += stride ) {
  10799. u = data[ i ];
  10800. v = data[ i + 1 ];
  10801. // normalize to <0,1>
  10802. u /= 1023;
  10803. v /= 1023;
  10804. uvs.push( u, 1 - v );
  10805. }
  10806. };
  10807. function init_faces( indices ) {
  10808. var i,
  10809. a, b, c,
  10810. u1, v1, u2, v2, u3, v3,
  10811. m,
  10812. end = indices.length;
  10813. m = 0; // all faces defaulting to material 0
  10814. for( i = 0; i < end; i += 3 ) {
  10815. a = indices[ i ];
  10816. b = indices[ i + 1 ];
  10817. c = indices[ i + 2 ];
  10818. f3n( scope, normals, a, b, c, m, a, b, c );
  10819. u1 = uvs[ a * 2 ];
  10820. v1 = uvs[ a * 2 + 1 ];
  10821. u2 = uvs[ b * 2 ];
  10822. v2 = uvs[ b * 2 + 1 ];
  10823. u3 = uvs[ c * 2 ];
  10824. v3 = uvs[ c * 2 + 1 ];
  10825. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  10826. }
  10827. }
  10828. };
  10829. function vertex ( scope, x, y, z ) {
  10830. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  10831. };
  10832. function f3n ( scope, normals, a, b, c, mi, nai, nbi, nci ) {
  10833. var nax = normals[ nai * 3 ],
  10834. nay = normals[ nai * 3 + 1 ],
  10835. naz = normals[ nai * 3 + 2 ],
  10836. nbx = normals[ nbi * 3 ],
  10837. nby = normals[ nbi * 3 + 1 ],
  10838. nbz = normals[ nbi * 3 + 2 ],
  10839. ncx = normals[ nci * 3 ],
  10840. ncy = normals[ nci * 3 + 1 ],
  10841. ncz = normals[ nci * 3 + 2 ];
  10842. var na = new THREE.Vector3( nax, nay, naz ),
  10843. nb = new THREE.Vector3( nbx, nby, nbz ),
  10844. nc = new THREE.Vector3( ncx, ncy, ncz );
  10845. scope.faces.push( new THREE.Face3( a, b, c, [ na, nb, nc ], null, mi ) );
  10846. };
  10847. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  10848. var uv = [];
  10849. uv.push( new THREE.UV( u1, v1 ) );
  10850. uv.push( new THREE.UV( u2, v2 ) );
  10851. uv.push( new THREE.UV( u3, v3 ) );
  10852. where.push( uv );
  10853. };
  10854. Model.prototype = new THREE.Geometry();
  10855. Model.prototype.constructor = Model;
  10856. callback( new Model() );
  10857. };
  10858. /**
  10859. * @author alteredq / http://alteredqualia.com/
  10860. */
  10861. THREE.ImmediateRenderObject = function ( ) {
  10862. THREE.Object3D.call( this );
  10863. this.render = function( renderCallback ) {
  10864. };
  10865. };
  10866. THREE.ImmediateRenderObject.prototype = new THREE.Object3D();
  10867. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  10868. /**
  10869. * @author mikael emtinger / http://gomo.se/
  10870. * @author alteredq / http://alteredqualia.com/
  10871. */
  10872. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  10873. THREE.Object3D.call( this );
  10874. this.lensFlares = [];
  10875. this.positionScreen = new THREE.Vector3();
  10876. this.customUpdateCallback = undefined;
  10877. if( texture !== undefined ) {
  10878. this.add( texture, size, distance, blending, color );
  10879. }
  10880. };
  10881. THREE.LensFlare.prototype = new THREE.Object3D();
  10882. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  10883. THREE.LensFlare.prototype.supr = THREE.Object3D.prototype;
  10884. /*
  10885. * Add: adds another flare
  10886. */
  10887. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  10888. if( size === undefined ) size = -1;
  10889. if( distance === undefined ) distance = 0;
  10890. if( opacity === undefined ) opacity = 1;
  10891. if( color === undefined ) color = new THREE.Color( 0xffffff );
  10892. if( blending === undefined ) blending = THREE.NormalBlending;
  10893. distance = Math.min( distance, Math.max( 0, distance ) );
  10894. this.lensFlares.push( { texture: texture, // THREE.Texture
  10895. size: size, // size in pixels (-1 = use texture.width)
  10896. distance: distance, // distance (0-1) from light source (0=at light source)
  10897. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  10898. scale: 1, // scale
  10899. rotation: 1, // rotation
  10900. opacity: opacity, // opacity
  10901. color: color, // color
  10902. blending: blending } ); // blending
  10903. };
  10904. /*
  10905. * Update lens flares update positions on all flares based on the screen position
  10906. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  10907. */
  10908. THREE.LensFlare.prototype.updateLensFlares = function () {
  10909. var f, fl = this.lensFlares.length;
  10910. var flare;
  10911. var vecX = -this.positionScreen.x * 2;
  10912. var vecY = -this.positionScreen.y * 2;
  10913. for( f = 0; f < fl; f ++ ) {
  10914. flare = this.lensFlares[ f ];
  10915. flare.x = this.positionScreen.x + vecX * flare.distance;
  10916. flare.y = this.positionScreen.y + vecY * flare.distance;
  10917. flare.wantedRotation = flare.x * Math.PI * 0.25;
  10918. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  10919. }
  10920. };
  10921. /**
  10922. * @author alteredq / http://alteredqualia.com/
  10923. */
  10924. THREE.MorphBlendMesh = function( geometry, material ) {
  10925. THREE.Mesh.call( this, geometry, material );
  10926. this.animationsMap = {};
  10927. this.animationsList = [];
  10928. // prepare default animation
  10929. // (all frames played together in 1 second)
  10930. var numFrames = this.geometry.morphTargets.length;
  10931. var name = "__default";
  10932. var startFrame = 0;
  10933. var endFrame = numFrames - 1;
  10934. var fps = numFrames / 1;
  10935. this.createAnimation( name, startFrame, endFrame, fps );
  10936. this.setAnimationWeight( name, 1 );
  10937. };
  10938. THREE.MorphBlendMesh.prototype = new THREE.Mesh();
  10939. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  10940. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  10941. var animation = {
  10942. startFrame: start,
  10943. endFrame: end,
  10944. length: end - start + 1,
  10945. fps: fps,
  10946. duration: ( end - start ) / fps,
  10947. lastFrame: 0,
  10948. currentFrame: 0,
  10949. active: false,
  10950. time: 0,
  10951. direction: 1,
  10952. weight: 1,
  10953. directionBackwards: false,
  10954. mirroredLoop: false
  10955. };
  10956. this.animationsMap[ name ] = animation;
  10957. this.animationsList.push( animation );
  10958. };
  10959. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  10960. var pattern = /([a-z]+)(\d+)/;
  10961. var firstAnimation, frameRanges = {};
  10962. var geometry = this.geometry;
  10963. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  10964. var morph = geometry.morphTargets[ i ];
  10965. var chunks = morph.name.match( pattern );
  10966. if ( chunks && chunks.length > 1 ) {
  10967. var name = chunks[ 1 ];
  10968. var num = chunks[ 2 ];
  10969. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  10970. var range = frameRanges[ name ];
  10971. if ( i < range.start ) range.start = i;
  10972. if ( i > range.end ) range.end = i;
  10973. if ( ! firstAnimation ) firstAnimation = name;
  10974. }
  10975. }
  10976. for ( var name in frameRanges ) {
  10977. var range = frameRanges[ name ];
  10978. this.createAnimation( name, range.start, range.end, fps );
  10979. }
  10980. this.firstAnimation = firstAnimation;
  10981. };
  10982. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  10983. var animation = this.animationsMap[ name ];
  10984. if ( animation ) {
  10985. animation.direction = 1;
  10986. animation.directionBackwards = false;
  10987. }
  10988. };
  10989. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  10990. var animation = this.animationsMap[ name ];
  10991. if ( animation ) {
  10992. animation.direction = -1;
  10993. animation.directionBackwards = true;
  10994. }
  10995. };
  10996. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  10997. var animation = this.animationsMap[ name ];
  10998. if ( animation ) {
  10999. animation.fps = fps;
  11000. animation.duration = ( animation.end - animation.start ) / animation.fps;
  11001. }
  11002. };
  11003. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  11004. var animation = this.animationsMap[ name ];
  11005. if ( animation ) {
  11006. animation.duration = duration;
  11007. animation.fps = ( animation.end - animation.start ) / animation.duration;
  11008. }
  11009. };
  11010. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  11011. var animation = this.animationsMap[ name ];
  11012. if ( animation ) {
  11013. animation.weight = weight;
  11014. }
  11015. };
  11016. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  11017. var animation = this.animationsMap[ name ];
  11018. if ( animation ) {
  11019. animation.time = time;
  11020. }
  11021. };
  11022. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  11023. var time = 0;
  11024. var animation = this.animationsMap[ name ];
  11025. if ( animation ) {
  11026. time = animation.time;
  11027. }
  11028. return time;
  11029. };
  11030. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  11031. var duration = -1;
  11032. var animation = this.animationsMap[ name ];
  11033. if ( animation ) {
  11034. duration = animation.duration;
  11035. }
  11036. return duration;
  11037. };
  11038. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  11039. var animation = this.animationsMap[ name ];
  11040. if ( animation ) {
  11041. animation.time = 0;
  11042. animation.active = true;
  11043. } else {
  11044. console.warn( "animation[" + name + "] undefined" );
  11045. }
  11046. };
  11047. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  11048. var animation = this.animationsMap[ name ];
  11049. if ( animation ) {
  11050. animation.active = false;
  11051. }
  11052. };
  11053. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  11054. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  11055. var animation = this.animationsList[ i ];
  11056. if ( ! animation.active ) continue;
  11057. var frameTime = animation.duration / animation.length;
  11058. animation.time += animation.direction * delta;
  11059. if ( animation.mirroredLoop ) {
  11060. if ( animation.time > animation.duration || animation.time < 0 ) {
  11061. animation.direction *= -1;
  11062. if ( animation.time > animation.duration ) {
  11063. animation.time = animation.duration;
  11064. animation.directionBackwards = true;
  11065. }
  11066. if ( animation.time < 0 ) {
  11067. animation.time = 0;
  11068. animation.directionBackwards = false;
  11069. }
  11070. }
  11071. } else {
  11072. animation.time = animation.time % animation.duration;
  11073. if ( animation.time < 0 ) animation.time += animation.duration;
  11074. }
  11075. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  11076. var weight = animation.weight;
  11077. if ( keyframe !== animation.currentFrame ) {
  11078. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  11079. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  11080. this.morphTargetInfluences[ keyframe ] = 0;
  11081. animation.lastFrame = animation.currentFrame;
  11082. animation.currentFrame = keyframe;
  11083. }
  11084. var mix = ( animation.time % frameTime ) / frameTime;
  11085. if ( animation.directionBackwards ) mix = 1 - mix;
  11086. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  11087. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  11088. }
  11089. };
  11090. /**
  11091. * @author mikael emtinger / http://gomo.se/
  11092. * @author alteredq / http://alteredqualia.com/
  11093. */
  11094. THREE.LensFlarePlugin = function ( ) {
  11095. var _gl, _renderer, _lensFlare = {};
  11096. this.init = function ( renderer ) {
  11097. _gl = renderer.context;
  11098. _renderer = renderer;
  11099. _lensFlare.vertices = new Float32Array( 8 + 8 );
  11100. _lensFlare.faces = new Uint16Array( 6 );
  11101. var i = 0;
  11102. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  11103. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  11104. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  11105. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  11106. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  11107. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  11108. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  11109. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  11110. i = 0;
  11111. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  11112. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  11113. // buffers
  11114. _lensFlare.vertexBuffer = _gl.createBuffer();
  11115. _lensFlare.elementBuffer = _gl.createBuffer();
  11116. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  11117. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  11118. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  11119. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  11120. // textures
  11121. _lensFlare.tempTexture = _gl.createTexture();
  11122. _lensFlare.occlusionTexture = _gl.createTexture();
  11123. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  11124. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  11125. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  11126. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  11127. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  11128. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  11129. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  11130. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  11131. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  11132. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  11133. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  11134. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  11135. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  11136. _lensFlare.hasVertexTexture = false;
  11137. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  11138. } else {
  11139. _lensFlare.hasVertexTexture = true;
  11140. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  11141. }
  11142. _lensFlare.attributes = {};
  11143. _lensFlare.uniforms = {};
  11144. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  11145. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  11146. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  11147. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  11148. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  11149. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  11150. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  11151. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  11152. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  11153. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  11154. _lensFlare.attributesEnabled = false;
  11155. };
  11156. /*
  11157. * Render lens flares
  11158. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  11159. * reads these back and calculates occlusion.
  11160. * Then _lensFlare.update_lensFlares() is called to re-position and
  11161. * update transparency of flares. Then they are rendered.
  11162. *
  11163. */
  11164. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  11165. var flares = scene.__webglFlares,
  11166. nFlares = flares.length;
  11167. if ( ! nFlares ) return;
  11168. var tempPosition = new THREE.Vector3();
  11169. var invAspect = viewportHeight / viewportWidth,
  11170. halfViewportWidth = viewportWidth * 0.5,
  11171. halfViewportHeight = viewportHeight * 0.5;
  11172. var size = 16 / viewportHeight,
  11173. scale = new THREE.Vector2( size * invAspect, size );
  11174. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  11175. screenPositionPixels = new THREE.Vector2( 1, 1 );
  11176. var uniforms = _lensFlare.uniforms,
  11177. attributes = _lensFlare.attributes;
  11178. // set _lensFlare program and reset blending
  11179. _gl.useProgram( _lensFlare.program );
  11180. if ( ! _lensFlare.attributesEnabled ) {
  11181. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  11182. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  11183. _lensFlare.attributesEnabled = true;
  11184. }
  11185. // loop through all lens flares to update their occlusion and positions
  11186. // setup gl and common used attribs/unforms
  11187. _gl.uniform1i( uniforms.occlusionMap, 0 );
  11188. _gl.uniform1i( uniforms.map, 1 );
  11189. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  11190. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  11191. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  11192. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  11193. _gl.disable( _gl.CULL_FACE );
  11194. _gl.depthMask( false );
  11195. var i, j, jl, flare, sprite;
  11196. for ( i = 0; i < nFlares; i ++ ) {
  11197. size = 16 / viewportHeight;
  11198. scale.set( size * invAspect, size );
  11199. // calc object screen position
  11200. flare = flares[ i ];
  11201. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  11202. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  11203. camera.projectionMatrix.multiplyVector3( tempPosition );
  11204. // setup arrays for gl programs
  11205. screenPosition.copy( tempPosition )
  11206. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  11207. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  11208. // screen cull
  11209. if ( _lensFlare.hasVertexTexture || (
  11210. screenPositionPixels.x > 0 &&
  11211. screenPositionPixels.x < viewportWidth &&
  11212. screenPositionPixels.y > 0 &&
  11213. screenPositionPixels.y < viewportHeight ) ) {
  11214. // save current RGB to temp texture
  11215. _gl.activeTexture( _gl.TEXTURE1 );
  11216. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  11217. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  11218. // render pink quad
  11219. _gl.uniform1i( uniforms.renderType, 0 );
  11220. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  11221. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  11222. _gl.disable( _gl.BLEND );
  11223. _gl.enable( _gl.DEPTH_TEST );
  11224. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  11225. // copy result to occlusionMap
  11226. _gl.activeTexture( _gl.TEXTURE0 );
  11227. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  11228. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  11229. // restore graphics
  11230. _gl.uniform1i( uniforms.renderType, 1 );
  11231. _gl.disable( _gl.DEPTH_TEST );
  11232. _gl.activeTexture( _gl.TEXTURE1 );
  11233. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  11234. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  11235. // update object positions
  11236. flare.positionScreen.copy( screenPosition )
  11237. if ( flare.customUpdateCallback ) {
  11238. flare.customUpdateCallback( flare );
  11239. } else {
  11240. flare.updateLensFlares();
  11241. }
  11242. // render flares
  11243. _gl.uniform1i( uniforms.renderType, 2 );
  11244. _gl.enable( _gl.BLEND );
  11245. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  11246. sprite = flare.lensFlares[ j ];
  11247. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  11248. screenPosition.x = sprite.x;
  11249. screenPosition.y = sprite.y;
  11250. screenPosition.z = sprite.z;
  11251. size = sprite.size * sprite.scale / viewportHeight;
  11252. scale.x = size * invAspect;
  11253. scale.y = size;
  11254. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  11255. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  11256. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  11257. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  11258. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  11259. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  11260. _renderer.setTexture( sprite.texture, 1 );
  11261. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  11262. }
  11263. }
  11264. }
  11265. }
  11266. // restore gl
  11267. _gl.enable( _gl.CULL_FACE );
  11268. _gl.enable( _gl.DEPTH_TEST );
  11269. _gl.depthMask( true );
  11270. };
  11271. function createProgram ( shader ) {
  11272. var program = _gl.createProgram();
  11273. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  11274. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  11275. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  11276. _gl.shaderSource( vertexShader, shader.vertexShader );
  11277. _gl.compileShader( fragmentShader );
  11278. _gl.compileShader( vertexShader );
  11279. _gl.attachShader( program, fragmentShader );
  11280. _gl.attachShader( program, vertexShader );
  11281. _gl.linkProgram( program );
  11282. return program;
  11283. };
  11284. };/**
  11285. * @author alteredq / http://alteredqualia.com/
  11286. */
  11287. THREE.ShadowMapPlugin = function ( ) {
  11288. var _gl,
  11289. _renderer,
  11290. _depthMaterial, _depthMaterialMorph,
  11291. _frustum = new THREE.Frustum(),
  11292. _projScreenMatrix = new THREE.Matrix4(),
  11293. _min = new THREE.Vector3(),
  11294. _max = new THREE.Vector3();
  11295. this.init = function ( renderer ) {
  11296. _gl = renderer.context;
  11297. _renderer = renderer;
  11298. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  11299. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  11300. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  11301. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  11302. _depthMaterial._shadowPass = true;
  11303. _depthMaterialMorph._shadowPass = true;
  11304. };
  11305. this.render = function ( scene, camera ) {
  11306. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  11307. this.update( scene, camera );
  11308. };
  11309. this.update = function ( scene, camera ) {
  11310. var i, il, j, jl, n,
  11311. shadowMap, shadowMatrix, shadowCamera,
  11312. program, buffer, material,
  11313. webglObject, object, light,
  11314. renderList,
  11315. lights = [],
  11316. k = 0,
  11317. fog = null;
  11318. // set GL state for depth map
  11319. _gl.clearColor( 1, 1, 1, 1 );
  11320. _gl.disable( _gl.BLEND );
  11321. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.FRONT );
  11322. _renderer.setDepthTest( true );
  11323. // preprocess lights
  11324. // - skip lights that are not casting shadows
  11325. // - create virtual lights for cascaded shadow maps
  11326. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  11327. light = scene.__lights[ i ];
  11328. if ( ! light.castShadow ) continue;
  11329. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  11330. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  11331. var virtualLight;
  11332. if ( ! light.shadowCascadeArray[ n ] ) {
  11333. virtualLight = createVirtualLight( light, n );
  11334. virtualLight.originalCamera = camera;
  11335. var gyro = new THREE.Gyroscope();
  11336. gyro.position = light.shadowCascadeOffset;
  11337. gyro.add( virtualLight );
  11338. gyro.add( virtualLight.target );
  11339. camera.add( gyro );
  11340. light.shadowCascadeArray[ n ] = virtualLight;
  11341. console.log( "Created virtualLight", virtualLight );
  11342. } else {
  11343. virtualLight = light.shadowCascadeArray[ n ];
  11344. }
  11345. updateVirtualLight( light, n );
  11346. lights[ k ] = virtualLight;
  11347. k ++;
  11348. }
  11349. } else {
  11350. lights[ k ] = light;
  11351. k ++;
  11352. }
  11353. }
  11354. // render depth map
  11355. for ( i = 0, il = lights.length; i < il; i ++ ) {
  11356. light = lights[ i ];
  11357. if ( ! light.shadowMap ) {
  11358. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  11359. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  11360. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  11361. light.shadowMatrix = new THREE.Matrix4();
  11362. }
  11363. if ( ! light.shadowCamera ) {
  11364. if ( light instanceof THREE.SpotLight ) {
  11365. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  11366. } else if ( light instanceof THREE.DirectionalLight ) {
  11367. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  11368. } else {
  11369. console.error( "Unsupported light type for shadow" );
  11370. continue;
  11371. }
  11372. scene.add( light.shadowCamera );
  11373. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  11374. }
  11375. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  11376. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  11377. light.shadowCamera.add( light.cameraHelper );
  11378. }
  11379. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  11380. updateShadowCamera( camera, light );
  11381. }
  11382. shadowMap = light.shadowMap;
  11383. shadowMatrix = light.shadowMatrix;
  11384. shadowCamera = light.shadowCamera;
  11385. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  11386. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  11387. shadowCamera.updateMatrixWorld();
  11388. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  11389. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  11390. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  11391. // compute shadow matrix
  11392. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  11393. 0.0, 0.5, 0.0, 0.5,
  11394. 0.0, 0.0, 0.5, 0.5,
  11395. 0.0, 0.0, 0.0, 1.0 );
  11396. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  11397. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  11398. // update camera matrices and frustum
  11399. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  11400. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  11401. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  11402. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  11403. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  11404. _frustum.setFromMatrix( _projScreenMatrix );
  11405. // render shadow map
  11406. _renderer.setRenderTarget( shadowMap );
  11407. _renderer.clear();
  11408. // set object matrices & frustum culling
  11409. renderList = scene.__webglObjects;
  11410. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11411. webglObject = renderList[ j ];
  11412. object = webglObject.object;
  11413. webglObject.render = false;
  11414. if ( object.visible && object.castShadow ) {
  11415. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11416. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  11417. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  11418. webglObject.render = true;
  11419. }
  11420. }
  11421. }
  11422. // render regular objects
  11423. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11424. webglObject = renderList[ j ];
  11425. if ( webglObject.render ) {
  11426. object = webglObject.object;
  11427. buffer = webglObject.buffer;
  11428. _renderer.setObjectFaces( object );
  11429. if ( object.customDepthMaterial ) {
  11430. material = object.customDepthMaterial;
  11431. } else if ( object.geometry.morphTargets.length ) {
  11432. material = _depthMaterialMorph;
  11433. } else {
  11434. material = _depthMaterial;
  11435. }
  11436. if ( buffer instanceof THREE.BufferGeometry ) {
  11437. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  11438. } else {
  11439. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  11440. }
  11441. }
  11442. }
  11443. // set matrices and render immediate objects
  11444. renderList = scene.__webglObjectsImmediate;
  11445. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11446. webglObject = renderList[ j ];
  11447. object = webglObject.object;
  11448. if ( object.visible && object.castShadow ) {
  11449. /*
  11450. if ( object.matrixAutoUpdate ) {
  11451. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  11452. }
  11453. */
  11454. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  11455. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  11456. }
  11457. }
  11458. }
  11459. // restore GL state
  11460. var clearColor = _renderer.getClearColor(),
  11461. clearAlpha = _renderer.getClearAlpha();
  11462. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  11463. _gl.enable( _gl.BLEND );
  11464. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.BACK );
  11465. };
  11466. function createVirtualLight( light, cascade ) {
  11467. var virtualLight = new THREE.DirectionalLight();
  11468. virtualLight.isVirtual = true;
  11469. virtualLight.onlyShadow = true;
  11470. virtualLight.castShadow = true;
  11471. virtualLight.shadowCameraNear = light.shadowCameraNear;
  11472. virtualLight.shadowCameraFar = light.shadowCameraFar;
  11473. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  11474. virtualLight.shadowCameraRight = light.shadowCameraRight;
  11475. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  11476. virtualLight.shadowCameraTop = light.shadowCameraTop;
  11477. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  11478. virtualLight.shadowDarkness = light.shadowDarkness;
  11479. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  11480. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  11481. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  11482. virtualLight.pointsWorld = [];
  11483. virtualLight.pointsFrustum = [];
  11484. var pointsWorld = virtualLight.pointsWorld,
  11485. pointsFrustum = virtualLight.pointsFrustum;
  11486. for ( var i = 0; i < 8; i ++ ) {
  11487. pointsWorld[ i ] = new THREE.Vector3();
  11488. pointsFrustum[ i ] = new THREE.Vector3();
  11489. }
  11490. var nearZ = light.shadowCascadeNearZ[ cascade ];
  11491. var farZ = light.shadowCascadeFarZ[ cascade ];
  11492. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  11493. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  11494. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  11495. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  11496. pointsFrustum[ 4 ].set( -1, -1, farZ );
  11497. pointsFrustum[ 5 ].set( 1, -1, farZ );
  11498. pointsFrustum[ 6 ].set( -1, 1, farZ );
  11499. pointsFrustum[ 7 ].set( 1, 1, farZ );
  11500. return virtualLight;
  11501. }
  11502. // Synchronize virtual light with the original light
  11503. function updateVirtualLight( light, cascade ) {
  11504. var virtualLight = light.shadowCascadeArray[ cascade ];
  11505. virtualLight.position.copy( light.position );
  11506. virtualLight.target.position.copy( light.target.position );
  11507. virtualLight.lookAt( virtualLight.target );
  11508. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  11509. virtualLight.shadowDarkness = light.shadowDarkness;
  11510. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  11511. var nearZ = light.shadowCascadeNearZ[ cascade ];
  11512. var farZ = light.shadowCascadeFarZ[ cascade ];
  11513. var pointsFrustum = virtualLight.pointsFrustum;
  11514. pointsFrustum[ 0 ].z = nearZ;
  11515. pointsFrustum[ 1 ].z = nearZ;
  11516. pointsFrustum[ 2 ].z = nearZ;
  11517. pointsFrustum[ 3 ].z = nearZ;
  11518. pointsFrustum[ 4 ].z = farZ;
  11519. pointsFrustum[ 5 ].z = farZ;
  11520. pointsFrustum[ 6 ].z = farZ;
  11521. pointsFrustum[ 7 ].z = farZ;
  11522. }
  11523. // Fit shadow camera's ortho frustum to camera frustum
  11524. function updateShadowCamera( camera, light ) {
  11525. var shadowCamera = light.shadowCamera,
  11526. pointsFrustum = light.pointsFrustum,
  11527. pointsWorld = light.pointsWorld;
  11528. _min.set( Infinity, Infinity, Infinity );
  11529. _max.set( -Infinity, -Infinity, -Infinity );
  11530. for ( var i = 0; i < 8; i ++ ) {
  11531. var p = pointsWorld[ i ];
  11532. p.copy( pointsFrustum[ i ] );
  11533. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  11534. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  11535. if ( p.x < _min.x ) _min.x = p.x;
  11536. if ( p.x > _max.x ) _max.x = p.x;
  11537. if ( p.y < _min.y ) _min.y = p.y;
  11538. if ( p.y > _max.y ) _max.y = p.y;
  11539. if ( p.z < _min.z ) _min.z = p.z;
  11540. if ( p.z > _max.z ) _max.z = p.z;
  11541. }
  11542. shadowCamera.left = _min.x;
  11543. shadowCamera.right = _max.x;
  11544. shadowCamera.top = _max.y;
  11545. shadowCamera.bottom = _min.y;
  11546. // can't really fit near/far
  11547. //shadowCamera.near = _min.z;
  11548. //shadowCamera.far = _max.z;
  11549. shadowCamera.updateProjectionMatrix();
  11550. }
  11551. };
  11552. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  11553. /**
  11554. * @author mikael emtinger / http://gomo.se/
  11555. * @author alteredq / http://alteredqualia.com/
  11556. */
  11557. THREE.SpritePlugin = function ( ) {
  11558. var _gl, _renderer, _sprite = {};
  11559. this.init = function ( renderer ) {
  11560. _gl = renderer.context;
  11561. _renderer = renderer;
  11562. _sprite.vertices = new Float32Array( 8 + 8 );
  11563. _sprite.faces = new Uint16Array( 6 );
  11564. var i = 0;
  11565. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  11566. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 0
  11567. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  11568. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 1
  11569. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  11570. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 2
  11571. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  11572. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 3
  11573. i = 0;
  11574. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  11575. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  11576. _sprite.vertexBuffer = _gl.createBuffer();
  11577. _sprite.elementBuffer = _gl.createBuffer();
  11578. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  11579. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  11580. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  11581. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  11582. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  11583. _sprite.attributes = {};
  11584. _sprite.uniforms = {};
  11585. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  11586. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  11587. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  11588. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  11589. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  11590. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  11591. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  11592. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  11593. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  11594. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  11595. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  11596. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  11597. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  11598. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  11599. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  11600. _sprite.attributesEnabled = false;
  11601. };
  11602. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  11603. var sprites = scene.__webglSprites,
  11604. nSprites = sprites.length;
  11605. if ( ! nSprites ) return;
  11606. var attributes = _sprite.attributes,
  11607. uniforms = _sprite.uniforms;
  11608. var invAspect = viewportHeight / viewportWidth;
  11609. var halfViewportWidth = viewportWidth * 0.5,
  11610. halfViewportHeight = viewportHeight * 0.5;
  11611. var mergeWith3D = true;
  11612. // setup gl
  11613. _gl.useProgram( _sprite.program );
  11614. if ( ! _sprite.attributesEnabled ) {
  11615. _gl.enableVertexAttribArray( attributes.position );
  11616. _gl.enableVertexAttribArray( attributes.uv );
  11617. _sprite.attributesEnabled = true;
  11618. }
  11619. _gl.disable( _gl.CULL_FACE );
  11620. _gl.enable( _gl.BLEND );
  11621. _gl.depthMask( true );
  11622. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  11623. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  11624. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  11625. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  11626. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  11627. _gl.activeTexture( _gl.TEXTURE0 );
  11628. _gl.uniform1i( uniforms.map, 0 );
  11629. // update positions and sort
  11630. var i, sprite, screenPosition, size, scale = [];
  11631. for( i = 0; i < nSprites; i ++ ) {
  11632. sprite = sprites[ i ];
  11633. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  11634. if( ! sprite.useScreenCoordinates ) {
  11635. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld);
  11636. sprite.z = - sprite._modelViewMatrix.elements[14];
  11637. } else {
  11638. sprite.z = - sprite.position.z;
  11639. }
  11640. }
  11641. sprites.sort( painterSort );
  11642. // render all sprites
  11643. for( i = 0; i < nSprites; i ++ ) {
  11644. sprite = sprites[ i ];
  11645. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  11646. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  11647. if ( sprite.useScreenCoordinates ) {
  11648. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  11649. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  11650. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  11651. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  11652. } else {
  11653. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  11654. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  11655. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements);
  11656. }
  11657. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  11658. scale[ 0 ] = size * invAspect * sprite.scale.x;
  11659. scale[ 1 ] = size * sprite.scale.y;
  11660. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  11661. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  11662. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  11663. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  11664. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  11665. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  11666. _gl.uniform2fv( uniforms.scale, scale );
  11667. if ( sprite.mergeWith3D && !mergeWith3D ) {
  11668. _gl.enable( _gl.DEPTH_TEST );
  11669. mergeWith3D = true;
  11670. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  11671. _gl.disable( _gl.DEPTH_TEST );
  11672. mergeWith3D = false;
  11673. }
  11674. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  11675. _renderer.setTexture( sprite.map, 0 );
  11676. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  11677. }
  11678. }
  11679. // restore gl
  11680. _gl.enable( _gl.CULL_FACE );
  11681. _gl.enable( _gl.DEPTH_TEST );
  11682. _gl.depthMask( true );
  11683. };
  11684. function createProgram ( shader ) {
  11685. var program = _gl.createProgram();
  11686. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  11687. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  11688. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  11689. _gl.shaderSource( vertexShader, shader.vertexShader );
  11690. _gl.compileShader( fragmentShader );
  11691. _gl.compileShader( vertexShader );
  11692. _gl.attachShader( program, fragmentShader );
  11693. _gl.attachShader( program, vertexShader );
  11694. _gl.linkProgram( program );
  11695. return program;
  11696. };
  11697. function painterSort ( a, b ) {
  11698. return b.z - a.z;
  11699. };
  11700. };/**
  11701. * @author alteredq / http://alteredqualia.com/
  11702. */
  11703. THREE.DepthPassPlugin = function ( ) {
  11704. this.enabled = false;
  11705. this.renderTarget = null;
  11706. var _gl,
  11707. _renderer,
  11708. _depthMaterial, _depthMaterialMorph,
  11709. _frustum = new THREE.Frustum(),
  11710. _projScreenMatrix = new THREE.Matrix4();
  11711. this.init = function ( renderer ) {
  11712. _gl = renderer.context;
  11713. _renderer = renderer;
  11714. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  11715. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  11716. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  11717. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  11718. _depthMaterial._shadowPass = true;
  11719. _depthMaterialMorph._shadowPass = true;
  11720. };
  11721. this.render = function ( scene, camera ) {
  11722. if ( ! this.enabled ) return;
  11723. this.update( scene, camera );
  11724. };
  11725. this.update = function ( scene, camera ) {
  11726. var i, il, j, jl, n,
  11727. program, buffer, material,
  11728. webglObject, object, light,
  11729. renderList,
  11730. fog = null;
  11731. // set GL state for depth map
  11732. _gl.clearColor( 1, 1, 1, 1 );
  11733. _gl.disable( _gl.BLEND );
  11734. _renderer.setDepthTest( true );
  11735. // update scene
  11736. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  11737. // update camera matrices and frustum
  11738. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11739. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11740. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11741. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11742. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11743. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11744. _frustum.setFromMatrix( _projScreenMatrix );
  11745. // render depth map
  11746. _renderer.setRenderTarget( this.renderTarget );
  11747. _renderer.clear();
  11748. // set object matrices & frustum culling
  11749. renderList = scene.__webglObjects;
  11750. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11751. webglObject = renderList[ j ];
  11752. object = webglObject.object;
  11753. webglObject.render = false;
  11754. if ( object.visible ) {
  11755. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11756. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  11757. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  11758. webglObject.render = true;
  11759. }
  11760. }
  11761. }
  11762. // render regular objects
  11763. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11764. webglObject = renderList[ j ];
  11765. if ( webglObject.render ) {
  11766. object = webglObject.object;
  11767. buffer = webglObject.buffer;
  11768. _renderer.setObjectFaces( object );
  11769. if ( object.customDepthMaterial ) {
  11770. material = object.customDepthMaterial;
  11771. } else if ( object.geometry.morphTargets.length ) {
  11772. material = _depthMaterialMorph;
  11773. } else {
  11774. material = _depthMaterial;
  11775. }
  11776. if ( buffer instanceof THREE.BufferGeometry ) {
  11777. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  11778. } else {
  11779. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  11780. }
  11781. }
  11782. }
  11783. // set matrices and render immediate objects
  11784. renderList = scene.__webglObjectsImmediate;
  11785. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11786. webglObject = renderList[ j ];
  11787. object = webglObject.object;
  11788. if ( object.visible && object.castShadow ) {
  11789. /*
  11790. if ( object.matrixAutoUpdate ) {
  11791. object.matrixWorld.flattenToArray( object._objectMatrixArray );
  11792. }
  11793. */
  11794. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  11795. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  11796. }
  11797. }
  11798. // restore GL state
  11799. var clearColor = _renderer.getClearColor(),
  11800. clearAlpha = _renderer.getClearAlpha();
  11801. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  11802. _gl.enable( _gl.BLEND );
  11803. };
  11804. };
  11805. /**
  11806. * @author mrdoob / http://mrdoob.com/
  11807. * @author marklundin / http://mark-lundin.com/
  11808. * @author alteredq / http://alteredqualia.com/
  11809. */
  11810. if ( THREE.WebGLRenderer ) {
  11811. THREE.AnaglyphWebGLRenderer = function ( parameters ) {
  11812. THREE.WebGLRenderer.call( this, parameters );
  11813. this.autoUpdateScene = false;
  11814. var _this = this, _setSize = this.setSize, _render = this.render;
  11815. var _cameraL = new THREE.PerspectiveCamera(),
  11816. _cameraR = new THREE.PerspectiveCamera();
  11817. var eyeRight = new THREE.Matrix4(),
  11818. eyeLeft = new THREE.Matrix4(),
  11819. focalLength = 125,
  11820. _aspect, _near, _far, _fov;
  11821. _cameraL.matrixAutoUpdate = _cameraR.matrixAutoUpdate = false;
  11822. var _params = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  11823. var _renderTargetL = new THREE.WebGLRenderTarget( 512, 512, _params ),
  11824. _renderTargetR = new THREE.WebGLRenderTarget( 512, 512, _params );
  11825. var _camera = new THREE.PerspectiveCamera( 53, 1, 1, 10000 );
  11826. _camera.position.z = 2;
  11827. var _material = new THREE.ShaderMaterial( {
  11828. uniforms: {
  11829. "mapLeft": { type: "t", value: 0, texture: _renderTargetL },
  11830. "mapRight": { type: "t", value: 1, texture: _renderTargetR }
  11831. },
  11832. vertexShader: [
  11833. "varying vec2 vUv;",
  11834. "void main() {",
  11835. "vUv = vec2( uv.x, 1.0 - uv.y );",
  11836. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11837. "}"
  11838. ].join("\n"),
  11839. fragmentShader: [
  11840. "uniform sampler2D mapLeft;",
  11841. "uniform sampler2D mapRight;",
  11842. "varying vec2 vUv;",
  11843. "void main() {",
  11844. "vec4 colorL, colorR;",
  11845. "vec2 uv = vUv;",
  11846. "colorL = texture2D( mapLeft, uv );",
  11847. "colorR = texture2D( mapRight, uv );",
  11848. // http://3dtv.at/Knowhow/AnaglyphComparison_en.aspx
  11849. "gl_FragColor = vec4( colorL.g * 0.7 + colorL.b * 0.3, colorR.g, colorR.b, colorL.a + colorR.a ) * 1.1;",
  11850. "}"
  11851. ].join("\n")
  11852. } );
  11853. var _scene = new THREE.Scene();
  11854. var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), _material );
  11855. mesh.rotation.x = Math.PI / 2;
  11856. _scene.add( mesh );
  11857. _scene.add( _camera );
  11858. this.setSize = function ( width, height ) {
  11859. _setSize.call( _this, width, height );
  11860. _renderTargetL.width = width;
  11861. _renderTargetL.height = height;
  11862. _renderTargetR.width = width;
  11863. _renderTargetR.height = height;
  11864. };
  11865. /*
  11866. * Renderer now uses an asymmetric perspective projection (http://paulbourke.net/miscellaneous/stereographics/stereorender/).
  11867. * Each camera is offset by the eye seperation and its projection matrix is also skewed asymetrically back to converge on the same
  11868. * projection plane. Added a focal length parameter to, this is where the parallax is equal to 0.
  11869. */
  11870. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11871. scene.updateMatrixWorld();
  11872. var hasCameraChanged = ( _aspect !== camera.aspect ) || ( _near !== camera.near ) || ( _far !== camera.far ) || ( _fov !== camera.fov );
  11873. if( hasCameraChanged ) {
  11874. _aspect = camera.aspect;
  11875. _near = camera.near;
  11876. _far = camera.far;
  11877. _fov = camera.fov;
  11878. var projectionMatrix = camera.projectionMatrix.clone(),
  11879. eyeSep = focalLength / 30 * 0.5,
  11880. eyeSepOnProjection = eyeSep * _near / focalLength,
  11881. ymax = _near * Math.tan( _fov * Math.PI / 360 ),
  11882. xmin, xmax;
  11883. // translate xOffset
  11884. eyeRight.elements[12] = eyeSep;
  11885. eyeLeft.elements[12] = -eyeSep;
  11886. // for left eye
  11887. xmin = -ymax * _aspect + eyeSepOnProjection;
  11888. xmax = ymax * _aspect + eyeSepOnProjection;
  11889. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  11890. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  11891. _cameraL.projectionMatrix.copy( projectionMatrix );
  11892. // for right eye
  11893. xmin = -ymax * _aspect - eyeSepOnProjection;
  11894. xmax = ymax * _aspect - eyeSepOnProjection;
  11895. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  11896. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  11897. _cameraR.projectionMatrix.copy( projectionMatrix );
  11898. }
  11899. _cameraL.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeLeft );
  11900. _cameraL.position.copy( camera.position );
  11901. _cameraL.near = camera.near;
  11902. _cameraL.far = camera.far;
  11903. _render.call( _this, scene, _cameraL, _renderTargetL, true );
  11904. _cameraR.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeRight );
  11905. _cameraR.position.copy( camera.position );
  11906. _cameraR.near = camera.near;
  11907. _cameraR.far = camera.far;
  11908. _render.call( _this, scene, _cameraR, _renderTargetR, true );
  11909. _scene.updateMatrixWorld();
  11910. _render.call( _this, _scene, _camera );
  11911. };
  11912. };
  11913. };
  11914. /**
  11915. * @author alteredq / http://alteredqualia.com/
  11916. */
  11917. if ( THREE.WebGLRenderer ) {
  11918. THREE.CrosseyedWebGLRenderer = function ( parameters ) {
  11919. THREE.WebGLRenderer.call( this, parameters );
  11920. this.autoClear = false;
  11921. var _this = this, _setSize = this.setSize, _render = this.render;
  11922. var _width, _height;
  11923. var _cameraL = new THREE.PerspectiveCamera();
  11924. _cameraL.target = new THREE.Vector3( 0, 0, 0 );
  11925. var _cameraR = new THREE.PerspectiveCamera();
  11926. _cameraR.target = new THREE.Vector3( 0, 0, 0 );
  11927. _this.separation = 10;
  11928. if ( parameters && parameters.separation !== undefined ) _this.separation = parameters.separation;
  11929. var SCREEN_WIDTH = window.innerWidth;
  11930. var SCREEN_HEIGHT = window.innerHeight;
  11931. var HALF_WIDTH = SCREEN_WIDTH / 2;
  11932. this.setSize = function ( width, height ) {
  11933. _setSize.call( _this, width, height );
  11934. _width = width/2;
  11935. _height = height;
  11936. };
  11937. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11938. this.clear();
  11939. _cameraL.fov = camera.fov;
  11940. _cameraL.aspect = 0.5 * camera.aspect;
  11941. _cameraL.near = camera.near;
  11942. _cameraL.far = camera.far;
  11943. _cameraL.updateProjectionMatrix();
  11944. _cameraL.position.copy( camera.position );
  11945. _cameraL.target.copy( camera.target );
  11946. _cameraL.translateX( _this.separation );
  11947. _cameraL.lookAt( _cameraL.target );
  11948. _cameraR.projectionMatrix = _cameraL.projectionMatrix;
  11949. _cameraR.position.copy( camera.position );
  11950. _cameraR.target.copy( camera.target );
  11951. _cameraR.translateX( - _this.separation );
  11952. _cameraR.lookAt( _cameraR.target );
  11953. this.setViewport( 0, 0, _width, _height );
  11954. _render.call( _this, scene, _cameraL );
  11955. this.setViewport( _width, 0, _width, _height );
  11956. _render.call( _this, scene, _cameraR, false );
  11957. };
  11958. };
  11959. }
  11960. /**
  11961. * @author mikael emtinger / http://gomo.se/
  11962. *
  11963. */
  11964. THREE.ShaderFlares = {
  11965. 'lensFlareVertexTexture': {
  11966. vertexShader: [
  11967. "uniform vec3 screenPosition;",
  11968. "uniform vec2 scale;",
  11969. "uniform float rotation;",
  11970. "uniform int renderType;",
  11971. "uniform sampler2D occlusionMap;",
  11972. "attribute vec2 position;",
  11973. "attribute vec2 uv;",
  11974. "varying vec2 vUV;",
  11975. "varying float vVisibility;",
  11976. "void main() {",
  11977. "vUV = uv;",
  11978. "vec2 pos = position;",
  11979. "if( renderType == 2 ) {",
  11980. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  11981. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  11982. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  11983. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  11984. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  11985. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  11986. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  11987. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  11988. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  11989. "vVisibility = ( visibility.r / 9.0 ) *",
  11990. "( 1.0 - visibility.g / 9.0 ) *",
  11991. "( visibility.b / 9.0 ) *",
  11992. "( 1.0 - visibility.a / 9.0 );",
  11993. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  11994. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  11995. "}",
  11996. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  11997. "}"
  11998. ].join( "\n" ),
  11999. fragmentShader: [
  12000. "precision mediump float;",
  12001. "uniform sampler2D map;",
  12002. "uniform float opacity;",
  12003. "uniform int renderType;",
  12004. "uniform vec3 color;",
  12005. "varying vec2 vUV;",
  12006. "varying float vVisibility;",
  12007. "void main() {",
  12008. // pink square
  12009. "if( renderType == 0 ) {",
  12010. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  12011. // restore
  12012. "} else if( renderType == 1 ) {",
  12013. "gl_FragColor = texture2D( map, vUV );",
  12014. // flare
  12015. "} else {",
  12016. "vec4 texture = texture2D( map, vUV );",
  12017. "texture.a *= opacity * vVisibility;",
  12018. "gl_FragColor = texture;",
  12019. "gl_FragColor.rgb *= color;",
  12020. "}",
  12021. "}"
  12022. ].join( "\n" )
  12023. },
  12024. 'lensFlare': {
  12025. vertexShader: [
  12026. "uniform vec3 screenPosition;",
  12027. "uniform vec2 scale;",
  12028. "uniform float rotation;",
  12029. "uniform int renderType;",
  12030. "attribute vec2 position;",
  12031. "attribute vec2 uv;",
  12032. "varying vec2 vUV;",
  12033. "void main() {",
  12034. "vUV = uv;",
  12035. "vec2 pos = position;",
  12036. "if( renderType == 2 ) {",
  12037. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  12038. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  12039. "}",
  12040. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  12041. "}"
  12042. ].join( "\n" ),
  12043. fragmentShader: [
  12044. "precision mediump float;",
  12045. "uniform sampler2D map;",
  12046. "uniform sampler2D occlusionMap;",
  12047. "uniform float opacity;",
  12048. "uniform int renderType;",
  12049. "uniform vec3 color;",
  12050. "varying vec2 vUV;",
  12051. "void main() {",
  12052. // pink square
  12053. "if( renderType == 0 ) {",
  12054. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  12055. // restore
  12056. "} else if( renderType == 1 ) {",
  12057. "gl_FragColor = texture2D( map, vUV );",
  12058. // flare
  12059. "} else {",
  12060. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  12061. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  12062. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  12063. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  12064. "visibility = ( 1.0 - visibility / 4.0 );",
  12065. "vec4 texture = texture2D( map, vUV );",
  12066. "texture.a *= opacity * visibility;",
  12067. "gl_FragColor = texture;",
  12068. "gl_FragColor.rgb *= color;",
  12069. "}",
  12070. "}"
  12071. ].join( "\n" )
  12072. }
  12073. };
  12074. /**
  12075. * @author mikael emtinger / http://gomo.se/
  12076. *
  12077. */
  12078. THREE.ShaderSprite = {
  12079. 'sprite': {
  12080. vertexShader: [
  12081. "uniform int useScreenCoordinates;",
  12082. "uniform int affectedByDistance;",
  12083. "uniform vec3 screenPosition;",
  12084. "uniform mat4 modelViewMatrix;",
  12085. "uniform mat4 projectionMatrix;",
  12086. "uniform float rotation;",
  12087. "uniform vec2 scale;",
  12088. "uniform vec2 alignment;",
  12089. "uniform vec2 uvOffset;",
  12090. "uniform vec2 uvScale;",
  12091. "attribute vec2 position;",
  12092. "attribute vec2 uv;",
  12093. "varying vec2 vUV;",
  12094. "void main() {",
  12095. "vUV = uvOffset + uv * uvScale;",
  12096. "vec2 alignedPosition = position + alignment;",
  12097. "vec2 rotatedPosition;",
  12098. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  12099. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  12100. "vec4 finalPosition;",
  12101. "if( useScreenCoordinates != 0 ) {",
  12102. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  12103. "} else {",
  12104. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  12105. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  12106. "}",
  12107. "gl_Position = finalPosition;",
  12108. "}"
  12109. ].join( "\n" ),
  12110. fragmentShader: [
  12111. "precision mediump float;",
  12112. "uniform vec3 color;",
  12113. "uniform sampler2D map;",
  12114. "uniform float opacity;",
  12115. "varying vec2 vUV;",
  12116. "void main() {",
  12117. "vec4 texture = texture2D( map, vUV );",
  12118. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  12119. "}"
  12120. ].join( "\n" )
  12121. }
  12122. };
  12123. =======
  12124. // ThreeExtras.js - http://github.com/mrdoob/three.js
  12125. 'use strict';THREE.ColorUtils={adjustHSV:function(b,a,c,d){var e=THREE.ColorUtils.__hsv;THREE.ColorUtils.rgbToHsv(b,e);e.h=THREE.Math.clamp(e.h+a,0,1);e.s=THREE.Math.clamp(e.s+c,0,1);e.v=THREE.Math.clamp(e.v+d,0,1);b.setHSV(e.h,e.s,e.v)},rgbToHsv:function(b,a){var c=b.r,d=b.g,e=b.b,f=Math.max(Math.max(c,d),e),g=Math.min(Math.min(c,d),e);if(g===f)g=c=0;else{var h=f-g,g=h/f,c=(c===f?(d-e)/h:d===f?2+(e-c)/h:4+(c-d)/h)/6;0>c&&(c+=1);1<c&&(c-=1)}void 0===a&&(a={h:0,s:0,v:0});a.h=c;a.s=g;a.v=f;return a}};
  12126. THREE.ColorUtils.__hsv={h:0,s:0,v:0};
  12127. THREE.GeometryUtils={merge:function(b,a){for(var c,d,e=b.vertices.length,f=a instanceof THREE.Mesh?a.geometry:a,g=b.vertices,h=f.vertices,i=b.faces,j=f.faces,l=b.faceVertexUvs[0],n=f.faceVertexUvs[0],k={},m=0;m<b.materials.length;m++)k[b.materials[m].id]=m;a instanceof THREE.Mesh&&(a.matrixAutoUpdate&&a.updateMatrix(),c=a.matrix,d=new THREE.Matrix4,d.extractRotation(c,a.scale));for(var m=0,p=h.length;m<p;m++){var q=h[m].clone();c&&c.multiplyVector3(q);g.push(q)}m=0;for(p=j.length;m<p;m++){var g=j[m],
  12128. r,u,s=g.vertexNormals,t=g.vertexColors;g instanceof THREE.Face3?r=new THREE.Face3(g.a+e,g.b+e,g.c+e):g instanceof THREE.Face4&&(r=new THREE.Face4(g.a+e,g.b+e,g.c+e,g.d+e));r.normal.copy(g.normal);d&&d.multiplyVector3(r.normal);h=0;for(q=s.length;h<q;h++)u=s[h].clone(),d&&d.multiplyVector3(u),r.vertexNormals.push(u);r.color.copy(g.color);h=0;for(q=t.length;h<q;h++)u=t[h],r.vertexColors.push(u.clone());void 0!==g.materialIndex&&(h=f.materials[g.materialIndex],q=h.id,t=k[q],void 0===t&&(t=b.materials.length,
  12129. k[q]=t,b.materials.push(h)),r.materialIndex=t);r.centroid.copy(g.centroid);c&&c.multiplyVector3(r.centroid);i.push(r)}m=0;for(p=n.length;m<p;m++){c=n[m];d=[];h=0;for(q=c.length;h<q;h++)d.push(new THREE.UV(c[h].u,c[h].v));l.push(d)}},clone:function(b){var a=new THREE.Geometry,c,d=b.vertices,e=b.faces,f=b.faceVertexUvs[0];b.materials&&(a.materials=b.materials.slice());b=0;for(c=d.length;b<c;b++)a.vertices.push(d[b].clone());b=0;for(c=e.length;b<c;b++)a.faces.push(e[b].clone());b=0;for(c=f.length;b<
  12130. c;b++){for(var d=f[b],e=[],g=0,h=d.length;g<h;g++)e.push(new THREE.UV(d[g].u,d[g].v));a.faceVertexUvs[0].push(e)}return a},randomPointInTriangle:function(b,a,c){var d,e,f,g=new THREE.Vector3,h=THREE.GeometryUtils.__v1;d=THREE.GeometryUtils.random();e=THREE.GeometryUtils.random();1<d+e&&(d=1-d,e=1-e);f=1-d-e;g.copy(b);g.multiplyScalar(d);h.copy(a);h.multiplyScalar(e);g.addSelf(h);h.copy(c);h.multiplyScalar(f);g.addSelf(h);return g},randomPointInFace:function(b,a,c){var d,e,f;if(b instanceof THREE.Face3)return d=
  12131. a.vertices[b.a],e=a.vertices[b.b],f=a.vertices[b.c],THREE.GeometryUtils.randomPointInTriangle(d,e,f);if(b instanceof THREE.Face4){d=a.vertices[b.a];e=a.vertices[b.b];f=a.vertices[b.c];var a=a.vertices[b.d],g;c?b._area1&&b._area2?(c=b._area1,g=b._area2):(c=THREE.GeometryUtils.triangleArea(d,e,a),g=THREE.GeometryUtils.triangleArea(e,f,a),b._area1=c,b._area2=g):(c=THREE.GeometryUtils.triangleArea(d,e,a),g=THREE.GeometryUtils.triangleArea(e,f,a));return THREE.GeometryUtils.random()*(c+g)<c?THREE.GeometryUtils.randomPointInTriangle(d,
  12132. e,a):THREE.GeometryUtils.randomPointInTriangle(e,f,a)}},randomPointsInGeometry:function(b,a){function c(a){function b(c,d){if(d<c)return c;var e=c+Math.floor((d-c)/2);return j[e]>a?b(c,e-1):j[e]<a?b(e+1,d):e}return b(0,j.length-1)}var d,e,f=b.faces,g=b.vertices,h=f.length,i=0,j=[],l,n,k,m;for(e=0;e<h;e++)d=f[e],d instanceof THREE.Face3?(l=g[d.a],n=g[d.b],k=g[d.c],d._area=THREE.GeometryUtils.triangleArea(l,n,k)):d instanceof THREE.Face4&&(l=g[d.a],n=g[d.b],k=g[d.c],m=g[d.d],d._area1=THREE.GeometryUtils.triangleArea(l,
  12133. n,m),d._area2=THREE.GeometryUtils.triangleArea(n,k,m),d._area=d._area1+d._area2),i+=d._area,j[e]=i;d=[];for(e=0;e<a;e++)g=THREE.GeometryUtils.random()*i,g=c(g),d[e]=THREE.GeometryUtils.randomPointInFace(f[g],b,!0);return d},triangleArea:function(b,a,c){var d,e=THREE.GeometryUtils.__v1;e.sub(b,a);d=e.length();e.sub(b,c);b=e.length();e.sub(a,c);c=e.length();a=0.5*(d+b+c);return Math.sqrt(a*(a-d)*(a-b)*(a-c))},center:function(b){b.computeBoundingBox();var a=b.boundingBox,c=new THREE.Vector3;c.add(a.min,
  12134. a.max);c.multiplyScalar(-0.5);b.applyMatrix((new THREE.Matrix4).makeTranslation(c.x,c.y,c.z));b.computeBoundingBox();return c},normalizeUVs:function(b){for(var b=b.faceVertexUvs[0],a=0,c=b.length;a<c;a++)for(var d=b[a],e=0,f=d.length;e<f;e++)if(1!==d[e].u&&(d[e].u-=Math.floor(d[e].u)),1!==d[e].v)d[e].v-=Math.floor(d[e].v)},triangulateQuads:function(b){var a,c,d,e,f=[],g=[],h=[];a=0;for(c=b.faceUvs.length;a<c;a++)g[a]=[];a=0;for(c=b.faceVertexUvs.length;a<c;a++)h[a]=[];a=0;for(c=b.faces.length;a<c;a++)if(d=
  12135. b.faces[a],d instanceof THREE.Face4){e=d.a;var i=d.b,j=d.c,l=d.d,n=new THREE.Face3,k=new THREE.Face3;n.color.copy(d.color);k.color.copy(d.color);n.materialIndex=d.materialIndex;k.materialIndex=d.materialIndex;n.a=e;n.b=i;n.c=l;k.a=i;k.b=j;k.c=l;4===d.vertexColors.length&&(n.vertexColors[0]=d.vertexColors[0].clone(),n.vertexColors[1]=d.vertexColors[1].clone(),n.vertexColors[2]=d.vertexColors[3].clone(),k.vertexColors[0]=d.vertexColors[1].clone(),k.vertexColors[1]=d.vertexColors[2].clone(),k.vertexColors[2]=
  12136. d.vertexColors[3].clone());f.push(n,k);d=0;for(e=b.faceVertexUvs.length;d<e;d++)b.faceVertexUvs[d].length&&(n=b.faceVertexUvs[d][a],i=n[1],j=n[2],l=n[3],n=[n[0].clone(),i.clone(),l.clone()],i=[i.clone(),j.clone(),l.clone()],h[d].push(n,i));d=0;for(e=b.faceUvs.length;d<e;d++)b.faceUvs[d].length&&(i=b.faceUvs[d][a],g[d].push(i,i))}else{f.push(d);d=0;for(e=b.faceUvs.length;d<e;d++)g[d].push(b.faceUvs[d]);d=0;for(e=b.faceVertexUvs.length;d<e;d++)h[d].push(b.faceVertexUvs[d])}b.faces=f;b.faceUvs=g;b.faceVertexUvs=
  12137. h;b.computeCentroids();b.computeFaceNormals();b.computeVertexNormals();b.hasTangents&&b.computeTangents()},explode:function(b){for(var a=[],c=0,d=b.faces.length;c<d;c++){var e=a.length,f=b.faces[c];if(f instanceof THREE.Face4){var g=f.a,h=f.b,i=f.c,g=b.vertices[g],h=b.vertices[h],i=b.vertices[i],j=b.vertices[f.d];a.push(g.clone());a.push(h.clone());a.push(i.clone());a.push(j.clone());f.a=e;f.b=e+1;f.c=e+2;f.d=e+3}else g=f.a,h=f.b,i=f.c,g=b.vertices[g],h=b.vertices[h],i=b.vertices[i],a.push(g.clone()),
  12138. a.push(h.clone()),a.push(i.clone()),f.a=e,f.b=e+1,f.c=e+2}b.vertices=a;delete b.__tmpVertices},tessellate:function(b,a){var c,d,e,f,g,h,i,j,l,n,k,m,p,q,r,u,s,t,o,x=[],z=[];c=0;for(d=b.faceVertexUvs.length;c<d;c++)z[c]=[];c=0;for(d=b.faces.length;c<d;c++)if(e=b.faces[c],e instanceof THREE.Face3)if(f=e.a,g=e.b,h=e.c,j=b.vertices[f],l=b.vertices[g],n=b.vertices[h],m=j.distanceTo(l),p=l.distanceTo(n),k=j.distanceTo(n),m>a||p>a||k>a){i=b.vertices.length;t=e.clone();o=e.clone();m>=p&&m>=k?(j=j.clone(),
  12139. j.lerpSelf(l,0.5),t.a=f,t.b=i,t.c=h,o.a=i,o.b=g,o.c=h,3===e.vertexNormals.length&&(f=e.vertexNormals[0].clone(),f.lerpSelf(e.vertexNormals[1],0.5),t.vertexNormals[1].copy(f),o.vertexNormals[0].copy(f)),3===e.vertexColors.length&&(f=e.vertexColors[0].clone(),f.lerpSelf(e.vertexColors[1],0.5),t.vertexColors[1].copy(f),o.vertexColors[0].copy(f)),e=0):p>=m&&p>=k?(j=l.clone(),j.lerpSelf(n,0.5),t.a=f,t.b=g,t.c=i,o.a=i,o.b=h,o.c=f,3===e.vertexNormals.length&&(f=e.vertexNormals[1].clone(),f.lerpSelf(e.vertexNormals[2],
  12140. 0.5),t.vertexNormals[2].copy(f),o.vertexNormals[0].copy(f),o.vertexNormals[1].copy(e.vertexNormals[2]),o.vertexNormals[2].copy(e.vertexNormals[0])),3===e.vertexColors.length&&(f=e.vertexColors[1].clone(),f.lerpSelf(e.vertexColors[2],0.5),t.vertexColors[2].copy(f),o.vertexColors[0].copy(f),o.vertexColors[1].copy(e.vertexColors[2]),o.vertexColors[2].copy(e.vertexColors[0])),e=1):(j=j.clone(),j.lerpSelf(n,0.5),t.a=f,t.b=g,t.c=i,o.a=i,o.b=g,o.c=h,3===e.vertexNormals.length&&(f=e.vertexNormals[0].clone(),
  12141. f.lerpSelf(e.vertexNormals[2],0.5),t.vertexNormals[2].copy(f),o.vertexNormals[0].copy(f)),3===e.vertexColors.length&&(f=e.vertexColors[0].clone(),f.lerpSelf(e.vertexColors[2],0.5),t.vertexColors[2].copy(f),o.vertexColors[0].copy(f)),e=2);x.push(t,o);b.vertices.push(j);f=0;for(g=b.faceVertexUvs.length;f<g;f++)b.faceVertexUvs[f].length&&(j=b.faceVertexUvs[f][c],o=j[0],h=j[1],t=j[2],0===e?(l=o.clone(),l.lerpSelf(h,0.5),j=[o.clone(),l.clone(),t.clone()],h=[l.clone(),h.clone(),t.clone()]):1===e?(l=h.clone(),
  12142. l.lerpSelf(t,0.5),j=[o.clone(),h.clone(),l.clone()],h=[l.clone(),t.clone(),o.clone()]):(l=o.clone(),l.lerpSelf(t,0.5),j=[o.clone(),h.clone(),l.clone()],h=[l.clone(),h.clone(),t.clone()]),z[f].push(j,h))}else{x.push(e);f=0;for(g=b.faceVertexUvs.length;f<g;f++)z[f].push(b.faceVertexUvs[f][c])}else if(f=e.a,g=e.b,h=e.c,i=e.d,j=b.vertices[f],l=b.vertices[g],n=b.vertices[h],k=b.vertices[i],m=j.distanceTo(l),p=l.distanceTo(n),q=n.distanceTo(k),r=j.distanceTo(k),m>a||p>a||q>a||r>a){u=b.vertices.length;s=
  12143. b.vertices.length+1;t=e.clone();o=e.clone();m>=p&&m>=q&&m>=r||q>=p&&q>=m&&q>=r?(m=j.clone(),m.lerpSelf(l,0.5),l=n.clone(),l.lerpSelf(k,0.5),t.a=f,t.b=u,t.c=s,t.d=i,o.a=u,o.b=g,o.c=h,o.d=s,4===e.vertexNormals.length&&(f=e.vertexNormals[0].clone(),f.lerpSelf(e.vertexNormals[1],0.5),g=e.vertexNormals[2].clone(),g.lerpSelf(e.vertexNormals[3],0.5),t.vertexNormals[1].copy(f),t.vertexNormals[2].copy(g),o.vertexNormals[0].copy(f),o.vertexNormals[3].copy(g)),4===e.vertexColors.length&&(f=e.vertexColors[0].clone(),
  12144. f.lerpSelf(e.vertexColors[1],0.5),g=e.vertexColors[2].clone(),g.lerpSelf(e.vertexColors[3],0.5),t.vertexColors[1].copy(f),t.vertexColors[2].copy(g),o.vertexColors[0].copy(f),o.vertexColors[3].copy(g)),e=0):(m=l.clone(),m.lerpSelf(n,0.5),l=k.clone(),l.lerpSelf(j,0.5),t.a=f,t.b=g,t.c=u,t.d=s,o.a=s,o.b=u,o.c=h,o.d=i,4===e.vertexNormals.length&&(f=e.vertexNormals[1].clone(),f.lerpSelf(e.vertexNormals[2],0.5),g=e.vertexNormals[3].clone(),g.lerpSelf(e.vertexNormals[0],0.5),t.vertexNormals[2].copy(f),t.vertexNormals[3].copy(g),
  12145. o.vertexNormals[0].copy(g),o.vertexNormals[1].copy(f)),4===e.vertexColors.length&&(f=e.vertexColors[1].clone(),f.lerpSelf(e.vertexColors[2],0.5),g=e.vertexColors[3].clone(),g.lerpSelf(e.vertexColors[0],0.5),t.vertexColors[2].copy(f),t.vertexColors[3].copy(g),o.vertexColors[0].copy(g),o.vertexColors[1].copy(f)),e=1);x.push(t,o);b.vertices.push(m,l);f=0;for(g=b.faceVertexUvs.length;f<g;f++)b.faceVertexUvs[f].length&&(j=b.faceVertexUvs[f][c],o=j[0],h=j[1],t=j[2],j=j[3],0===e?(l=o.clone(),l.lerpSelf(h,
  12146. 0.5),n=t.clone(),n.lerpSelf(j,0.5),o=[o.clone(),l.clone(),n.clone(),j.clone()],h=[l.clone(),h.clone(),t.clone(),n.clone()]):(l=h.clone(),l.lerpSelf(t,0.5),n=j.clone(),n.lerpSelf(o,0.5),o=[o.clone(),h.clone(),l.clone(),n.clone()],h=[n.clone(),l.clone(),t.clone(),j.clone()]),z[f].push(o,h))}else{x.push(e);f=0;for(g=b.faceVertexUvs.length;f<g;f++)z[f].push(b.faceVertexUvs[f][c])}b.faces=x;b.faceVertexUvs=z}};THREE.GeometryUtils.random=THREE.Math.random16;THREE.GeometryUtils.__v1=new THREE.Vector3;
  12147. THREE.ImageUtils={crossOrigin:"anonymous",loadTexture:function(b,a,c){var d=new Image,e=new THREE.Texture(d,a);d.onload=function(){e.needsUpdate=!0;c&&c(this)};d.crossOrigin=this.crossOrigin;d.src=b;return e},loadTextureCube:function(b,a,c){var d,e=[],f=new THREE.Texture(e,a),a=e.loadCount=0;for(d=b.length;a<d;++a)e[a]=new Image,e[a].onload=function(){e.loadCount+=1;6===e.loadCount&&(f.needsUpdate=!0);c&&c(this)},e[a].crossOrigin=this.crossOrigin,e[a].src=b[a];return f},getNormalMap:function(b,a){var c=
  12148. function(a){var b=Math.sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]);return[a[0]/b,a[1]/b,a[2]/b]},a=a|1,d=b.width,e=b.height,f=document.createElement("canvas");f.width=d;f.height=e;var g=f.getContext("2d");g.drawImage(b,0,0);for(var h=g.getImageData(0,0,d,e).data,i=g.createImageData(d,e),j=i.data,l=0;l<d;l++)for(var n=1;n<e;n++){var k=0>n-1?e-1:n-1,m=(n+1)%e,p=0>l-1?d-1:l-1,q=(l+1)%d,r=[],u=[0,0,h[4*(n*d+l)]/255*a];r.push([-1,0,h[4*(n*d+p)]/255*a]);r.push([-1,-1,h[4*(k*d+p)]/255*a]);r.push([0,-1,h[4*(k*d+
  12149. l)]/255*a]);r.push([1,-1,h[4*(k*d+q)]/255*a]);r.push([1,0,h[4*(n*d+q)]/255*a]);r.push([1,1,h[4*(m*d+q)]/255*a]);r.push([0,1,h[4*(m*d+l)]/255*a]);r.push([-1,1,h[4*(m*d+p)]/255*a]);k=[];p=r.length;for(m=0;m<p;m++){var q=r[m],s=r[(m+1)%p],q=[q[0]-u[0],q[1]-u[1],q[2]-u[2]],s=[s[0]-u[0],s[1]-u[1],s[2]-u[2]];k.push(c([q[1]*s[2]-q[2]*s[1],q[2]*s[0]-q[0]*s[2],q[0]*s[1]-q[1]*s[0]]))}r=[0,0,0];for(m=0;m<k.length;m++)r[0]+=k[m][0],r[1]+=k[m][1],r[2]+=k[m][2];r[0]/=k.length;r[1]/=k.length;r[2]/=k.length;u=4*
  12150. (n*d+l);j[u]=255*((r[0]+1)/2)|0;j[u+1]=255*(r[1]+0.5)|0;j[u+2]=255*r[2]|0;j[u+3]=255}g.putImageData(i,0,0);return f},generateDataTexture:function(b,a,c){for(var d=b*a,e=new Uint8Array(3*d),f=Math.floor(255*c.r),g=Math.floor(255*c.g),c=Math.floor(255*c.b),h=0;h<d;h++)e[3*h]=f,e[3*h+1]=g,e[3*h+2]=c;b=new THREE.DataTexture(e,b,a,THREE.RGBFormat);b.needsUpdate=!0;return b}};
  12151. THREE.SceneUtils={showHierarchy:function(b,a){THREE.SceneUtils.traverseHierarchy(b,function(b){b.visible=a})},traverseHierarchy:function(b,a){var c,d,e=b.children.length;for(d=0;d<e;d++)c=b.children[d],a(c),THREE.SceneUtils.traverseHierarchy(c,a)},createMultiMaterialObject:function(b,a){var c,d=a.length,e=new THREE.Object3D;for(c=0;c<d;c++){var f=new THREE.Mesh(b,a[c]);e.add(f)}return e},cloneObject:function(b){var a;b instanceof THREE.MorphAnimMesh?(a=new THREE.MorphAnimMesh(b.geometry,b.material),
  12152. a.duration=b.duration,a.mirroredLoop=b.mirroredLoop,a.time=b.time,a.lastKeyframe=b.lastKeyframe,a.currentKeyframe=b.currentKeyframe,a.direction=b.direction,a.directionBackwards=b.directionBackwards):b instanceof THREE.SkinnedMesh?a=new THREE.SkinnedMesh(b.geometry,b.material):b instanceof THREE.Mesh?a=new THREE.Mesh(b.geometry,b.material):b instanceof THREE.Line?a=new THREE.Line(b.geometry,b.material,b.type):b instanceof THREE.Ribbon?a=new THREE.Ribbon(b.geometry,b.material):b instanceof THREE.ParticleSystem?
  12153. (a=new THREE.ParticleSystem(b.geometry,b.material),a.sortParticles=b.sortParticles):b instanceof THREE.Particle?a=new THREE.Particle(b.material):b instanceof THREE.Sprite?(a=new THREE.Sprite({}),a.color.copy(b.color),a.map=b.map,a.blending=b.blending,a.useScreenCoordinates=b.useScreenCoordinates,a.mergeWith3D=b.mergeWith3D,a.affectedByDistance=b.affectedByDistance,a.scaleByViewport=b.scaleByViewport,a.alignment=b.alignment,a.rotation3d.copy(b.rotation3d),a.rotation=b.rotation,a.opacity=b.opacity,
  12154. a.uvOffset.copy(b.uvOffset),a.uvScale.copy(b.uvScale)):b instanceof THREE.LOD?a=new THREE.LOD:b instanceof THREE.MarchingCubes?(a=new THREE.MarchingCubes(b.resolution,b.material),a.field.set(b.field),a.isolation=b.isolation):b instanceof THREE.Object3D&&(a=new THREE.Object3D);a.name=b.name;a.parent=b.parent;a.up.copy(b.up);a.position.copy(b.position);a.rotation instanceof THREE.Vector3&&a.rotation.copy(b.rotation);a.eulerOrder=b.eulerOrder;a.scale.copy(b.scale);a.dynamic=b.dynamic;a.doubleSided=b.doubleSided;
  12155. a.flipSided=b.flipSided;a.renderDepth=b.renderDepth;a.rotationAutoUpdate=b.rotationAutoUpdate;a.matrix.copy(b.matrix);a.matrixWorld.copy(b.matrixWorld);a.matrixRotationWorld.copy(b.matrixRotationWorld);a.matrixAutoUpdate=b.matrixAutoUpdate;a.matrixWorldNeedsUpdate=b.matrixWorldNeedsUpdate;a.quaternion.copy(b.quaternion);a.useQuaternion=b.useQuaternion;a.boundRadius=b.boundRadius;a.boundRadiusScale=b.boundRadiusScale;a.visible=b.visible;a.castShadow=b.castShadow;a.receiveShadow=b.receiveShadow;a.frustumCulled=
  12156. b.frustumCulled;for(var c=0;c<b.children.length;c++){var d=THREE.SceneUtils.cloneObject(b.children[c]);a.children[c]=d;d.parent=a}if(b instanceof THREE.LOD)for(c=0;c<b.LODs.length;c++)a.LODs[c]={visibleAtDistance:b.LODs[c].visibleAtDistance,object3D:a.children[c]};return a},detach:function(b,a,c){b.applyMatrix(a.matrixWorld);a.remove(b);c.add(b)},attach:function(b,a,c){var d=new THREE.Matrix4;d.getInverse(c.matrixWorld);b.applyMatrix(d);a.remove(b);c.add(b)}};
  12157. THREE.WebGLRenderer&&(THREE.ShaderUtils={lib:{fresnel:{uniforms:{mRefractionRatio:{type:"f",value:1.02},mFresnelBias:{type:"f",value:0.1},mFresnelPower:{type:"f",value:2},mFresnelScale:{type:"f",value:1},tCube:{type:"t",value:1,texture:null}},fragmentShader:"uniform samplerCube tCube;\nvarying vec3 vReflect;\nvarying vec3 vRefract[3];\nvarying float vReflectionFactor;\nvoid main() {\nvec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );\nvec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );\nrefractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;\nrefractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;\nrefractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;\nrefractedColor.a = 1.0;\ngl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );\n}",
  12158. vertexShader:"uniform float mRefractionRatio;\nuniform float mFresnelBias;\nuniform float mFresnelScale;\nuniform float mFresnelPower;\nvarying vec3 vReflect;\nvarying vec3 vRefract[3];\nvarying float vReflectionFactor;\nvoid main() {\nvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\nvec4 mPosition = objectMatrix * vec4( position, 1.0 );\nvec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );\nvec3 I = mPosition.xyz - cameraPosition;\nvReflect = reflect( I, nWorld );\nvRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );\nvRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );\nvRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );\nvReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );\ngl_Position = projectionMatrix * mvPosition;\n}"},
  12159. normal:{uniforms:THREE.UniformsUtils.merge([THREE.UniformsLib.fog,THREE.UniformsLib.lights,THREE.UniformsLib.shadowmap,{enableAO:{type:"i",value:0},enableDiffuse:{type:"i",value:0},enableSpecular:{type:"i",value:0},enableReflection:{type:"i",value:0},tDiffuse:{type:"t",value:0,texture:null},tCube:{type:"t",value:1,texture:null},tNormal:{type:"t",value:2,texture:null},tSpecular:{type:"t",value:3,texture:null},tAO:{type:"t",value:4,texture:null},tDisplacement:{type:"t",value:5,texture:null},uNormalScale:{type:"f",
  12160. value:1},uDisplacementBias:{type:"f",value:0},uDisplacementScale:{type:"f",value:1},uDiffuseColor:{type:"c",value:new THREE.Color(16777215)},uSpecularColor:{type:"c",value:new THREE.Color(1118481)},uAmbientColor:{type:"c",value:new THREE.Color(16777215)},uShininess:{type:"f",value:30},uOpacity:{type:"f",value:1},uReflectivity:{type:"f",value:0.5},uOffset:{type:"v2",value:new THREE.Vector2(0,0)},uRepeat:{type:"v2",value:new THREE.Vector2(1,1)},wrapRGB:{type:"v3",value:new THREE.Vector3(1,1,1)}}]),
  12161. fragmentShader:["uniform vec3 uAmbientColor;\nuniform vec3 uDiffuseColor;\nuniform vec3 uSpecularColor;\nuniform float uShininess;\nuniform float uOpacity;\nuniform bool enableDiffuse;\nuniform bool enableSpecular;\nuniform bool enableAO;\nuniform bool enableReflection;\nuniform sampler2D tDiffuse;\nuniform sampler2D tNormal;\nuniform sampler2D tSpecular;\nuniform sampler2D tAO;\nuniform samplerCube tCube;\nuniform float uNormalScale;\nuniform float uReflectivity;\nvarying vec3 vTangent;\nvarying vec3 vBinormal;\nvarying vec3 vNormal;\nvarying vec2 vUv;\nuniform vec3 ambientLightColor;\n#if MAX_DIR_LIGHTS > 0\nuniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\nuniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n#endif\n#if MAX_POINT_LIGHTS > 0\nuniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\nvarying vec4 vPointLight[ MAX_POINT_LIGHTS ];\n#endif\n#ifdef WRAP_AROUND\nuniform vec3 wrapRGB;\n#endif\nvarying vec3 vViewPosition;",
  12162. THREE.ShaderChunk.shadowmap_pars_fragment,THREE.ShaderChunk.fog_pars_fragment,"void main() {\ngl_FragColor = vec4( vec3( 1.0 ), uOpacity );\nvec3 specularTex = vec3( 1.0 );\nvec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;\nnormalTex.xy *= uNormalScale;\nnormalTex = normalize( normalTex );\nif( enableDiffuse ) {\n#ifdef GAMMA_INPUT\nvec4 texelColor = texture2D( tDiffuse, vUv );\ntexelColor.xyz *= texelColor.xyz;\ngl_FragColor = gl_FragColor * texelColor;\n#else\ngl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );\n#endif\n}\nif( enableAO ) {\n#ifdef GAMMA_INPUT\nvec4 aoColor = texture2D( tAO, vUv );\naoColor.xyz *= aoColor.xyz;\ngl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;\n#else\ngl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;\n#endif\n}\nif( enableSpecular )\nspecularTex = texture2D( tSpecular, vUv ).xyz;\nmat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );\nvec3 finalNormal = tsb * normalTex;\nvec3 normal = normalize( finalNormal );\nvec3 viewPosition = normalize( vViewPosition );\n#if MAX_POINT_LIGHTS > 0\nvec3 pointDiffuse = vec3( 0.0 );\nvec3 pointSpecular = vec3( 0.0 );\nfor ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\nvec3 pointVector = normalize( vPointLight[ i ].xyz );\nfloat pointDistance = vPointLight[ i ].w;\n#ifdef WRAP_AROUND\nfloat pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );\nfloat pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );\nvec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );\n#else\nfloat pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );\n#endif\npointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;\nvec3 pointHalfVector = normalize( pointVector + viewPosition );\nfloat pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );\nfloat pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );\n#ifdef PHYSICALLY_BASED_SHADING\nfloat specularNormalization = ( uShininess + 2.0001 ) / 8.0;\nvec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );\npointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;\n#else\npointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;\n#endif\n}\n#endif\n#if MAX_DIR_LIGHTS > 0\nvec3 dirDiffuse = vec3( 0.0 );\nvec3 dirSpecular = vec3( 0.0 );\nfor( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {\nvec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );\nvec3 dirVector = normalize( lDirection.xyz );\n#ifdef WRAP_AROUND\nfloat directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );\nfloat directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );\nvec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );\n#else\nfloat dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );\n#endif\ndirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;\nvec3 dirHalfVector = normalize( dirVector + viewPosition );\nfloat dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );\nfloat dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );\n#ifdef PHYSICALLY_BASED_SHADING\nfloat specularNormalization = ( uShininess + 2.0001 ) / 8.0;\nvec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );\ndirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;\n#else\ndirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;\n#endif\n}\n#endif\nvec3 totalDiffuse = vec3( 0.0 );\nvec3 totalSpecular = vec3( 0.0 );\n#if MAX_DIR_LIGHTS > 0\ntotalDiffuse += dirDiffuse;\ntotalSpecular += dirSpecular;\n#endif\n#if MAX_POINT_LIGHTS > 0\ntotalDiffuse += pointDiffuse;\ntotalSpecular += pointSpecular;\n#endif\ngl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor) + totalSpecular;\nif ( enableReflection ) {\nvec3 wPos = cameraPosition - vViewPosition;\nvec3 vReflect = reflect( normalize( wPos ), normal );\nvec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );\n#ifdef GAMMA_INPUT\ncubeColor.xyz *= cubeColor.xyz;\n#endif\ngl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );\n}",
  12163. THREE.ShaderChunk.shadowmap_fragment,THREE.ShaderChunk.linear_to_gamma_fragment,THREE.ShaderChunk.fog_fragment,"}"].join("\n"),vertexShader:["attribute vec4 tangent;\nuniform vec2 uOffset;\nuniform vec2 uRepeat;\n#ifdef VERTEX_TEXTURES\nuniform sampler2D tDisplacement;\nuniform float uDisplacementScale;\nuniform float uDisplacementBias;\n#endif\nvarying vec3 vTangent;\nvarying vec3 vBinormal;\nvarying vec3 vNormal;\nvarying vec2 vUv;\n#if MAX_POINT_LIGHTS > 0\nuniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\nuniform float pointLightDistance[ MAX_POINT_LIGHTS ];\nvarying vec4 vPointLight[ MAX_POINT_LIGHTS ];\n#endif\nvarying vec3 vViewPosition;",
  12164. THREE.ShaderChunk.shadowmap_pars_vertex,"void main() {\nvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\nvViewPosition = -mvPosition.xyz;\nvNormal = normalMatrix * normal;\nvTangent = normalMatrix * tangent.xyz;\nvBinormal = cross( vNormal, vTangent ) * tangent.w;\nvUv = uv * uRepeat + uOffset;\n#if MAX_POINT_LIGHTS > 0\nfor( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {\nvec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\nvec3 lVector = lPosition.xyz - mvPosition.xyz;\nfloat lDistance = 1.0;\nif ( pointLightDistance[ i ] > 0.0 )\nlDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );\nlVector = normalize( lVector );\nvPointLight[ i ] = vec4( lVector, lDistance );\n}\n#endif\n#ifdef VERTEX_TEXTURES\nvec3 dv = texture2D( tDisplacement, uv ).xyz;\nfloat df = uDisplacementScale * dv.x + uDisplacementBias;\nvec4 displacedPosition = vec4( normalize( vNormal.xyz ) * df, 0.0 ) + mvPosition;\ngl_Position = projectionMatrix * displacedPosition;\n#else\ngl_Position = projectionMatrix * mvPosition;\n#endif",
  12165. THREE.ShaderChunk.shadowmap_vertex,"}"].join("\n")},cube:{uniforms:{tCube:{type:"t",value:1,texture:null},tFlip:{type:"f",value:-1}},vertexShader:"varying vec3 vViewPosition;\nvoid main() {\nvec4 mPosition = objectMatrix * vec4( position, 1.0 );\nvViewPosition = cameraPosition - mPosition.xyz;\ngl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"uniform samplerCube tCube;\nuniform float tFlip;\nvarying vec3 vViewPosition;\nvoid main() {\nvec3 wPos = cameraPosition - vViewPosition;\ngl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );\n}"}}});
  12166. THREE.BufferGeometry=function(){this.id=THREE.GeometryCount++;this.vertexColorArray=this.vertexUvArray=this.vertexNormalArray=this.vertexPositionArray=this.vertexIndexArray=this.vertexColorBuffer=this.vertexUvBuffer=this.vertexNormalBuffer=this.vertexPositionBuffer=this.vertexIndexBuffer=null;this.dynamic=false;this.boundingSphere=this.boundingBox=null;this.morphTargets=[]};THREE.BufferGeometry.prototype={constructor:THREE.BufferGeometry,computeBoundingBox:function(){},computeBoundingSphere:function(){}};
  12167. THREE.Curve=function(){};THREE.Curve.prototype.getPoint=function(){console.log("Warning, getPoint() not implemented!");return null};THREE.Curve.prototype.getPointAt=function(b){return this.getPoint(this.getUtoTmapping(b))};THREE.Curve.prototype.getPoints=function(b){b||(b=5);var a,c=[];for(a=0;a<=b;a++)c.push(this.getPoint(a/b));return c};THREE.Curve.prototype.getSpacedPoints=function(b){b||(b=5);var a,c=[];for(a=0;a<=b;a++)c.push(this.getPointAt(a/b));return c};
  12168. THREE.Curve.prototype.getLength=function(){var b=this.getLengths();return b[b.length-1]};THREE.Curve.prototype.getLengths=function(b){b||(b=this.__arcLengthDivisions?this.__arcLengthDivisions:200);if(this.cacheArcLengths&&this.cacheArcLengths.length==b+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=false;var a=[],c,d=this.getPoint(0),e,f=0;a.push(0);for(e=1;e<=b;e++){c=this.getPoint(e/b);f=f+c.distanceTo(d);a.push(f);d=c}return this.cacheArcLengths=a};
  12169. THREE.Curve.prototype.updateArcLengths=function(){this.needsUpdate=true;this.getLengths()};THREE.Curve.prototype.getUtoTmapping=function(b,a){var c=this.getLengths(),d=0,e=c.length,f;f=a?a:b*c[e-1];for(var g=0,h=e-1,i;g<=h;){d=Math.floor(g+(h-g)/2);i=c[d]-f;if(i<0)g=d+1;else if(i>0)h=d-1;else{h=d;break}}d=h;if(c[d]==f)return d/(e-1);g=c[d];return c=(d+(f-g)/(c[d+1]-g))/(e-1)};THREE.Curve.prototype.getNormalVector=function(b){b=this.getTangent(b);return new THREE.Vector2(-b.y,b.x)};
  12170. THREE.Curve.prototype.getTangent=function(b){var a=b-1.0E-4,b=b+1.0E-4;a<0&&(a=0);b>1&&(b=1);a=this.getPoint(a);return this.getPoint(b).clone().subSelf(a).normalize()};THREE.Curve.prototype.getTangentAt=function(b){return this.getTangent(this.getUtoTmapping(b))};THREE.LineCurve=function(b,a){this.v1=b;this.v2=a};THREE.LineCurve.prototype=new THREE.Curve;THREE.LineCurve.prototype.constructor=THREE.LineCurve;
  12171. THREE.LineCurve.prototype.getPoint=function(b){var a=this.v2.clone().subSelf(this.v1);a.multiplyScalar(b).addSelf(this.v1);return a};THREE.LineCurve.prototype.getPointAt=function(b){return this.getPoint(b)};THREE.LineCurve.prototype.getTangent=function(){return this.v2.clone().subSelf(this.v1).normalize()};THREE.QuadraticBezierCurve=function(b,a,c){this.v0=b;this.v1=a;this.v2=c};THREE.QuadraticBezierCurve.prototype=new THREE.Curve;THREE.QuadraticBezierCurve.prototype.constructor=THREE.QuadraticBezierCurve;
  12172. THREE.QuadraticBezierCurve.prototype.getPoint=function(b){var a;a=THREE.Shape.Utils.b2(b,this.v0.x,this.v1.x,this.v2.x);b=THREE.Shape.Utils.b2(b,this.v0.y,this.v1.y,this.v2.y);return new THREE.Vector2(a,b)};THREE.QuadraticBezierCurve.prototype.getTangent=function(b){var a;a=THREE.Curve.Utils.tangentQuadraticBezier(b,this.v0.x,this.v1.x,this.v2.x);b=THREE.Curve.Utils.tangentQuadraticBezier(b,this.v0.y,this.v1.y,this.v2.y);a=new THREE.Vector2(a,b);a.normalize();return a};
  12173. THREE.CubicBezierCurve=function(b,a,c,d){this.v0=b;this.v1=a;this.v2=c;this.v3=d};THREE.CubicBezierCurve.prototype=new THREE.Curve;THREE.CubicBezierCurve.prototype.constructor=THREE.CubicBezierCurve;THREE.CubicBezierCurve.prototype.getPoint=function(b){var a;a=THREE.Shape.Utils.b3(b,this.v0.x,this.v1.x,this.v2.x,this.v3.x);b=THREE.Shape.Utils.b3(b,this.v0.y,this.v1.y,this.v2.y,this.v3.y);return new THREE.Vector2(a,b)};
  12174. THREE.CubicBezierCurve.prototype.getTangent=function(b){var a;a=THREE.Curve.Utils.tangentCubicBezier(b,this.v0.x,this.v1.x,this.v2.x,this.v3.x);b=THREE.Curve.Utils.tangentCubicBezier(b,this.v0.y,this.v1.y,this.v2.y,this.v3.y);a=new THREE.Vector2(a,b);a.normalize();return a};THREE.SplineCurve=function(b){this.points=b==void 0?[]:b};THREE.SplineCurve.prototype=new THREE.Curve;THREE.SplineCurve.prototype.constructor=THREE.SplineCurve;
  12175. THREE.SplineCurve.prototype.getPoint=function(b){var a=new THREE.Vector2,c=[],d=this.points,e;e=(d.length-1)*b;b=Math.floor(e);e=e-b;c[0]=b==0?b:b-1;c[1]=b;c[2]=b>d.length-2?d.length-1:b+1;c[3]=b>d.length-3?d.length-1:b+2;a.x=THREE.Curve.Utils.interpolate(d[c[0]].x,d[c[1]].x,d[c[2]].x,d[c[3]].x,e);a.y=THREE.Curve.Utils.interpolate(d[c[0]].y,d[c[1]].y,d[c[2]].y,d[c[3]].y,e);return a};
  12176. THREE.ArcCurve=function(b,a,c,d,e,f){this.aX=b;this.aY=a;this.aRadius=c;this.aStartAngle=d;this.aEndAngle=e;this.aClockwise=f};THREE.ArcCurve.prototype=new THREE.Curve;THREE.ArcCurve.prototype.constructor=THREE.ArcCurve;THREE.ArcCurve.prototype.getPoint=function(b){var a=this.aEndAngle-this.aStartAngle;this.aClockwise||(b=1-b);a=this.aStartAngle+b*a;b=this.aX+this.aRadius*Math.cos(a);a=this.aY+this.aRadius*Math.sin(a);return new THREE.Vector2(b,a)};
  12177. THREE.Curve.Utils={tangentQuadraticBezier:function(b,a,c,d){return 2*(1-b)*(c-a)+2*b*(d-c)},tangentCubicBezier:function(b,a,c,d,e){return-3*a*(1-b)*(1-b)+3*c*(1-b)*(1-b)-6*b*c*(1-b)+6*b*d*(1-b)-3*b*b*d+3*b*b*e},tangentSpline:function(b){return 6*b*b-6*b+(3*b*b-4*b+1)+(-6*b*b+6*b)+(3*b*b-2*b)},interpolate:function(b,a,c,d,e){var b=(c-b)*0.5,d=(d-a)*0.5,f=e*e;return(2*a-2*c+b+d)*e*f+(-3*a+3*c-2*b-d)*f+b*e+a}};
  12178. THREE.Curve.create=function(b,a){b.prototype=new THREE.Curve;b.prototype.constructor=b;b.prototype.getPoint=a;return b};THREE.LineCurve3=THREE.Curve.create(function(b,a){this.v1=b;this.v2=a},function(b){var a=new THREE.Vector3;a.sub(this.v2,this.v1);a.multiplyScalar(b);a.addSelf(this.v1);return a});
  12179. THREE.QuadraticBezierCurve3=THREE.Curve.create(function(b,a,c){this.v0=b;this.v1=a;this.v2=c},function(b){var a,c;a=THREE.Shape.Utils.b2(b,this.v0.x,this.v1.x,this.v2.x);c=THREE.Shape.Utils.b2(b,this.v0.y,this.v1.y,this.v2.y);b=THREE.Shape.Utils.b2(b,this.v0.z,this.v1.z,this.v2.z);return new THREE.Vector3(a,c,b)});
  12180. THREE.CubicBezierCurve3=THREE.Curve.create(function(b,a,c,d){this.v0=b;this.v1=a;this.v2=c;this.v3=d},function(b){var a,c;a=THREE.Shape.Utils.b3(b,this.v0.x,this.v1.x,this.v2.x,this.v3.x);c=THREE.Shape.Utils.b3(b,this.v0.y,this.v1.y,this.v2.y,this.v3.y);b=THREE.Shape.Utils.b3(b,this.v0.z,this.v1.z,this.v2.z,this.v3.z);return new THREE.Vector3(a,c,b)});
  12181. THREE.SplineCurve3=THREE.Curve.create(function(b){this.points=b==void 0?[]:b},function(b){var a=new THREE.Vector3,c=[],d=this.points,e,b=(d.length-1)*b;e=Math.floor(b);b=b-e;c[0]=e==0?e:e-1;c[1]=e;c[2]=e>d.length-2?d.length-1:e+1;c[3]=e>d.length-3?d.length-1:e+2;e=d[c[0]];var f=d[c[1]],g=d[c[2]],c=d[c[3]];a.x=THREE.Curve.Utils.interpolate(e.x,f.x,g.x,c.x,b);a.y=THREE.Curve.Utils.interpolate(e.y,f.y,g.y,c.y,b);a.z=THREE.Curve.Utils.interpolate(e.z,f.z,g.z,c.z,b);return a});
  12182. THREE.ClosedSplineCurve3=THREE.Curve.create(function(b){this.points=b==void 0?[]:b},function(b){var a=new THREE.Vector3,c=[],d=this.points,e;e=(d.length-0)*b;b=Math.floor(e);e=e-b;b=b+(b>0?0:(Math.floor(Math.abs(b)/d.length)+1)*d.length);c[0]=(b-1)%d.length;c[1]=b%d.length;c[2]=(b+1)%d.length;c[3]=(b+2)%d.length;a.x=THREE.Curve.Utils.interpolate(d[c[0]].x,d[c[1]].x,d[c[2]].x,d[c[3]].x,e);a.y=THREE.Curve.Utils.interpolate(d[c[0]].y,d[c[1]].y,d[c[2]].y,d[c[3]].y,e);a.z=THREE.Curve.Utils.interpolate(d[c[0]].z,
  12183. d[c[1]].z,d[c[2]].z,d[c[3]].z,e);return a});THREE.CurvePath=function(){this.curves=[];this.bends=[];this.autoClose=false};THREE.CurvePath.prototype=new THREE.Curve;THREE.CurvePath.prototype.constructor=THREE.CurvePath;THREE.CurvePath.prototype.add=function(b){this.curves.push(b)};THREE.CurvePath.prototype.checkConnection=function(){};
  12184. THREE.CurvePath.prototype.closePath=function(){var b=this.curves[0].getPoint(0),a=this.curves[this.curves.length-1].getPoint(1);b.equals(a)||this.curves.push(new THREE.LineCurve(a,b))};THREE.CurvePath.prototype.getPoint=function(b){for(var a=b*this.getLength(),c=this.getCurveLengths(),b=0;b<c.length;){if(c[b]>=a){a=c[b]-a;b=this.curves[b];a=1-a/b.getLength();return b.getPointAt(a)}b++}return null};THREE.CurvePath.prototype.getLength=function(){var b=this.getCurveLengths();return b[b.length-1]};
  12185. THREE.CurvePath.prototype.getCurveLengths=function(){if(this.cacheLengths&&this.cacheLengths.length==this.curves.length)return this.cacheLengths;var b=[],a=0,c,d=this.curves.length;for(c=0;c<d;c++){a=a+this.curves[c].getLength();b.push(a)}return this.cacheLengths=b};
  12186. THREE.CurvePath.prototype.getBoundingBox=function(){var b=this.getPoints(),a,c,d,e;a=c=Number.NEGATIVE_INFINITY;d=e=Number.POSITIVE_INFINITY;var f,g,h,i;i=new THREE.Vector2;g=0;for(h=b.length;g<h;g++){f=b[g];if(f.x>a)a=f.x;else if(f.x<d)d=f.x;if(f.y>c)c=f.y;else if(f.y<c)e=f.y;i.addSelf(f.x,f.y)}return{minX:d,minY:e,maxX:a,maxY:c,centroid:i.divideScalar(h)}};THREE.CurvePath.prototype.createPointsGeometry=function(b){return this.createGeometry(this.getPoints(b,true))};
  12187. THREE.CurvePath.prototype.createSpacedPointsGeometry=function(b){return this.createGeometry(this.getSpacedPoints(b,true))};THREE.CurvePath.prototype.createGeometry=function(b){for(var a=new THREE.Geometry,c=0;c<b.length;c++)a.vertices.push(new THREE.Vector3(b[c].x,b[c].y,0));return a};THREE.CurvePath.prototype.addWrapPath=function(b){this.bends.push(b)};
  12188. THREE.CurvePath.prototype.getTransformedPoints=function(b,a){var c=this.getPoints(b),d,e;if(!a)a=this.bends;d=0;for(e=a.length;d<e;d++)c=this.getWrapPoints(c,a[d]);return c};THREE.CurvePath.prototype.getTransformedSpacedPoints=function(b,a){var c=this.getSpacedPoints(b),d,e;if(!a)a=this.bends;d=0;for(e=a.length;d<e;d++)c=this.getWrapPoints(c,a[d]);return c};
  12189. THREE.CurvePath.prototype.getWrapPoints=function(b,a){var c=this.getBoundingBox(),d,e,f,g,h,i;d=0;for(e=b.length;d<e;d++){f=b[d];g=f.x;h=f.y;i=g/c.maxX;i=a.getUtoTmapping(i,g);g=a.getPoint(i);h=a.getNormalVector(i).multiplyScalar(h);f.x=g.x+h.x;f.y=g.y+h.y}return b};
  12190. THREE.EventTarget=function(){var b={};this.addEventListener=function(a,c){b[a]==void 0&&(b[a]=[]);b[a].indexOf(c)===-1&&b[a].push(c)};this.dispatchEvent=function(a){for(var c in b[a.type])b[a.type][c](a)};this.removeEventListener=function(a,c){var d=b[a].indexOf(c);d!==-1&&b[a].splice(d,1)}};THREE.Gyroscope=function(){THREE.Object3D.call(this)};THREE.Gyroscope.prototype=new THREE.Object3D;THREE.Gyroscope.prototype.constructor=THREE.Gyroscope;
  12191. THREE.Gyroscope.prototype.updateMatrixWorld=function(b){this.matrixAutoUpdate&&this.updateMatrix();if(this.matrixWorldNeedsUpdate||b){if(this.parent){this.matrixWorld.multiply(this.parent.matrixWorld,this.matrix);this.matrixWorld.decompose(this.translationWorld,this.rotationWorld,this.scaleWorld);this.matrix.decompose(this.translationObject,this.rotationObject,this.scaleObject);this.matrixWorld.compose(this.translationWorld,this.rotationObject,this.scaleWorld)}else this.matrixWorld.copy(this.matrix);
  12192. this.matrixWorldNeedsUpdate=false;b=true}for(var a=0,c=this.children.length;a<c;a++)this.children[a].updateMatrixWorld(b)};THREE.Gyroscope.prototype.translationWorld=new THREE.Vector3;THREE.Gyroscope.prototype.translationObject=new THREE.Vector3;THREE.Gyroscope.prototype.rotationWorld=new THREE.Quaternion;THREE.Gyroscope.prototype.rotationObject=new THREE.Quaternion;THREE.Gyroscope.prototype.scaleWorld=new THREE.Vector3;THREE.Gyroscope.prototype.scaleObject=new THREE.Vector3;
  12193. THREE.Path=function(b){THREE.CurvePath.call(this);this.actions=[];b&&this.fromPoints(b)};THREE.Path.prototype=new THREE.CurvePath;THREE.Path.prototype.constructor=THREE.Path;THREE.PathActions={MOVE_TO:"moveTo",LINE_TO:"lineTo",QUADRATIC_CURVE_TO:"quadraticCurveTo",BEZIER_CURVE_TO:"bezierCurveTo",CSPLINE_THRU:"splineThru",ARC:"arc"};THREE.Path.prototype.fromPoints=function(b){this.moveTo(b[0].x,b[0].y);for(var a=1,c=b.length;a<c;a++)this.lineTo(b[a].x,b[a].y)};
  12194. THREE.Path.prototype.moveTo=function(b,a){var c=Array.prototype.slice.call(arguments);this.actions.push({action:THREE.PathActions.MOVE_TO,args:c})};THREE.Path.prototype.lineTo=function(b,a){var c=Array.prototype.slice.call(arguments),d=this.actions[this.actions.length-1].args;this.curves.push(new THREE.LineCurve(new THREE.Vector2(d[d.length-2],d[d.length-1]),new THREE.Vector2(b,a)));this.actions.push({action:THREE.PathActions.LINE_TO,args:c})};
  12195. THREE.Path.prototype.quadraticCurveTo=function(b,a,c,d){var e=Array.prototype.slice.call(arguments),f=this.actions[this.actions.length-1].args;this.curves.push(new THREE.QuadraticBezierCurve(new THREE.Vector2(f[f.length-2],f[f.length-1]),new THREE.Vector2(b,a),new THREE.Vector2(c,d)));this.actions.push({action:THREE.PathActions.QUADRATIC_CURVE_TO,args:e})};
  12196. THREE.Path.prototype.bezierCurveTo=function(b,a,c,d,e,f){var g=Array.prototype.slice.call(arguments),h=this.actions[this.actions.length-1].args;this.curves.push(new THREE.CubicBezierCurve(new THREE.Vector2(h[h.length-2],h[h.length-1]),new THREE.Vector2(b,a),new THREE.Vector2(c,d),new THREE.Vector2(e,f)));this.actions.push({action:THREE.PathActions.BEZIER_CURVE_TO,args:g})};
  12197. THREE.Path.prototype.splineThru=function(b){var a=Array.prototype.slice.call(arguments),c=this.actions[this.actions.length-1].args,c=[new THREE.Vector2(c[c.length-2],c[c.length-1])];Array.prototype.push.apply(c,b);this.curves.push(new THREE.SplineCurve(c));this.actions.push({action:THREE.PathActions.CSPLINE_THRU,args:a})};
  12198. THREE.Path.prototype.arc=function(b,a,c,d,e,f){var g=Array.prototype.slice.call(arguments),h=this.actions[this.actions.length-1],h=new THREE.ArcCurve(h.x+b,h.y+a,c,d,e,f);this.curves.push(h);h=h.getPoint(f?1:0);g.push(h.x);g.push(h.y);this.actions.push({action:THREE.PathActions.ARC,args:g})};
  12199. THREE.Path.prototype.absarc=function(b,a,c,d,e,f){var g=Array.prototype.slice.call(arguments),h=new THREE.ArcCurve(b,a,c,d,e,f);this.curves.push(h);h=h.getPoint(f?1:0);g.push(h.x);g.push(h.y);this.actions.push({action:THREE.PathActions.ARC,args:g})};THREE.Path.prototype.getSpacedPoints=function(b){b||(b=40);for(var a=[],c=0;c<b;c++)a.push(this.getPoint(c/b));return a};
  12200. THREE.Path.prototype.getPoints=function(b,a){if(this.useSpacedPoints){console.log("tata");return this.getSpacedPoints(b,a)}var b=b||12,c=[],d,e,f,g,h,i,j,l,n,k,m,p,q;d=0;for(e=this.actions.length;d<e;d++){f=this.actions[d];g=f.action;f=f.args;switch(g){case THREE.PathActions.MOVE_TO:c.push(new THREE.Vector2(f[0],f[1]));break;case THREE.PathActions.LINE_TO:c.push(new THREE.Vector2(f[0],f[1]));break;case THREE.PathActions.QUADRATIC_CURVE_TO:h=f[2];i=f[3];n=f[0];k=f[1];if(c.length>0){g=c[c.length-1];
  12201. m=g.x;p=g.y}else{g=this.actions[d-1].args;m=g[g.length-2];p=g[g.length-1]}for(f=1;f<=b;f++){q=f/b;g=THREE.Shape.Utils.b2(q,m,n,h);q=THREE.Shape.Utils.b2(q,p,k,i);c.push(new THREE.Vector2(g,q))}break;case THREE.PathActions.BEZIER_CURVE_TO:h=f[4];i=f[5];n=f[0];k=f[1];j=f[2];l=f[3];if(c.length>0){g=c[c.length-1];m=g.x;p=g.y}else{g=this.actions[d-1].args;m=g[g.length-2];p=g[g.length-1]}for(f=1;f<=b;f++){q=f/b;g=THREE.Shape.Utils.b3(q,m,n,j,h);q=THREE.Shape.Utils.b3(q,p,k,l,i);c.push(new THREE.Vector2(g,
  12202. q))}break;case THREE.PathActions.CSPLINE_THRU:g=this.actions[d-1].args;q=[new THREE.Vector2(g[g.length-2],g[g.length-1])];g=b*f[0].length;q=q.concat(f[0]);q=new THREE.SplineCurve(q);for(f=1;f<=g;f++)c.push(q.getPointAt(f/g));break;case THREE.PathActions.ARC:h=f[0];i=f[1];j=f[2];n=f[3];k=!!f[5];l=f[4]-n;m=b*2;for(f=1;f<=m;f++){q=f/m;k||(q=1-q);q=n+q*l;g=h+j*Math.cos(q);q=i+j*Math.sin(q);c.push(new THREE.Vector2(g,q))}}}d=c[c.length-1];Math.abs(d.x-c[0].x)<1.0E-10&&Math.abs(d.y-c[0].y)<1.0E-10&&c.splice(c.length-
  12203. 1,1);a&&c.push(c[0]);return c};THREE.Path.prototype.transform=function(b,a){this.getBoundingBox();return this.getWrapPoints(this.getPoints(a),b)};THREE.Path.prototype.nltransform=function(b,a,c,d,e,f){var g=this.getPoints(),h,i,j,l,n;h=0;for(i=g.length;h<i;h++){j=g[h];l=j.x;n=j.y;j.x=b*l+a*n+c;j.y=d*n+e*l+f}return g};
  12204. THREE.Path.prototype.debug=function(b){var a=this.getBoundingBox();if(!b){b=document.createElement("canvas");b.setAttribute("width",a.maxX+100);b.setAttribute("height",a.maxY+100);document.body.appendChild(b)}a=b.getContext("2d");a.fillStyle="white";a.fillRect(0,0,b.width,b.height);a.strokeStyle="black";a.beginPath();var c,d,e,b=0;for(c=this.actions.length;b<c;b++){d=this.actions[b];e=d.args;d=d.action;d!=THREE.PathActions.CSPLINE_THRU&&a[d].apply(a,e)}a.stroke();a.closePath();a.strokeStyle="red";
  12205. d=this.getPoints();b=0;for(c=d.length;b<c;b++){e=d[b];a.beginPath();a.arc(e.x,e.y,1.5,0,Math.PI*2,false);a.stroke();a.closePath()}};
  12206. THREE.Path.prototype.toShapes=function(){var b,a,c,d,e=[],f=new THREE.Path;b=0;for(a=this.actions.length;b<a;b++){c=this.actions[b];d=c.args;c=c.action;if(c==THREE.PathActions.MOVE_TO&&f.actions.length!=0){e.push(f);f=new THREE.Path}f[c].apply(f,d)}f.actions.length!=0&&e.push(f);if(e.length==0)return[];var g;d=[];b=!THREE.Shape.Utils.isClockWise(e[0].getPoints());if(e.length==1){f=e[0];g=new THREE.Shape;g.actions=f.actions;g.curves=f.curves;d.push(g);return d}if(b){g=new THREE.Shape;b=0;for(a=e.length;b<
  12207. a;b++){f=e[b];if(THREE.Shape.Utils.isClockWise(f.getPoints())){g.actions=f.actions;g.curves=f.curves;d.push(g);g=new THREE.Shape}else g.holes.push(f)}}else{b=0;for(a=e.length;b<a;b++){f=e[b];if(THREE.Shape.Utils.isClockWise(f.getPoints())){g&&d.push(g);g=new THREE.Shape;g.actions=f.actions;g.curves=f.curves}else g.holes.push(f)}d.push(g)}return d};THREE.Shape=function(){THREE.Path.apply(this,arguments);this.holes=[]};THREE.Shape.prototype=new THREE.Path;THREE.Shape.prototype.constructor=THREE.Path;
  12208. THREE.Shape.prototype.extrude=function(b){return new THREE.ExtrudeGeometry(this,b)};THREE.Shape.prototype.getPointsHoles=function(b){var a,c=this.holes.length,d=[];for(a=0;a<c;a++)d[a]=this.holes[a].getTransformedPoints(b,this.bends);return d};THREE.Shape.prototype.getSpacedPointsHoles=function(b){var a,c=this.holes.length,d=[];for(a=0;a<c;a++)d[a]=this.holes[a].getTransformedSpacedPoints(b,this.bends);return d};
  12209. THREE.Shape.prototype.extractAllPoints=function(b){return{shape:this.getTransformedPoints(b),holes:this.getPointsHoles(b)}};THREE.Shape.prototype.extractPoints=function(b){return this.useSpacedPoints?this.extractAllSpacedPoints(b):this.extractAllPoints(b)};THREE.Shape.prototype.extractAllSpacedPoints=function(b){return{shape:this.getTransformedSpacedPoints(b),holes:this.getSpacedPointsHoles(b)}};
  12210. THREE.Shape.Utils={removeHoles:function(b,a){var c=b.concat(),d=c.concat(),e,f,g,h,i,j,l,n,k,m,p=[];for(i=0;i<a.length;i++){j=a[i];Array.prototype.push.apply(d,j);f=Number.POSITIVE_INFINITY;for(e=0;e<j.length;e++){k=j[e];m=[];for(n=0;n<c.length;n++){l=c[n];l=k.distanceToSquared(l);m.push(l);if(l<f){f=l;g=e;h=n}}}e=h-1>=0?h-1:c.length-1;f=g-1>=0?g-1:j.length-1;var q=[j[g],c[h],c[e]];n=THREE.FontUtils.Triangulate.area(q);var r=[j[g],j[f],c[h]];k=THREE.FontUtils.Triangulate.area(r);m=h;l=g;h=h+1;g=g+
  12211. -1;h<0&&(h=h+c.length);h=h%c.length;g<0&&(g=g+j.length);g=g%j.length;e=h-1>=0?h-1:c.length-1;f=g-1>=0?g-1:j.length-1;q=[j[g],c[h],c[e]];q=THREE.FontUtils.Triangulate.area(q);r=[j[g],j[f],c[h]];r=THREE.FontUtils.Triangulate.area(r);if(n+k>q+r){h=m;g=l;h<0&&(h=h+c.length);h=h%c.length;g<0&&(g=g+j.length);g=g%j.length;e=h-1>=0?h-1:c.length-1;f=g-1>=0?g-1:j.length-1}n=c.slice(0,h);k=c.slice(h);m=j.slice(g);l=j.slice(0,g);f=[j[g],j[f],c[h]];p.push([j[g],c[h],c[e]]);p.push(f);c=n.concat(m).concat(l).concat(k)}return{shape:c,
  12212. isolatedPts:p,allpoints:d}},triangulateShape:function(b,a){var c=THREE.Shape.Utils.removeHoles(b,a),d=c.allpoints,e=c.isolatedPts,c=THREE.FontUtils.Triangulate(c.shape,false),f,g,h,i,j={};f=0;for(g=d.length;f<g;f++){i=d[f].x+":"+d[f].y;j[i]!==void 0&&console.log("Duplicate point",i);j[i]=f}f=0;for(g=c.length;f<g;f++){h=c[f];for(d=0;d<3;d++){i=h[d].x+":"+h[d].y;i=j[i];i!==void 0&&(h[d]=i)}}f=0;for(g=e.length;f<g;f++){h=e[f];for(d=0;d<3;d++){i=h[d].x+":"+h[d].y;i=j[i];i!==void 0&&(h[d]=i)}}return c.concat(e)},
  12213. isClockWise:function(b){return THREE.FontUtils.Triangulate.area(b)<0},b2p0:function(b,a){var c=1-b;return c*c*a},b2p1:function(b,a){return 2*(1-b)*b*a},b2p2:function(b,a){return b*b*a},b2:function(b,a,c,d){return this.b2p0(b,a)+this.b2p1(b,c)+this.b2p2(b,d)},b3p0:function(b,a){var c=1-b;return c*c*c*a},b3p1:function(b,a){var c=1-b;return 3*c*c*b*a},b3p2:function(b,a){return 3*(1-b)*b*b*a},b3p3:function(b,a){return b*b*b*a},b3:function(b,a,c,d,e){return this.b3p0(b,a)+this.b3p1(b,c)+this.b3p2(b,d)+
  12214. this.b3p3(b,e)}};THREE.TextPath=function(b,a){THREE.Path.call(this);this.parameters=a||{};this.set(b)};THREE.TextPath.prototype.set=function(b,a){a=a||this.parameters;this.text=b;var c=a.curveSegments!==void 0?a.curveSegments:4,d=a.font!==void 0?a.font:"helvetiker",e=a.weight!==void 0?a.weight:"normal",f=a.style!==void 0?a.style:"normal";THREE.FontUtils.size=a.size!==void 0?a.size:100;THREE.FontUtils.divisions=c;THREE.FontUtils.face=d;THREE.FontUtils.weight=e;THREE.FontUtils.style=f};
  12215. THREE.TextPath.prototype.toShapes=function(){for(var b=THREE.FontUtils.drawText(this.text).paths,a=[],c=0,d=b.length;c<d;c++)Array.prototype.push.apply(a,b[c].toShapes());return a};
  12216. THREE.AnimationHandler=function(){var b=[],a={},c={update:function(a){for(var c=0;c<b.length;c++)b[c].update(a)},addToUpdate:function(a){b.indexOf(a)===-1&&b.push(a)},removeFromUpdate:function(a){a=b.indexOf(a);a!==-1&&b.splice(a,1)},add:function(b){a[b.name]!==void 0&&console.log("THREE.AnimationHandler.add: Warning! "+b.name+" already exists in library. Overwriting.");a[b.name]=b;if(b.initialized!==true){for(var c=0;c<b.hierarchy.length;c++){for(var d=0;d<b.hierarchy[c].keys.length;d++){if(b.hierarchy[c].keys[d].time<
  12217. 0)b.hierarchy[c].keys[d].time=0;if(b.hierarchy[c].keys[d].rot!==void 0&&!(b.hierarchy[c].keys[d].rot instanceof THREE.Quaternion)){var h=b.hierarchy[c].keys[d].rot;b.hierarchy[c].keys[d].rot=new THREE.Quaternion(h[0],h[1],h[2],h[3])}}if(b.hierarchy[c].keys.length&&b.hierarchy[c].keys[0].morphTargets!==void 0){h={};for(d=0;d<b.hierarchy[c].keys.length;d++)for(var i=0;i<b.hierarchy[c].keys[d].morphTargets.length;i++){var j=b.hierarchy[c].keys[d].morphTargets[i];h[j]=-1}b.hierarchy[c].usedMorphTargets=
  12218. h;for(d=0;d<b.hierarchy[c].keys.length;d++){var l={};for(j in h){for(i=0;i<b.hierarchy[c].keys[d].morphTargets.length;i++)if(b.hierarchy[c].keys[d].morphTargets[i]===j){l[j]=b.hierarchy[c].keys[d].morphTargetsInfluences[i];break}i===b.hierarchy[c].keys[d].morphTargets.length&&(l[j]=0)}b.hierarchy[c].keys[d].morphTargetsInfluences=l}}for(d=1;d<b.hierarchy[c].keys.length;d++)if(b.hierarchy[c].keys[d].time===b.hierarchy[c].keys[d-1].time){b.hierarchy[c].keys.splice(d,1);d--}for(d=0;d<b.hierarchy[c].keys.length;d++)b.hierarchy[c].keys[d].index=
  12219. d}d=parseInt(b.length*b.fps,10);b.JIT={};b.JIT.hierarchy=[];for(c=0;c<b.hierarchy.length;c++)b.JIT.hierarchy.push(Array(d));b.initialized=true}},get:function(b){if(typeof b==="string"){if(a[b])return a[b];console.log("THREE.AnimationHandler.get: Couldn't find animation "+b);return null}},parse:function(a){var b=[];if(a instanceof THREE.SkinnedMesh)for(var c=0;c<a.bones.length;c++)b.push(a.bones[c]);else d(a,b);return b}},d=function(a,b){b.push(a);for(var c=0;c<a.children.length;c++)d(a.children[c],
  12220. b)};c.LINEAR=0;c.CATMULLROM=1;c.CATMULLROM_FORWARD=2;return c}();THREE.Animation=function(b,a,c,d){this.root=b;this.data=THREE.AnimationHandler.get(a);this.hierarchy=THREE.AnimationHandler.parse(b);this.currentTime=0;this.timeScale=1;this.isPlaying=false;this.loop=this.isPaused=true;this.interpolationType=c!==void 0?c:THREE.AnimationHandler.LINEAR;this.JITCompile=d!==void 0?d:true;this.points=[];this.target=new THREE.Vector3};
  12221. THREE.Animation.prototype.play=function(b,a){if(!this.isPlaying){this.isPlaying=true;this.loop=b!==void 0?b:true;this.currentTime=a!==void 0?a:0;var c,d=this.hierarchy.length,e;for(c=0;c<d;c++){e=this.hierarchy[c];if(this.interpolationType!==THREE.AnimationHandler.CATMULLROM_FORWARD)e.useQuaternion=true;e.matrixAutoUpdate=true;if(e.animationCache===void 0){e.animationCache={};e.animationCache.prevKey={pos:0,rot:0,scl:0};e.animationCache.nextKey={pos:0,rot:0,scl:0};e.animationCache.originalMatrix=
  12222. e instanceof THREE.Bone?e.skinMatrix:e.matrix}var f=e.animationCache.prevKey;e=e.animationCache.nextKey;f.pos=this.data.hierarchy[c].keys[0];f.rot=this.data.hierarchy[c].keys[0];f.scl=this.data.hierarchy[c].keys[0];e.pos=this.getNextKeyWith("pos",c,1);e.rot=this.getNextKeyWith("rot",c,1);e.scl=this.getNextKeyWith("scl",c,1)}this.update(0)}this.isPaused=false;THREE.AnimationHandler.addToUpdate(this)};
  12223. THREE.Animation.prototype.pause=function(){this.isPaused?THREE.AnimationHandler.addToUpdate(this):THREE.AnimationHandler.removeFromUpdate(this);this.isPaused=!this.isPaused};
  12224. THREE.Animation.prototype.stop=function(){this.isPaused=this.isPlaying=false;THREE.AnimationHandler.removeFromUpdate(this);for(var b=0;b<this.hierarchy.length;b++)if(this.hierarchy[b].animationCache!==void 0){this.hierarchy[b]instanceof THREE.Bone?this.hierarchy[b].skinMatrix=this.hierarchy[b].animationCache.originalMatrix:this.hierarchy[b].matrix=this.hierarchy[b].animationCache.originalMatrix;delete this.hierarchy[b].animationCache}};
  12225. THREE.Animation.prototype.update=function(b){if(this.isPlaying){var a=["pos","rot","scl"],c,d,e,f,g,h,i,j,l=this.data.JIT.hierarchy,n,k;k=this.currentTime=this.currentTime+b*this.timeScale;n=this.currentTime=this.currentTime%this.data.length;j=parseInt(Math.min(n*this.data.fps,this.data.length*this.data.fps),10);for(var m=0,p=this.hierarchy.length;m<p;m++){b=this.hierarchy[m];i=b.animationCache;if(this.JITCompile&&l[m][j]!==void 0)if(b instanceof THREE.Bone){b.skinMatrix=l[m][j];b.matrixAutoUpdate=
  12226. false;b.matrixWorldNeedsUpdate=false}else{b.matrix=l[m][j];b.matrixAutoUpdate=false;b.matrixWorldNeedsUpdate=true}else{if(this.JITCompile)b instanceof THREE.Bone?b.skinMatrix=b.animationCache.originalMatrix:b.matrix=b.animationCache.originalMatrix;for(var q=0;q<3;q++){c=a[q];g=i.prevKey[c];h=i.nextKey[c];if(h.time<=k){if(n<k)if(this.loop){g=this.data.hierarchy[m].keys[0];for(h=this.getNextKeyWith(c,m,1);h.time<n;){g=h;h=this.getNextKeyWith(c,m,h.index+1)}}else{this.stop();return}else{do{g=h;h=this.getNextKeyWith(c,
  12227. m,h.index+1)}while(h.time<n)}i.prevKey[c]=g;i.nextKey[c]=h}b.matrixAutoUpdate=true;b.matrixWorldNeedsUpdate=true;d=(n-g.time)/(h.time-g.time);e=g[c];f=h[c];if(d<0||d>1){console.log("THREE.Animation.update: Warning! Scale out of bounds:"+d+" on bone "+m);d=d<0?0:1}if(c==="pos"){c=b.position;if(this.interpolationType===THREE.AnimationHandler.LINEAR){c.x=e[0]+(f[0]-e[0])*d;c.y=e[1]+(f[1]-e[1])*d;c.z=e[2]+(f[2]-e[2])*d}else if(this.interpolationType===THREE.AnimationHandler.CATMULLROM||this.interpolationType===
  12228. THREE.AnimationHandler.CATMULLROM_FORWARD){this.points[0]=this.getPrevKeyWith("pos",m,g.index-1).pos;this.points[1]=e;this.points[2]=f;this.points[3]=this.getNextKeyWith("pos",m,h.index+1).pos;d=d*0.33+0.33;e=this.interpolateCatmullRom(this.points,d);c.x=e[0];c.y=e[1];c.z=e[2];if(this.interpolationType===THREE.AnimationHandler.CATMULLROM_FORWARD){d=this.interpolateCatmullRom(this.points,d*1.01);this.target.set(d[0],d[1],d[2]);this.target.subSelf(c);this.target.y=0;this.target.normalize();d=Math.atan2(this.target.x,
  12229. this.target.z);b.rotation.set(0,d,0)}}}else if(c==="rot")THREE.Quaternion.slerp(e,f,b.quaternion,d);else if(c==="scl"){c=b.scale;c.x=e[0]+(f[0]-e[0])*d;c.y=e[1]+(f[1]-e[1])*d;c.z=e[2]+(f[2]-e[2])*d}}}}if(this.JITCompile&&l[0][j]===void 0){this.hierarchy[0].updateMatrixWorld(true);for(m=0;m<this.hierarchy.length;m++)l[m][j]=this.hierarchy[m]instanceof THREE.Bone?this.hierarchy[m].skinMatrix.clone():this.hierarchy[m].matrix.clone()}}};
  12230. THREE.Animation.prototype.interpolateCatmullRom=function(b,a){var c=[],d=[],e,f,g,h,i,j;e=(b.length-1)*a;f=Math.floor(e);e=e-f;c[0]=f===0?f:f-1;c[1]=f;c[2]=f>b.length-2?f:f+1;c[3]=f>b.length-3?f:f+2;f=b[c[0]];h=b[c[1]];i=b[c[2]];j=b[c[3]];c=e*e;g=e*c;d[0]=this.interpolate(f[0],h[0],i[0],j[0],e,c,g);d[1]=this.interpolate(f[1],h[1],i[1],j[1],e,c,g);d[2]=this.interpolate(f[2],h[2],i[2],j[2],e,c,g);return d};
  12231. THREE.Animation.prototype.interpolate=function(b,a,c,d,e,f,g){b=(c-b)*0.5;d=(d-a)*0.5;return(2*(a-c)+b+d)*g+(-3*(a-c)-2*b-d)*f+b*e+a};THREE.Animation.prototype.getNextKeyWith=function(b,a,c){for(var d=this.data.hierarchy[a].keys,c=this.interpolationType===THREE.AnimationHandler.CATMULLROM||this.interpolationType===THREE.AnimationHandler.CATMULLROM_FORWARD?c<d.length-1?c:d.length-1:c%d.length;c<d.length;c++)if(d[c][b]!==void 0)return d[c];return this.data.hierarchy[a].keys[0]};
  12232. THREE.Animation.prototype.getPrevKeyWith=function(b,a,c){for(var d=this.data.hierarchy[a].keys,c=this.interpolationType===THREE.AnimationHandler.CATMULLROM||this.interpolationType===THREE.AnimationHandler.CATMULLROM_FORWARD?c>0?c:0:c>=0?c:c+d.length;c>=0;c--)if(d[c][b]!==void 0)return d[c];return this.data.hierarchy[a].keys[d.length-1]};
  12233. THREE.KeyFrameAnimation=function(b,a,c){this.root=b;this.data=THREE.AnimationHandler.get(a);this.hierarchy=THREE.AnimationHandler.parse(b);this.currentTime=0;this.timeScale=0.001;this.isPlaying=false;this.loop=this.isPaused=true;this.JITCompile=c!==void 0?c:true;b=0;for(a=this.hierarchy.length;b<a;b++){var c=this.data.hierarchy[b].sids,d=this.hierarchy[b];if(this.data.hierarchy[b].keys.length&&c){for(var e=0;e<c.length;e++){var f=c[e],g=this.getNextKeyWith(f,b,0);g&&g.apply(f)}d.matrixAutoUpdate=
  12234. false;this.data.hierarchy[b].node.updateMatrix();d.matrixWorldNeedsUpdate=true}}};
  12235. THREE.KeyFrameAnimation.prototype.play=function(b,a){if(!this.isPlaying){this.isPlaying=true;this.loop=b!==void 0?b:true;this.currentTime=a!==void 0?a:0;this.startTimeMs=a;this.startTime=1E7;this.endTime=-this.startTime;var c,d=this.hierarchy.length,e,f;for(c=0;c<d;c++){e=this.hierarchy[c];f=this.data.hierarchy[c];e.useQuaternion=true;if(f.animationCache===void 0){f.animationCache={};f.animationCache.prevKey=null;f.animationCache.nextKey=null;f.animationCache.originalMatrix=e instanceof THREE.Bone?
  12236. e.skinMatrix:e.matrix}e=this.data.hierarchy[c].keys;if(e.length){f.animationCache.prevKey=e[0];f.animationCache.nextKey=e[1];this.startTime=Math.min(e[0].time,this.startTime);this.endTime=Math.max(e[e.length-1].time,this.endTime)}}this.update(0)}this.isPaused=false;THREE.AnimationHandler.addToUpdate(this)};THREE.KeyFrameAnimation.prototype.pause=function(){this.isPaused?THREE.AnimationHandler.addToUpdate(this):THREE.AnimationHandler.removeFromUpdate(this);this.isPaused=!this.isPaused};
  12237. THREE.KeyFrameAnimation.prototype.stop=function(){this.isPaused=this.isPlaying=false;THREE.AnimationHandler.removeFromUpdate(this);for(var b=0;b<this.data.hierarchy.length;b++){var a=this.hierarchy[b],c=this.data.hierarchy[b];if(c.animationCache!==void 0){var d=c.animationCache.originalMatrix;if(a instanceof THREE.Bone){d.copy(a.skinMatrix);a.skinMatrix=d}else{d.copy(a.matrix);a.matrix=d}delete c.animationCache}}};
  12238. THREE.KeyFrameAnimation.prototype.update=function(b){if(this.isPlaying){var a,c,d,e,f=this.data.JIT.hierarchy,g,h,i;h=this.currentTime=this.currentTime+b*this.timeScale;g=this.currentTime=this.currentTime%this.data.length;if(g<this.startTimeMs)g=this.currentTime=this.startTimeMs+g;e=parseInt(Math.min(g*this.data.fps,this.data.length*this.data.fps),10);if((i=g<h)&&!this.loop){for(var b=0,j=this.hierarchy.length;b<j;b++){var l=this.data.hierarchy[b].keys,f=this.data.hierarchy[b].sids;d=l.length-1;e=
  12239. this.hierarchy[b];if(l.length){for(l=0;l<f.length;l++){g=f[l];(h=this.getPrevKeyWith(g,b,d))&&h.apply(g)}this.data.hierarchy[b].node.updateMatrix();e.matrixWorldNeedsUpdate=true}}this.stop()}else if(!(g<this.startTime)){b=0;for(j=this.hierarchy.length;b<j;b++){d=this.hierarchy[b];a=this.data.hierarchy[b];var l=a.keys,n=a.animationCache;if(this.JITCompile&&f[b][e]!==void 0)if(d instanceof THREE.Bone){d.skinMatrix=f[b][e];d.matrixWorldNeedsUpdate=false}else{d.matrix=f[b][e];d.matrixWorldNeedsUpdate=
  12240. true}else if(l.length){if(this.JITCompile&&n)d instanceof THREE.Bone?d.skinMatrix=n.originalMatrix:d.matrix=n.originalMatrix;a=n.prevKey;c=n.nextKey;if(a&&c){if(c.time<=h){if(i&&this.loop){a=l[0];for(c=l[1];c.time<g;){a=c;c=l[a.index+1]}}else if(!i)for(var k=l.length-1;c.time<g&&c.index!==k;){a=c;c=l[a.index+1]}n.prevKey=a;n.nextKey=c}c.time>=g?a.interpolate(c,g):a.interpolate(c,c.time)}this.data.hierarchy[b].node.updateMatrix();d.matrixWorldNeedsUpdate=true}}if(this.JITCompile&&f[0][e]===void 0){this.hierarchy[0].updateMatrixWorld(true);
  12241. for(b=0;b<this.hierarchy.length;b++)f[b][e]=this.hierarchy[b]instanceof THREE.Bone?this.hierarchy[b].skinMatrix.clone():this.hierarchy[b].matrix.clone()}}}};THREE.KeyFrameAnimation.prototype.getNextKeyWith=function(b,a,c){a=this.data.hierarchy[a].keys;for(c=c%a.length;c<a.length;c++)if(a[c].hasTarget(b))return a[c];return a[0]};
  12242. THREE.KeyFrameAnimation.prototype.getPrevKeyWith=function(b,a,c){a=this.data.hierarchy[a].keys;for(c=c>=0?c:c+a.length;c>=0;c--)if(a[c].hasTarget(b))return a[c];return a[a.length-1]};
  12243. THREE.CubeCamera=function(b,a,c){THREE.Object3D.call(this);var d=new THREE.PerspectiveCamera(90,1,b,a);d.up.set(0,-1,0);d.lookAt(new THREE.Vector3(1,0,0));this.add(d);var e=new THREE.PerspectiveCamera(90,1,b,a);e.up.set(0,-1,0);e.lookAt(new THREE.Vector3(-1,0,0));this.add(e);var f=new THREE.PerspectiveCamera(90,1,b,a);f.up.set(0,0,1);f.lookAt(new THREE.Vector3(0,1,0));this.add(f);var g=new THREE.PerspectiveCamera(90,1,b,a);g.up.set(0,0,-1);g.lookAt(new THREE.Vector3(0,-1,0));this.add(g);var h=new THREE.PerspectiveCamera(90,
  12244. 1,b,a);h.up.set(0,-1,0);h.lookAt(new THREE.Vector3(0,0,1));this.add(h);var i=new THREE.PerspectiveCamera(90,1,b,a);i.up.set(0,-1,0);i.lookAt(new THREE.Vector3(0,0,-1));this.add(i);this.renderTarget=new THREE.WebGLRenderTargetCube(c,c,{format:THREE.RGBFormat,magFilter:THREE.LinearFilter,minFilter:THREE.LinearFilter});this.updateCubeMap=function(a,b){var c=this.renderTarget,k=c.generateMipmaps;c.generateMipmaps=false;c.activeCubeFace=0;a.render(b,d,c);c.activeCubeFace=1;a.render(b,e,c);c.activeCubeFace=
  12245. 2;a.render(b,f,c);c.activeCubeFace=3;a.render(b,g,c);c.activeCubeFace=4;a.render(b,h,c);c.generateMipmaps=k;c.activeCubeFace=5;a.render(b,i,c)}};THREE.CubeCamera.prototype=new THREE.Object3D;THREE.CubeCamera.prototype.constructor=THREE.CubeCamera;
  12246. THREE.CombinedCamera=function(b,a,c,d,e,f,g){THREE.Camera.call(this);this.fov=c;this.left=-b/2;this.right=b/2;this.top=a/2;this.bottom=-a/2;this.cameraO=new THREE.OrthographicCamera(b/-2,b/2,a/2,a/-2,f,g);this.cameraP=new THREE.PerspectiveCamera(c,b/a,d,e);this.zoom=1;this.toPerspective()};THREE.CombinedCamera.prototype=new THREE.Camera;THREE.CombinedCamera.prototype.constructor=THREE.CombinedCamera;
  12247. THREE.CombinedCamera.prototype.toPerspective=function(){this.near=this.cameraP.near;this.far=this.cameraP.far;this.cameraP.fov=this.fov/this.zoom;this.cameraP.updateProjectionMatrix();this.projectionMatrix=this.cameraP.projectionMatrix;this.inPersepectiveMode=true;this.inOrthographicMode=false};
  12248. THREE.CombinedCamera.prototype.toOrthographic=function(){var b=this.cameraP.aspect,a=(this.cameraP.near+this.cameraP.far)/2,a=Math.tan(this.fov/2)*a,b=2*a*b/2,a=a/this.zoom,b=b/this.zoom;this.cameraO.left=-b;this.cameraO.right=b;this.cameraO.top=a;this.cameraO.bottom=-a;this.cameraO.updateProjectionMatrix();this.near=this.cameraO.near;this.far=this.cameraO.far;this.projectionMatrix=this.cameraO.projectionMatrix;this.inPersepectiveMode=false;this.inOrthographicMode=true};
  12249. THREE.CombinedCamera.prototype.setSize=function(b,a){this.cameraP.aspect=b/a;this.left=-b/2;this.right=b/2;this.top=a/2;this.bottom=-a/2};THREE.CombinedCamera.prototype.setFov=function(b){this.fov=b;this.inPersepectiveMode?this.toPerspective():this.toOrthographic()};THREE.CombinedCamera.prototype.updateProjectionMatrix=function(){if(this.inPersepectiveMode)this.toPerspective();else{this.toPerspective();this.toOrthographic()}};
  12250. THREE.CombinedCamera.prototype.setLens=function(b,a){var c=2*Math.atan((a!==void 0?a:24)/(b*2))*(180/Math.PI);this.setFov(c);return c};THREE.CombinedCamera.prototype.setZoom=function(b){this.zoom=b;this.inPersepectiveMode?this.toPerspective():this.toOrthographic()};THREE.CombinedCamera.prototype.toFrontView=function(){this.rotation.x=0;this.rotation.y=0;this.rotation.z=0;this.rotationAutoUpdate=false};
  12251. THREE.CombinedCamera.prototype.toBackView=function(){this.rotation.x=0;this.rotation.y=Math.PI;this.rotation.z=0;this.rotationAutoUpdate=false};THREE.CombinedCamera.prototype.toLeftView=function(){this.rotation.x=0;this.rotation.y=-Math.PI/2;this.rotation.z=0;this.rotationAutoUpdate=false};THREE.CombinedCamera.prototype.toRightView=function(){this.rotation.x=0;this.rotation.y=Math.PI/2;this.rotation.z=0;this.rotationAutoUpdate=false};
  12252. THREE.CombinedCamera.prototype.toTopView=function(){this.rotation.x=-Math.PI/2;this.rotation.y=0;this.rotation.z=0;this.rotationAutoUpdate=false};THREE.CombinedCamera.prototype.toBottomView=function(){this.rotation.x=Math.PI/2;this.rotation.y=0;this.rotation.z=0;this.rotationAutoUpdate=false};
  12253. THREE.FirstPersonControls=function(b,a){function c(a,b){return function(){b.apply(a,arguments)}}this.object=b;this.target=new THREE.Vector3(0,0,0);this.domElement=a!==void 0?a:document;this.movementSpeed=1;this.lookSpeed=0.005;this.noFly=false;this.lookVertical=true;this.autoForward=false;this.activeLook=true;this.heightSpeed=false;this.heightCoef=1;this.heightMin=0;this.constrainVertical=false;this.verticalMin=0;this.verticalMax=Math.PI;this.theta=this.phi=this.lon=this.lat=this.mouseY=this.mouseX=
  12254. this.autoSpeedFactor=0;this.mouseDragOn=this.freeze=this.moveRight=this.moveLeft=this.moveBackward=this.moveForward=false;if(this.domElement===document){this.viewHalfX=window.innerWidth/2;this.viewHalfY=window.innerHeight/2}else{this.viewHalfX=this.domElement.offsetWidth/2;this.viewHalfY=this.domElement.offsetHeight/2;this.domElement.setAttribute("tabindex",-1)}this.onMouseDown=function(a){this.domElement!==document&&this.domElement.focus();a.preventDefault();a.stopPropagation();if(this.activeLook)switch(a.button){case 0:this.moveForward=
  12255. true;break;case 2:this.moveBackward=true}this.mouseDragOn=true};this.onMouseUp=function(a){a.preventDefault();a.stopPropagation();if(this.activeLook)switch(a.button){case 0:this.moveForward=false;break;case 2:this.moveBackward=false}this.mouseDragOn=false};this.onMouseMove=function(a){if(this.domElement===document){this.mouseX=a.pageX-this.viewHalfX;this.mouseY=a.pageY-this.viewHalfY}else{this.mouseX=a.pageX-this.domElement.offsetLeft-this.viewHalfX;this.mouseY=a.pageY-this.domElement.offsetTop-this.viewHalfY}};
  12256. this.onKeyDown=function(a){switch(a.keyCode){case 38:case 87:this.moveForward=true;break;case 37:case 65:this.moveLeft=true;break;case 40:case 83:this.moveBackward=true;break;case 39:case 68:this.moveRight=true;break;case 82:this.moveUp=true;break;case 70:this.moveDown=true;break;case 81:this.freeze=!this.freeze}};this.onKeyUp=function(a){switch(a.keyCode){case 38:case 87:this.moveForward=false;break;case 37:case 65:this.moveLeft=false;break;case 40:case 83:this.moveBackward=false;break;case 39:case 68:this.moveRight=
  12257. false;break;case 82:this.moveUp=false;break;case 70:this.moveDown=false}};this.update=function(a){var b=0;if(!this.freeze){if(this.heightSpeed){b=THREE.Math.clamp(this.object.position.y,this.heightMin,this.heightMax)-this.heightMin;this.autoSpeedFactor=a*b*this.heightCoef}else this.autoSpeedFactor=0;b=a*this.movementSpeed;(this.moveForward||this.autoForward&&!this.moveBackward)&&this.object.translateZ(-(b+this.autoSpeedFactor));this.moveBackward&&this.object.translateZ(b);this.moveLeft&&this.object.translateX(-b);
  12258. this.moveRight&&this.object.translateX(b);this.moveUp&&this.object.translateY(b);this.moveDown&&this.object.translateY(-b);a=a*this.lookSpeed;this.activeLook||(a=0);this.lon=this.lon+this.mouseX*a;if(this.lookVertical)this.lat=this.lat-this.mouseY*a;this.lat=Math.max(-85,Math.min(85,this.lat));this.phi=(90-this.lat)*Math.PI/180;this.theta=this.lon*Math.PI/180;var b=this.target,c=this.object.position;b.x=c.x+100*Math.sin(this.phi)*Math.cos(this.theta);b.y=c.y+100*Math.cos(this.phi);b.z=c.z+100*Math.sin(this.phi)*
  12259. Math.sin(this.theta);b=1;this.constrainVertical&&(b=Math.PI/(this.verticalMax-this.verticalMin));this.lon=this.lon+this.mouseX*a;if(this.lookVertical)this.lat=this.lat-this.mouseY*a*b;this.lat=Math.max(-85,Math.min(85,this.lat));this.phi=(90-this.lat)*Math.PI/180;this.theta=this.lon*Math.PI/180;if(this.constrainVertical)this.phi=THREE.Math.mapLinear(this.phi,0,Math.PI,this.verticalMin,this.verticalMax);b=this.target;c=this.object.position;b.x=c.x+100*Math.sin(this.phi)*Math.cos(this.theta);b.y=c.y+
  12260. 100*Math.cos(this.phi);b.z=c.z+100*Math.sin(this.phi)*Math.sin(this.theta);this.object.lookAt(b)}};this.domElement.addEventListener("contextmenu",function(a){a.preventDefault()},false);this.domElement.addEventListener("mousemove",c(this,this.onMouseMove),false);this.domElement.addEventListener("mousedown",c(this,this.onMouseDown),false);this.domElement.addEventListener("mouseup",c(this,this.onMouseUp),false);this.domElement.addEventListener("keydown",c(this,this.onKeyDown),false);this.domElement.addEventListener("keyup",
  12261. c(this,this.onKeyUp),false)};
  12262. THREE.PathControls=function(b,a){function c(a){return(a=a*2)<1?0.5*a*a:-0.5*(--a*(a-2)-1)}function d(a,b){return function(){b.apply(a,arguments)}}function e(a,b,c,d){var e={name:c,fps:0.6,length:d,hierarchy:[]},f,g=b.getControlPointsArray(),h=b.getLength(),r=g.length,u=0;f=r-1;b={parent:-1,keys:[]};b.keys[0]={time:0,pos:g[0],rot:[0,0,0,1],scl:[1,1,1]};b.keys[f]={time:d,pos:g[f],rot:[0,0,0,1],scl:[1,1,1]};for(f=1;f<r-1;f++){u=d*h.chunks[f]/h.total;b.keys[f]={time:u,pos:g[f]}}e.hierarchy[0]=b;THREE.AnimationHandler.add(e);
  12263. return new THREE.Animation(a,c,THREE.AnimationHandler.CATMULLROM_FORWARD,false)}function f(a,b){var c,d,e=new THREE.Geometry;for(c=0;c<a.points.length*b;c++){d=c/(a.points.length*b);d=a.getPoint(d);e.vertices[c]=new THREE.Vector3(d.x,d.y,d.z)}return e}this.object=b;this.domElement=a!==void 0?a:document;this.id="PathControls"+THREE.PathControlsIdCounter++;this.duration=1E4;this.waypoints=[];this.useConstantSpeed=true;this.resamplingCoef=50;this.debugPath=new THREE.Object3D;this.debugDummy=new THREE.Object3D;
  12264. this.animationParent=new THREE.Object3D;this.lookSpeed=0.005;this.lookHorizontal=this.lookVertical=true;this.verticalAngleMap={srcRange:[0,2*Math.PI],dstRange:[0,2*Math.PI]};this.horizontalAngleMap={srcRange:[0,2*Math.PI],dstRange:[0,2*Math.PI]};this.target=new THREE.Object3D;this.theta=this.phi=this.lon=this.lat=this.mouseY=this.mouseX=0;if(this.domElement===document){this.viewHalfX=window.innerWidth/2;this.viewHalfY=window.innerHeight/2}else{this.viewHalfX=this.domElement.offsetWidth/2;this.viewHalfY=
  12265. this.domElement.offsetHeight/2;this.domElement.setAttribute("tabindex",-1)}var g=Math.PI*2,h=Math.PI/180;this.update=function(a){var b;if(this.lookHorizontal)this.lon=this.lon+this.mouseX*this.lookSpeed*a;if(this.lookVertical)this.lat=this.lat-this.mouseY*this.lookSpeed*a;this.lon=Math.max(0,Math.min(360,this.lon));this.lat=Math.max(-85,Math.min(85,this.lat));this.phi=(90-this.lat)*h;this.theta=this.lon*h;a=this.phi%g;this.phi=a>=0?a:a+g;b=this.verticalAngleMap.srcRange;a=this.verticalAngleMap.dstRange;
  12266. b=THREE.Math.mapLinear(this.phi,b[0],b[1],a[0],a[1]);var d=a[1]-a[0];this.phi=c((b-a[0])/d)*d+a[0];b=this.horizontalAngleMap.srcRange;a=this.horizontalAngleMap.dstRange;b=THREE.Math.mapLinear(this.theta,b[0],b[1],a[0],a[1]);d=a[1]-a[0];this.theta=c((b-a[0])/d)*d+a[0];a=this.target.position;a.x=100*Math.sin(this.phi)*Math.cos(this.theta);a.y=100*Math.cos(this.phi);a.z=100*Math.sin(this.phi)*Math.sin(this.theta);this.object.lookAt(this.target.position)};this.onMouseMove=function(a){if(this.domElement===
  12267. document){this.mouseX=a.pageX-this.viewHalfX;this.mouseY=a.pageY-this.viewHalfY}else{this.mouseX=a.pageX-this.domElement.offsetLeft-this.viewHalfX;this.mouseY=a.pageY-this.domElement.offsetTop-this.viewHalfY}};this.init=function(){this.spline=new THREE.Spline;this.spline.initFromArray(this.waypoints);this.useConstantSpeed&&this.spline.reparametrizeByArcLength(this.resamplingCoef);if(this.createDebugDummy){var a=new THREE.MeshLambertMaterial({color:30719}),b=new THREE.MeshLambertMaterial({color:65280}),
  12268. c=new THREE.CubeGeometry(10,10,20),g=new THREE.CubeGeometry(2,2,10);this.animationParent=new THREE.Mesh(c,a);a=new THREE.Mesh(g,b);a.position.set(0,10,0);this.animation=e(this.animationParent,this.spline,this.id,this.duration);this.animationParent.add(this.object);this.animationParent.add(this.target);this.animationParent.add(a)}else{this.animation=e(this.animationParent,this.spline,this.id,this.duration);this.animationParent.add(this.target);this.animationParent.add(this.object)}if(this.createDebugPath){var a=
  12269. this.debugPath,b=this.spline,g=f(b,10),c=f(b,10),h=new THREE.LineBasicMaterial({color:16711680,linewidth:3}),g=new THREE.Line(g,h),c=new THREE.ParticleSystem(c,new THREE.ParticleBasicMaterial({color:16755200,size:3}));g.scale.set(1,1,1);a.add(g);c.scale.set(1,1,1);a.add(c);for(var g=new THREE.SphereGeometry(1,16,8),h=new THREE.MeshBasicMaterial({color:65280}),m=0;m<b.points.length;m++){c=new THREE.Mesh(g,h);c.position.copy(b.points[m]);a.add(c)}}this.domElement.addEventListener("mousemove",d(this,
  12270. this.onMouseMove),false)}};THREE.PathControlsIdCounter=0;
  12271. THREE.FlyControls=function(b,a){function c(a,b){return function(){b.apply(a,arguments)}}this.object=b;this.domElement=a!==void 0?a:document;a&&this.domElement.setAttribute("tabindex",-1);this.movementSpeed=1;this.rollSpeed=0.005;this.autoForward=this.dragToLook=false;this.object.useQuaternion=true;this.tmpQuaternion=new THREE.Quaternion;this.mouseStatus=0;this.moveState={up:0,down:0,left:0,right:0,forward:0,back:0,pitchUp:0,pitchDown:0,yawLeft:0,yawRight:0,rollLeft:0,rollRight:0};this.moveVector=
  12272. new THREE.Vector3(0,0,0);this.rotationVector=new THREE.Vector3(0,0,0);this.handleEvent=function(a){if(typeof this[a.type]=="function")this[a.type](a)};this.keydown=function(a){if(!a.altKey){switch(a.keyCode){case 16:this.movementSpeedMultiplier=0.1;break;case 87:this.moveState.forward=1;break;case 83:this.moveState.back=1;break;case 65:this.moveState.left=1;break;case 68:this.moveState.right=1;break;case 82:this.moveState.up=1;break;case 70:this.moveState.down=1;break;case 38:this.moveState.pitchUp=
  12273. 1;break;case 40:this.moveState.pitchDown=1;break;case 37:this.moveState.yawLeft=1;break;case 39:this.moveState.yawRight=1;break;case 81:this.moveState.rollLeft=1;break;case 69:this.moveState.rollRight=1}this.updateMovementVector();this.updateRotationVector()}};this.keyup=function(a){switch(a.keyCode){case 16:this.movementSpeedMultiplier=1;break;case 87:this.moveState.forward=0;break;case 83:this.moveState.back=0;break;case 65:this.moveState.left=0;break;case 68:this.moveState.right=0;break;case 82:this.moveState.up=
  12274. 0;break;case 70:this.moveState.down=0;break;case 38:this.moveState.pitchUp=0;break;case 40:this.moveState.pitchDown=0;break;case 37:this.moveState.yawLeft=0;break;case 39:this.moveState.yawRight=0;break;case 81:this.moveState.rollLeft=0;break;case 69:this.moveState.rollRight=0}this.updateMovementVector();this.updateRotationVector()};this.mousedown=function(a){this.domElement!==document&&this.domElement.focus();a.preventDefault();a.stopPropagation();if(this.dragToLook)this.mouseStatus++;else switch(a.button){case 0:this.object.moveForward=
  12275. true;break;case 2:this.object.moveBackward=true}};this.mousemove=function(a){if(!this.dragToLook||this.mouseStatus>0){var b=this.getContainerDimensions(),c=b.size[0]/2,g=b.size[1]/2;this.moveState.yawLeft=-(a.pageX-b.offset[0]-c)/c;this.moveState.pitchDown=(a.pageY-b.offset[1]-g)/g;this.updateRotationVector()}};this.mouseup=function(a){a.preventDefault();a.stopPropagation();if(this.dragToLook){this.mouseStatus--;this.moveState.yawLeft=this.moveState.pitchDown=0}else switch(a.button){case 0:this.moveForward=
  12276. false;break;case 2:this.moveBackward=false}this.updateRotationVector()};this.update=function(a){var b=a*this.movementSpeed,a=a*this.rollSpeed;this.object.translateX(this.moveVector.x*b);this.object.translateY(this.moveVector.y*b);this.object.translateZ(this.moveVector.z*b);this.tmpQuaternion.set(this.rotationVector.x*a,this.rotationVector.y*a,this.rotationVector.z*a,1).normalize();this.object.quaternion.multiplySelf(this.tmpQuaternion);this.object.matrix.setPosition(this.object.position);this.object.matrix.setRotationFromQuaternion(this.object.quaternion);
  12277. this.object.matrixWorldNeedsUpdate=true};this.updateMovementVector=function(){var a=this.moveState.forward||this.autoForward&&!this.moveState.back?1:0;this.moveVector.x=-this.moveState.left+this.moveState.right;this.moveVector.y=-this.moveState.down+this.moveState.up;this.moveVector.z=-a+this.moveState.back};this.updateRotationVector=function(){this.rotationVector.x=-this.moveState.pitchDown+this.moveState.pitchUp;this.rotationVector.y=-this.moveState.yawRight+this.moveState.yawLeft;this.rotationVector.z=
  12278. -this.moveState.rollRight+this.moveState.rollLeft};this.getContainerDimensions=function(){return this.domElement!=document?{size:[this.domElement.offsetWidth,this.domElement.offsetHeight],offset:[this.domElement.offsetLeft,this.domElement.offsetTop]}:{size:[window.innerWidth,window.innerHeight],offset:[0,0]}};this.domElement.addEventListener("mousemove",c(this,this.mousemove),false);this.domElement.addEventListener("mousedown",c(this,this.mousedown),false);this.domElement.addEventListener("mouseup",
  12279. c(this,this.mouseup),false);this.domElement.addEventListener("keydown",c(this,this.keydown),false);this.domElement.addEventListener("keyup",c(this,this.keyup),false);this.updateMovementVector();this.updateRotationVector()};
  12280. THREE.RollControls=function(b,a){this.object=b;this.domElement=a!==void 0?a:document;this.mouseLook=true;this.autoForward=false;this.rollSpeed=this.movementSpeed=this.lookSpeed=1;this.constrainVertical=[-0.9,0.9];this.object.matrixAutoUpdate=false;this.forward=new THREE.Vector3(0,0,1);this.roll=0;var c=new THREE.Vector3,d=new THREE.Vector3,e=new THREE.Vector3,f=new THREE.Matrix4,g=false,h=1,i=0,j=0,l=0,n=0,k=0,m=window.innerWidth/2,p=window.innerHeight/2;this.update=function(a){if(this.mouseLook){var b=
  12281. a*this.lookSpeed;this.rotateHorizontally(b*n);this.rotateVertically(b*k)}b=a*this.movementSpeed;this.object.translateZ(-b*(i>0||this.autoForward&&!(i<0)?1:i));this.object.translateX(b*j);this.object.translateY(b*l);if(g)this.roll=this.roll+this.rollSpeed*a*h;if(this.forward.y>this.constrainVertical[1]){this.forward.y=this.constrainVertical[1];this.forward.normalize()}else if(this.forward.y<this.constrainVertical[0]){this.forward.y=this.constrainVertical[0];this.forward.normalize()}e.copy(this.forward);
  12282. d.set(0,1,0);c.cross(d,e).normalize();d.cross(e,c).normalize();this.object.matrix.elements[0]=c.x;this.object.matrix.elements[4]=d.x;this.object.matrix.elements[8]=e.x;this.object.matrix.elements[1]=c.y;this.object.matrix.elements[5]=d.y;this.object.matrix.elements[9]=e.y;this.object.matrix.elements[2]=c.z;this.object.matrix.elements[6]=d.z;this.object.matrix.elements[10]=e.z;f.identity();f.elements[0]=Math.cos(this.roll);f.elements[4]=-Math.sin(this.roll);f.elements[1]=Math.sin(this.roll);f.elements[5]=
  12283. Math.cos(this.roll);this.object.matrix.multiplySelf(f);this.object.matrixWorldNeedsUpdate=true;this.object.matrix.elements[12]=this.object.position.x;this.object.matrix.elements[13]=this.object.position.y;this.object.matrix.elements[14]=this.object.position.z};this.translateX=function(a){this.object.position.x=this.object.position.x+this.object.matrix.elements[0]*a;this.object.position.y=this.object.position.y+this.object.matrix.elements[1]*a;this.object.position.z=this.object.position.z+this.object.matrix.elements[2]*
  12284. a};this.translateY=function(a){this.object.position.x=this.object.position.x+this.object.matrix.elements[4]*a;this.object.position.y=this.object.position.y+this.object.matrix.elements[5]*a;this.object.position.z=this.object.position.z+this.object.matrix.elements[6]*a};this.translateZ=function(a){this.object.position.x=this.object.position.x-this.object.matrix.elements[8]*a;this.object.position.y=this.object.position.y-this.object.matrix.elements[9]*a;this.object.position.z=this.object.position.z-
  12285. this.object.matrix.elements[10]*a};this.rotateHorizontally=function(a){c.set(this.object.matrix.elements[0],this.object.matrix.elements[1],this.object.matrix.elements[2]);c.multiplyScalar(a);this.forward.subSelf(c);this.forward.normalize()};this.rotateVertically=function(a){d.set(this.object.matrix.elements[4],this.object.matrix.elements[5],this.object.matrix.elements[6]);d.multiplyScalar(a);this.forward.addSelf(d);this.forward.normalize()};this.domElement.addEventListener("contextmenu",function(a){a.preventDefault()},
  12286. false);this.domElement.addEventListener("mousemove",function(a){n=(a.clientX-m)/window.innerWidth;k=(a.clientY-p)/window.innerHeight},false);this.domElement.addEventListener("mousedown",function(a){a.preventDefault();a.stopPropagation();switch(a.button){case 0:i=1;break;case 2:i=-1}},false);this.domElement.addEventListener("mouseup",function(a){a.preventDefault();a.stopPropagation();switch(a.button){case 0:i=0;break;case 2:i=0}},false);this.domElement.addEventListener("keydown",function(a){switch(a.keyCode){case 38:case 87:i=
  12287. 1;break;case 37:case 65:j=-1;break;case 40:case 83:i=-1;break;case 39:case 68:j=1;break;case 81:g=true;h=1;break;case 69:g=true;h=-1;break;case 82:l=1;break;case 70:l=-1}},false);this.domElement.addEventListener("keyup",function(a){switch(a.keyCode){case 38:case 87:i=0;break;case 37:case 65:j=0;break;case 40:case 83:i=0;break;case 39:case 68:j=0;break;case 81:g=false;break;case 69:g=false;break;case 82:l=0;break;case 70:l=0}},false)};
  12288. THREE.TrackballControls=function(b,a){THREE.EventTarget.call(this);var c=this;this.object=b;this.domElement=a!==void 0?a:document;this.enabled=true;this.screen={width:window.innerWidth,height:window.innerHeight,offsetLeft:0,offsetTop:0};this.radius=(this.screen.width+this.screen.height)/4;this.rotateSpeed=1;this.zoomSpeed=1.2;this.panSpeed=0.3;this.staticMoving=this.noPan=this.noZoom=this.noRotate=false;this.dynamicDampingFactor=0.2;this.minDistance=0;this.maxDistance=Infinity;this.keys=[65,83,68];
  12289. this.target=new THREE.Vector3;var d=new THREE.Vector3,e=false,f=-1,g=new THREE.Vector3,h=new THREE.Vector3,i=new THREE.Vector3,j=new THREE.Vector2,l=new THREE.Vector2,n=new THREE.Vector2,k=new THREE.Vector2,m={type:"change"};this.handleEvent=function(a){if(typeof this[a.type]=="function")this[a.type](a)};this.getMouseOnScreen=function(a,b){return new THREE.Vector2((a-c.screen.offsetLeft)/c.radius*0.5,(b-c.screen.offsetTop)/c.radius*0.5)};this.getMouseProjectionOnBall=function(a,b){var d=new THREE.Vector3((a-
  12290. c.screen.width*0.5-c.screen.offsetLeft)/c.radius,(c.screen.height*0.5+c.screen.offsetTop-b)/c.radius,0),e=d.length();e>1?d.normalize():d.z=Math.sqrt(1-e*e);g.copy(c.object.position).subSelf(c.target);e=c.object.up.clone().setLength(d.y);e.addSelf(c.object.up.clone().crossSelf(g).setLength(d.x));e.addSelf(g.setLength(d.z));return e};this.rotateCamera=function(){var a=Math.acos(h.dot(i)/h.length()/i.length());if(a){var b=(new THREE.Vector3).cross(h,i).normalize(),d=new THREE.Quaternion,a=a*c.rotateSpeed;
  12291. d.setFromAxisAngle(b,-a);d.multiplyVector3(g);d.multiplyVector3(c.object.up);d.multiplyVector3(i);if(c.staticMoving)h=i;else{d.setFromAxisAngle(b,a*(c.dynamicDampingFactor-1));d.multiplyVector3(h)}}};this.zoomCamera=function(){var a=1+(l.y-j.y)*c.zoomSpeed;if(a!==1&&a>0){g.multiplyScalar(a);c.staticMoving?j=l:j.y=j.y+(l.y-j.y)*this.dynamicDampingFactor}};this.panCamera=function(){var a=k.clone().subSelf(n);if(a.lengthSq()){a.multiplyScalar(g.length()*c.panSpeed);var b=g.clone().crossSelf(c.object.up).setLength(a.x);
  12292. b.addSelf(c.object.up.clone().setLength(a.y));c.object.position.addSelf(b);c.target.addSelf(b);c.staticMoving?n=k:n.addSelf(a.sub(k,n).multiplyScalar(c.dynamicDampingFactor))}};this.checkDistances=function(){if(!c.noZoom||!c.noPan){c.object.position.lengthSq()>c.maxDistance*c.maxDistance&&c.object.position.setLength(c.maxDistance);g.lengthSq()<c.minDistance*c.minDistance&&c.object.position.add(c.target,g.setLength(c.minDistance))}};this.update=function(){g.copy(c.object.position).subSelf(c.target);
  12293. c.noRotate||c.rotateCamera();c.noZoom||c.zoomCamera();c.noPan||c.panCamera();c.object.position.add(c.target,g);c.checkDistances();c.object.lookAt(c.target);if(d.distanceTo(c.object.position)>0){c.dispatchEvent(m);d.copy(c.object.position)}};this.domElement.addEventListener("contextmenu",function(a){a.preventDefault()},false);this.domElement.addEventListener("mousemove",function(a){if(c.enabled){if(e){h=i=c.getMouseProjectionOnBall(a.clientX,a.clientY);j=l=c.getMouseOnScreen(a.clientX,a.clientY);n=
  12294. k=c.getMouseOnScreen(a.clientX,a.clientY);e=false}f!==-1&&(f===0&&!c.noRotate?i=c.getMouseProjectionOnBall(a.clientX,a.clientY):f===1&&!c.noZoom?l=c.getMouseOnScreen(a.clientX,a.clientY):f===2&&!c.noPan&&(k=c.getMouseOnScreen(a.clientX,a.clientY)))}},false);this.domElement.addEventListener("mousedown",function(a){if(c.enabled){a.preventDefault();a.stopPropagation();if(f===-1){f=a.button;f===0&&!c.noRotate?h=i=c.getMouseProjectionOnBall(a.clientX,a.clientY):f===1&&!c.noZoom?j=l=c.getMouseOnScreen(a.clientX,
  12295. a.clientY):this.noPan||(n=k=c.getMouseOnScreen(a.clientX,a.clientY))}}},false);this.domElement.addEventListener("mouseup",function(a){if(c.enabled){a.preventDefault();a.stopPropagation();f=-1}},false);window.addEventListener("keydown",function(a){if(c.enabled&&f===-1){a.keyCode===c.keys[0]&&!c.noRotate?f=0:a.keyCode===c.keys[1]&&!c.noZoom?f=1:a.keyCode===c.keys[2]&&!c.noPan&&(f=2);f!==-1&&(e=true)}},false);window.addEventListener("keyup",function(){c.enabled&&f!==-1&&(f=-1)},false)};
  12296. THREE.CubeGeometry=function(b,a,c,d,e,f,g,h){function i(a,b,c,g,h,i,k,l){var m,n=d||1,p=e||1,q=h/2,r=i/2,u=j.vertices.length;if(a==="x"&&b==="y"||a==="y"&&b==="x")m="z";else if(a==="x"&&b==="z"||a==="z"&&b==="x"){m="y";p=f||1}else if(a==="z"&&b==="y"||a==="y"&&b==="z"){m="x";n=f||1}var s=n+1,t=p+1,L=h/n,J=i/p,M=new THREE.Vector3;M[m]=k>0?1:-1;for(h=0;h<t;h++)for(i=0;i<s;i++){var y=new THREE.Vector3;y[a]=(i*L-q)*c;y[b]=(h*J-r)*g;y[m]=k;j.vertices.push(y)}for(h=0;h<p;h++)for(i=0;i<n;i++){a=new THREE.Face4(i+
  12297. s*h+u,i+s*(h+1)+u,i+1+s*(h+1)+u,i+1+s*h+u);a.normal.copy(M);a.vertexNormals.push(M.clone(),M.clone(),M.clone(),M.clone());a.materialIndex=l;j.faces.push(a);j.faceVertexUvs[0].push([new THREE.UV(i/n,h/p),new THREE.UV(i/n,(h+1)/p),new THREE.UV((i+1)/n,(h+1)/p),new THREE.UV((i+1)/n,h/p)])}}THREE.Geometry.call(this);var j=this,l=b/2,n=a/2,k=c/2,m,p,q,r,u,s;if(g!==void 0){if(g instanceof Array)this.materials=g;else{this.materials=[];for(m=0;m<6;m++)this.materials.push(g)}m=0;r=1;p=2;u=3;q=4;s=5}else this.materials=
  12298. [];this.sides={px:true,nx:true,py:true,ny:true,pz:true,nz:true};if(h!=void 0)for(var t in h)this.sides[t]!==void 0&&(this.sides[t]=h[t]);this.sides.px&&i("z","y",-1,-1,c,a,l,m);this.sides.nx&&i("z","y",1,-1,c,a,-l,r);this.sides.py&&i("x","z",1,1,b,c,n,p);this.sides.ny&&i("x","z",1,-1,b,c,-n,u);this.sides.pz&&i("x","y",1,-1,b,a,k,q);this.sides.nz&&i("x","y",-1,-1,b,a,-k,s);this.computeCentroids();this.mergeVertices()};THREE.CubeGeometry.prototype=new THREE.Geometry;
  12299. THREE.CubeGeometry.prototype.constructor=THREE.CubeGeometry;
  12300. THREE.CylinderGeometry=function(b,a,c,d,e,f){THREE.Geometry.call(this);var b=b!==void 0?b:20,a=a!==void 0?a:20,c=c!==void 0?c:100,g=c/2,d=d||8,e=e||1,h,i,j=[],l=[];for(i=0;i<=e;i++){var n=[],k=[],m=i/e,p=m*(a-b)+b;for(h=0;h<=d;h++){var q=h/d,r=new THREE.Vector3;r.x=p*Math.sin(q*Math.PI*2);r.y=-m*c+g;r.z=p*Math.cos(q*Math.PI*2);this.vertices.push(r);n.push(this.vertices.length-1);k.push(new THREE.UV(q,m))}j.push(n);l.push(k)}for(i=0;i<e;i++)for(h=0;h<d;h++){var c=j[i][h],n=j[i+1][h],k=j[i+1][h+1],
  12301. m=j[i][h+1],p=this.vertices[c].clone().setY(0).normalize(),q=this.vertices[n].clone().setY(0).normalize(),r=this.vertices[k].clone().setY(0).normalize(),u=this.vertices[m].clone().setY(0).normalize(),s=l[i][h].clone(),t=l[i+1][h].clone(),o=l[i+1][h+1].clone(),x=l[i][h+1].clone();this.faces.push(new THREE.Face4(c,n,k,m,[p,q,r,u]));this.faceVertexUvs[0].push([s,t,o,x])}if(!f&&b>0){this.vertices.push(new THREE.Vector3(0,g,0));for(h=0;h<d;h++){c=j[0][h];n=j[0][h+1];k=this.vertices.length-1;p=new THREE.Vector3(0,
  12302. 1,0);q=new THREE.Vector3(0,1,0);r=new THREE.Vector3(0,1,0);s=l[0][h].clone();t=l[0][h+1].clone();o=new THREE.UV(t.u,0);this.faces.push(new THREE.Face3(c,n,k,[p,q,r]));this.faceVertexUvs[0].push([s,t,o])}}if(!f&&a>0){this.vertices.push(new THREE.Vector3(0,-g,0));for(h=0;h<d;h++){c=j[i][h+1];n=j[i][h];k=this.vertices.length-1;p=new THREE.Vector3(0,-1,0);q=new THREE.Vector3(0,-1,0);r=new THREE.Vector3(0,-1,0);s=l[i][h+1].clone();t=l[i][h].clone();o=new THREE.UV(t.u,1);this.faces.push(new THREE.Face3(c,
  12303. n,k,[p,q,r]));this.faceVertexUvs[0].push([s,t,o])}}this.computeCentroids();this.computeFaceNormals()};THREE.CylinderGeometry.prototype=new THREE.Geometry;THREE.CylinderGeometry.prototype.constructor=THREE.CylinderGeometry;THREE.ExtrudeGeometry=function(b,a){if(typeof b!=="undefined"){THREE.Geometry.call(this);b=b instanceof Array?b:[b];this.shapebb=b[b.length-1].getBoundingBox();this.addShapeList(b,a);this.computeCentroids();this.computeFaceNormals()}};THREE.ExtrudeGeometry.prototype=new THREE.Geometry;
  12304. THREE.ExtrudeGeometry.prototype.constructor=THREE.ExtrudeGeometry;THREE.ExtrudeGeometry.prototype.addShapeList=function(b,a){for(var c=b.length,d=0;d<c;d++)this.addShape(b[d],a)};
  12305. THREE.ExtrudeGeometry.prototype.addShape=function(b,a){function c(a,b,c){b||console.log("die");return b.clone().multiplyScalar(c).addSelf(a)}function d(a,b,c){var d=THREE.ExtrudeGeometry.__v1,e=THREE.ExtrudeGeometry.__v2,f=THREE.ExtrudeGeometry.__v3,g=THREE.ExtrudeGeometry.__v4,h=THREE.ExtrudeGeometry.__v5,i=THREE.ExtrudeGeometry.__v6;d.set(a.x-b.x,a.y-b.y);e.set(a.x-c.x,a.y-c.y);d=d.normalize();e=e.normalize();f.set(-d.y,d.x);g.set(e.y,-e.x);h.copy(a).addSelf(f);i.copy(a).addSelf(g);if(h.equals(i))return g.clone();
  12306. h.copy(b).addSelf(f);i.copy(c).addSelf(g);f=d.dot(g);g=i.subSelf(h).dot(g);if(f===0){console.log("Either infinite or no solutions!");g===0?console.log("Its finite solutions."):console.log("Too bad, no solutions.")}g=g/f;if(g<0){b=Math.atan2(b.y-a.y,b.x-a.x);a=Math.atan2(c.y-a.y,c.x-a.x);b>a&&(a=a+Math.PI*2);c=(b+a)/2;a=-Math.cos(c);c=-Math.sin(c);a=new THREE.Vector2(a,c)}else a=d.multiplyScalar(g).addSelf(h).subSelf(a).clone();return a}function e(c,d){var e,f;for(y=c.length;--y>=0;){e=y;f=y-1;f<0&&
  12307. (f=c.length-1);for(var g=0,h=k+l*2,g=0;g<h;g++){var i=L*g,j=L*(g+1),m=d+e+i,i=d+f+i,n=d+f+j,j=d+e+j,p=c,q=g,o=h,m=m+C,i=i+C,n=n+C,j=j+C;F.faces.push(new THREE.Face4(m,i,n,j,null,null,s));m=Q.generateSideWallUV(F,b,p,a,m,i,n,j,q,o);F.faceVertexUvs[0].push(m)}}}function f(a,b,c){F.vertices.push(new THREE.Vector3(a,b,c))}function g(c,d,e,f){c=c+C;d=d+C;e=e+C;F.faces.push(new THREE.Face3(c,d,e,null,null,u));c=f?Q.generateBottomUV(F,b,a,c,d,e):Q.generateTopUV(F,b,a,c,d,e);F.faceVertexUvs[0].push(c)}var h=
  12308. a.amount!==void 0?a.amount:100,i=a.bevelThickness!==void 0?a.bevelThickness:6,j=a.bevelSize!==void 0?a.bevelSize:i-2,l=a.bevelSegments!==void 0?a.bevelSegments:3,n=a.bevelEnabled!==void 0?a.bevelEnabled:true,k=a.steps!==void 0?a.steps:1,m=a.bendPath,p=a.extrudePath,q,r=false,u=a.material,s=a.extrudeMaterial,t,o,x,z;if(p){q=p.getSpacedPoints(k);r=true;n=false;t=new THREE.TubeGeometry.FrenetFrames(p,k,false);o=new THREE.Vector3;x=new THREE.Vector3;z=new THREE.Vector3}if(!n)j=i=l=0;var A,v,w,F=this,
  12309. C=this.vertices.length;m&&b.addWrapPath(m);var p=b.extractPoints(),m=p.shape,B=p.holes;if(p=!THREE.Shape.Utils.isClockWise(m)){m=m.reverse();v=0;for(w=B.length;v<w;v++){A=B[v];THREE.Shape.Utils.isClockWise(A)&&(B[v]=A.reverse())}p=false}var I=THREE.Shape.Utils.triangulateShape(m,B),K=m;v=0;for(w=B.length;v<w;v++){A=B[v];m=m.concat(A)}var E,D,G,N,H,L=m.length,J,M=I.length,p=[],y=0;G=K.length;E=G-1;for(D=y+1;y<G;y++,E++,D++){E===G&&(E=0);D===G&&(D=0);p[y]=d(K[y],K[E],K[D])}var R=[],O,P=p.concat();v=
  12310. 0;for(w=B.length;v<w;v++){A=B[v];O=[];y=0;G=A.length;E=G-1;for(D=y+1;y<G;y++,E++,D++){E===G&&(E=0);D===G&&(D=0);O[y]=d(A[y],A[E],A[D])}R.push(O);P=P.concat(O)}for(E=0;E<l;E++){G=E/l;N=i*(1-G);D=j*Math.sin(G*Math.PI/2);y=0;for(G=K.length;y<G;y++){H=c(K[y],p[y],D);f(H.x,H.y,-N)}v=0;for(w=B.length;v<w;v++){A=B[v];O=R[v];y=0;for(G=A.length;y<G;y++){H=c(A[y],O[y],D);f(H.x,H.y,-N)}}}D=j;for(y=0;y<L;y++){H=n?c(m[y],P[y],D):m[y];if(r){x.copy(t.normals[0]).multiplyScalar(H.x);o.copy(t.binormals[0]).multiplyScalar(H.y);
  12311. z.copy(q[0]).addSelf(x).addSelf(o);f(z.x,z.y,z.z)}else f(H.x,H.y,0)}for(G=1;G<=k;G++)for(y=0;y<L;y++){H=n?c(m[y],P[y],D):m[y];if(r){x.copy(t.normals[G]).multiplyScalar(H.x);o.copy(t.binormals[G]).multiplyScalar(H.y);z.copy(q[G]).addSelf(x).addSelf(o);f(z.x,z.y,z.z)}else f(H.x,H.y,h/k*G)}for(E=l-1;E>=0;E--){G=E/l;N=i*(1-G);D=j*Math.sin(G*Math.PI/2);y=0;for(G=K.length;y<G;y++){H=c(K[y],p[y],D);f(H.x,H.y,h+N)}v=0;for(w=B.length;v<w;v++){A=B[v];O=R[v];y=0;for(G=A.length;y<G;y++){H=c(A[y],O[y],D);r?f(H.x,
  12312. H.y+q[k-1].y,q[k-1].x+N):f(H.x,H.y,h+N)}}}var Q=THREE.ExtrudeGeometry.WorldUVGenerator;(function(){if(n){var a;a=L*0;for(y=0;y<M;y++){J=I[y];g(J[2]+a,J[1]+a,J[0]+a,true)}a=k+l*2;a=L*a;for(y=0;y<M;y++){J=I[y];g(J[0]+a,J[1]+a,J[2]+a,false)}}else{for(y=0;y<M;y++){J=I[y];g(J[2],J[1],J[0],true)}for(y=0;y<M;y++){J=I[y];g(J[0]+L*k,J[1]+L*k,J[2]+L*k,false)}}})();(function(){var a=0;e(K,a);a=a+K.length;v=0;for(w=B.length;v<w;v++){A=B[v];e(A,a);a=a+A.length}})()};
  12313. THREE.ExtrudeGeometry.WorldUVGenerator={generateTopUV:function(b,a,c,d,e,f){a=b.vertices[e].x;e=b.vertices[e].y;c=b.vertices[f].x;f=b.vertices[f].y;return[new THREE.UV(b.vertices[d].x,1-b.vertices[d].y),new THREE.UV(a,1-e),new THREE.UV(c,1-f)]},generateBottomUV:function(b,a,c,d,e,f){return this.generateTopUV(b,a,c,d,e,f)},generateSideWallUV:function(b,a,c,d,e,f,g,h){var a=b.vertices[e].x,c=b.vertices[e].y,e=b.vertices[e].z,d=b.vertices[f].x,i=b.vertices[f].y,f=b.vertices[f].z,j=b.vertices[g].x,l=
  12314. b.vertices[g].y,g=b.vertices[g].z,n=b.vertices[h].x,k=b.vertices[h].y,b=b.vertices[h].z;return Math.abs(c-i)<0.01?[new THREE.UV(a,e),new THREE.UV(d,f),new THREE.UV(j,g),new THREE.UV(n,b)]:[new THREE.UV(c,e),new THREE.UV(i,f),new THREE.UV(l,g),new THREE.UV(k,b)]}};THREE.ExtrudeGeometry.__v1=new THREE.Vector2;THREE.ExtrudeGeometry.__v2=new THREE.Vector2;THREE.ExtrudeGeometry.__v3=new THREE.Vector2;THREE.ExtrudeGeometry.__v4=new THREE.Vector2;THREE.ExtrudeGeometry.__v5=new THREE.Vector2;
  12315. THREE.ExtrudeGeometry.__v6=new THREE.Vector2;
  12316. THREE.LatheGeometry=function(b,a,c){THREE.Geometry.call(this);for(var a=a||12,c=c||2*Math.PI,d=[],e=(new THREE.Matrix4).makeRotationZ(c/a),f=0;f<b.length;f++){d[f]=b[f].clone();this.vertices.push(d[f])}for(var g=a+1,c=0;c<g;c++)for(f=0;f<d.length;f++){d[f]=e.multiplyVector3(d[f].clone());this.vertices.push(d[f])}for(c=0;c<a;c++){d=0;for(e=b.length;d<e-1;d++){this.faces.push(new THREE.Face4(c*e+d,(c+1)%g*e+d,(c+1)%g*e+(d+1)%e,c*e+(d+1)%e));this.faceVertexUvs[0].push([new THREE.UV(1-c/a,d/e),new THREE.UV(1-
  12317. (c+1)/a,d/e),new THREE.UV(1-(c+1)/a,(d+1)/e),new THREE.UV(1-c/a,(d+1)/e)])}}this.computeCentroids();this.computeFaceNormals();this.computeVertexNormals()};THREE.LatheGeometry.prototype=new THREE.Geometry;THREE.LatheGeometry.prototype.constructor=THREE.LatheGeometry;
  12318. THREE.PlaneGeometry=function(b,a,c,d){THREE.Geometry.call(this);for(var e=b/2,f=a/2,c=c||1,d=d||1,g=c+1,h=d+1,i=b/c,j=a/d,l=new THREE.Vector3(0,1,0),b=0;b<h;b++)for(a=0;a<g;a++)this.vertices.push(new THREE.Vector3(a*i-e,0,b*j-f));for(b=0;b<d;b++)for(a=0;a<c;a++){e=new THREE.Face4(a+g*b,a+g*(b+1),a+1+g*(b+1),a+1+g*b);e.normal.copy(l);e.vertexNormals.push(l.clone(),l.clone(),l.clone(),l.clone());this.faces.push(e);this.faceVertexUvs[0].push([new THREE.UV(a/c,b/d),new THREE.UV(a/c,(b+1)/d),new THREE.UV((a+
  12319. 1)/c,(b+1)/d),new THREE.UV((a+1)/c,b/d)])}this.computeCentroids()};THREE.PlaneGeometry.prototype=new THREE.Geometry;THREE.PlaneGeometry.prototype.constructor=THREE.PlaneGeometry;
  12320. THREE.SphereGeometry=function(b,a,c,d,e,f,g){THREE.Geometry.call(this);var b=b||50,d=d!==void 0?d:0,e=e!==void 0?e:Math.PI*2,f=f!==void 0?f:0,g=g!==void 0?g:Math.PI,a=Math.max(3,Math.floor(a)||8),c=Math.max(2,Math.floor(c)||6),h,i,j=[],l=[];for(i=0;i<=c;i++){var n=[],k=[];for(h=0;h<=a;h++){var m=h/a,p=i/c,q=new THREE.Vector3;q.x=-b*Math.cos(d+m*e)*Math.sin(f+p*g);q.y=b*Math.cos(f+p*g);q.z=b*Math.sin(d+m*e)*Math.sin(f+p*g);this.vertices.push(q);n.push(this.vertices.length-1);k.push(new THREE.UV(m,
  12321. p))}j.push(n);l.push(k)}for(i=0;i<c;i++)for(h=0;h<a;h++){var d=j[i][h+1],e=j[i][h],f=j[i+1][h],g=j[i+1][h+1],n=this.vertices[d].clone().normalize(),k=this.vertices[e].clone().normalize(),m=this.vertices[f].clone().normalize(),p=this.vertices[g].clone().normalize(),q=l[i][h+1].clone(),r=l[i][h].clone(),u=l[i+1][h].clone(),s=l[i+1][h+1].clone();if(Math.abs(this.vertices[d].y)==b){this.faces.push(new THREE.Face3(d,f,g,[n,m,p]));this.faceVertexUvs[0].push([q,u,s])}else if(Math.abs(this.vertices[f].y)==
  12322. b){this.faces.push(new THREE.Face3(d,e,f,[n,k,m]));this.faceVertexUvs[0].push([q,r,u])}else{this.faces.push(new THREE.Face4(d,e,f,g,[n,k,m,p]));this.faceVertexUvs[0].push([q,r,u,s])}}this.computeCentroids();this.computeFaceNormals();this.boundingSphere={radius:b}};THREE.SphereGeometry.prototype=new THREE.Geometry;THREE.SphereGeometry.prototype.constructor=THREE.SphereGeometry;
  12323. THREE.TextGeometry=function(b,a){var c=(new THREE.TextPath(b,a)).toShapes();a.amount=a.height!==void 0?a.height:50;if(a.bevelThickness===void 0)a.bevelThickness=10;if(a.bevelSize===void 0)a.bevelSize=8;if(a.bevelEnabled===void 0)a.bevelEnabled=false;if(a.bend){var d=c[c.length-1].getBoundingBox().maxX;a.bendPath=new THREE.QuadraticBezierCurve(new THREE.Vector2(0,0),new THREE.Vector2(d/2,120),new THREE.Vector2(d,0))}THREE.ExtrudeGeometry.call(this,c,a)};THREE.TextGeometry.prototype=new THREE.ExtrudeGeometry;
  12324. THREE.TextGeometry.prototype.constructor=THREE.TextGeometry;
  12325. THREE.FontUtils={faces:{},face:"helvetiker",weight:"normal",style:"normal",size:150,divisions:10,getFace:function(){return this.faces[this.face][this.weight][this.style]},loadFace:function(b){var a=b.familyName.toLowerCase();this.faces[a]=this.faces[a]||{};this.faces[a][b.cssFontWeight]=this.faces[a][b.cssFontWeight]||{};this.faces[a][b.cssFontWeight][b.cssFontStyle]=b;return this.faces[a][b.cssFontWeight][b.cssFontStyle]=b},drawText:function(b){for(var a=this.getFace(),c=this.size/a.resolution,d=
  12326. 0,e=(""+b).split(""),f=e.length,g=[],b=0;b<f;b++){var h=new THREE.Path,h=this.extractGlyphPoints(e[b],a,c,d,h),d=d+h.offset;g.push(h.path)}return{paths:g,offset:d/2}},extractGlyphPoints:function(b,a,c,d,e){var f=[],g,h,i,j,l,n,k,m,p,q,r,u=a.glyphs[b]||a.glyphs["?"];if(u){if(u.o){a=u._cachedOutline||(u._cachedOutline=u.o.split(" "));j=a.length;for(b=0;b<j;){i=a[b++];switch(i){case "m":i=a[b++]*c+d;l=a[b++]*c;f.push(new THREE.Vector2(i,l));e.moveTo(i,l);break;case "l":i=a[b++]*c+d;l=a[b++]*c;f.push(new THREE.Vector2(i,
  12327. l));e.lineTo(i,l);break;case "q":i=a[b++]*c+d;l=a[b++]*c;m=a[b++]*c+d;p=a[b++]*c;e.quadraticCurveTo(m,p,i,l);if(g=f[f.length-1]){n=g.x;k=g.y;g=1;for(h=this.divisions;g<=h;g++){var s=g/h,t=THREE.Shape.Utils.b2(s,n,m,i),s=THREE.Shape.Utils.b2(s,k,p,l);f.push(new THREE.Vector2(t,s))}}break;case "b":i=a[b++]*c+d;l=a[b++]*c;m=a[b++]*c+d;p=a[b++]*-c;q=a[b++]*c+d;r=a[b++]*-c;e.bezierCurveTo(i,l,m,p,q,r);if(g=f[f.length-1]){n=g.x;k=g.y;g=1;for(h=this.divisions;g<=h;g++){s=g/h;t=THREE.Shape.Utils.b3(s,n,m,
  12328. q,i);s=THREE.Shape.Utils.b3(s,k,p,r,l);f.push(new THREE.Vector2(t,s))}}}}}return{offset:u.ha*c,points:f,path:e}}}};
  12329. (function(b){var a=function(a){for(var b=a.length,e=0,f=b-1,g=0;g<b;f=g++)e=e+(a[f].x*a[g].y-a[g].x*a[f].y);return e*0.5};b.Triangulate=function(b,d){var e=b.length;if(e<3)return null;var f=[],g=[],h=[],i,j,l;if(a(b)>0)for(j=0;j<e;j++)g[j]=j;else for(j=0;j<e;j++)g[j]=e-1-j;var n=2*e;for(j=e-1;e>2;){if(n--<=0){console.log("Warning, unable to triangulate polygon!");break}i=j;e<=i&&(i=0);j=i+1;e<=j&&(j=0);l=j+1;e<=l&&(l=0);var k;a:{k=b;var m=i,p=j,q=l,r=e,u=g,s=void 0,t=void 0,o=void 0,x=void 0,z=void 0,
  12330. A=void 0,v=void 0,w=void 0,F=void 0,t=k[u[m]].x,o=k[u[m]].y,x=k[u[p]].x,z=k[u[p]].y,A=k[u[q]].x,v=k[u[q]].y;if(1.0E-10>(x-t)*(v-o)-(z-o)*(A-t))k=false;else{for(s=0;s<r;s++)if(!(s==m||s==p||s==q)){var w=k[u[s]].x,F=k[u[s]].y,C=void 0,B=void 0,I=void 0,K=void 0,E=void 0,D=void 0,G=void 0,N=void 0,H=void 0,L=void 0,J=void 0,M=void 0,C=I=E=void 0,C=A-x,B=v-z,I=t-A,K=o-v,E=x-t,D=z-o,G=w-t,N=F-o,H=w-x,L=F-z,J=w-A,M=F-v,C=C*L-B*H,E=E*N-D*G,I=I*M-K*J;if(C>=0&&I>=0&&E>=0){k=false;break a}}k=true}}if(k){f.push([b[g[i]],
  12331. b[g[j]],b[g[l]]]);h.push([g[i],g[j],g[l]]);i=j;for(l=j+1;l<e;i++,l++)g[i]=g[l];e--;n=2*e}}return d?h:f};b.Triangulate.area=a;return b})(THREE.FontUtils);self._typeface_js={faces:THREE.FontUtils.faces,loadFace:THREE.FontUtils.loadFace};
  12332. THREE.TorusGeometry=function(b,a,c,d,e){THREE.Geometry.call(this);this.radius=b||100;this.tube=a||40;this.segmentsR=c||8;this.segmentsT=d||6;this.arc=e||Math.PI*2;e=new THREE.Vector3;b=[];a=[];for(c=0;c<=this.segmentsR;c++)for(d=0;d<=this.segmentsT;d++){var f=d/this.segmentsT*this.arc,g=c/this.segmentsR*Math.PI*2;e.x=this.radius*Math.cos(f);e.y=this.radius*Math.sin(f);var h=new THREE.Vector3;h.x=(this.radius+this.tube*Math.cos(g))*Math.cos(f);h.y=(this.radius+this.tube*Math.cos(g))*Math.sin(f);h.z=
  12333. this.tube*Math.sin(g);this.vertices.push(h);b.push(new THREE.UV(d/this.segmentsT,1-c/this.segmentsR));a.push(h.clone().subSelf(e).normalize())}for(c=1;c<=this.segmentsR;c++)for(d=1;d<=this.segmentsT;d++){var e=(this.segmentsT+1)*c+d-1,f=(this.segmentsT+1)*(c-1)+d-1,g=(this.segmentsT+1)*(c-1)+d,h=(this.segmentsT+1)*c+d,i=new THREE.Face4(e,f,g,h,[a[e],a[f],a[g],a[h]]);i.normal.addSelf(a[e]);i.normal.addSelf(a[f]);i.normal.addSelf(a[g]);i.normal.addSelf(a[h]);i.normal.normalize();this.faces.push(i);
  12334. this.faceVertexUvs[0].push([b[e].clone(),b[f].clone(),b[g].clone(),b[h].clone()])}this.computeCentroids()};THREE.TorusGeometry.prototype=new THREE.Geometry;THREE.TorusGeometry.prototype.constructor=THREE.TorusGeometry;
  12335. THREE.TorusKnotGeometry=function(b,a,c,d,e,f,g){function h(a,b,c,d,e,f){var g=Math.cos(a);Math.cos(b);b=Math.sin(a);a=c/d*a;c=Math.cos(a);g=e*(2+c)*0.5*g;b=e*(2+c)*b*0.5;e=f*e*Math.sin(a)*0.5;return new THREE.Vector3(g,b,e)}THREE.Geometry.call(this);this.radius=b||200;this.tube=a||40;this.segmentsR=c||64;this.segmentsT=d||8;this.p=e||2;this.q=f||3;this.heightScale=g||1;this.grid=Array(this.segmentsR);c=new THREE.Vector3;d=new THREE.Vector3;e=new THREE.Vector3;for(b=0;b<this.segmentsR;++b){this.grid[b]=
  12336. Array(this.segmentsT);for(a=0;a<this.segmentsT;++a){var i=b/this.segmentsR*2*this.p*Math.PI,g=a/this.segmentsT*2*Math.PI,f=h(i,g,this.q,this.p,this.radius,this.heightScale),i=h(i+0.01,g,this.q,this.p,this.radius,this.heightScale);c.sub(i,f);d.add(i,f);e.cross(c,d);d.cross(e,c);e.normalize();d.normalize();i=-this.tube*Math.cos(g);g=this.tube*Math.sin(g);f.x=f.x+(i*d.x+g*e.x);f.y=f.y+(i*d.y+g*e.y);f.z=f.z+(i*d.z+g*e.z);this.grid[b][a]=this.vertices.push(new THREE.Vector3(f.x,f.y,f.z))-1}}for(b=0;b<
  12337. this.segmentsR;++b)for(a=0;a<this.segmentsT;++a){var e=(b+1)%this.segmentsR,f=(a+1)%this.segmentsT,c=this.grid[b][a],d=this.grid[e][a],e=this.grid[e][f],f=this.grid[b][f],g=new THREE.UV(b/this.segmentsR,a/this.segmentsT),i=new THREE.UV((b+1)/this.segmentsR,a/this.segmentsT),j=new THREE.UV((b+1)/this.segmentsR,(a+1)/this.segmentsT),l=new THREE.UV(b/this.segmentsR,(a+1)/this.segmentsT);this.faces.push(new THREE.Face4(c,d,e,f));this.faceVertexUvs[0].push([g,i,j,l])}this.computeCentroids();this.computeFaceNormals();
  12338. this.computeVertexNormals()};THREE.TorusKnotGeometry.prototype=new THREE.Geometry;THREE.TorusKnotGeometry.prototype.constructor=THREE.TorusKnotGeometry;
  12339. THREE.TubeGeometry=function(b,a,c,d,e,f){THREE.Geometry.call(this);this.path=b;this.segments=a||64;this.radius=c||1;this.segmentsRadius=d||8;this.closed=e||false;if(f)this.debug=new THREE.Object3D;this.grid=[];var g,h,f=this.segments+1,i,j,l,n=new THREE.Vector3,k,m,p,a=new THREE.TubeGeometry.FrenetFrames(b,a,e);k=a.tangents;m=a.normals;p=a.binormals;this.tangents=k;this.normals=m;this.binormals=p;for(a=0;a<f;a++){this.grid[a]=[];d=a/(f-1);l=b.getPointAt(d);d=k[a];g=m[a];h=p[a];if(this.debug){this.debug.add(new THREE.ArrowHelper(d,
  12340. l,c,255));this.debug.add(new THREE.ArrowHelper(g,l,c,16711680));this.debug.add(new THREE.ArrowHelper(h,l,c,65280))}for(d=0;d<this.segmentsRadius;d++){i=d/this.segmentsRadius*2*Math.PI;j=-this.radius*Math.cos(i);i=this.radius*Math.sin(i);n.copy(l);n.x=n.x+(j*g.x+i*h.x);n.y=n.y+(j*g.y+i*h.y);n.z=n.z+(j*g.z+i*h.z);this.grid[a][d]=this.vertices.push(new THREE.Vector3(n.x,n.y,n.z))-1}}for(a=0;a<this.segments;a++)for(d=0;d<this.segmentsRadius;d++){f=e?(a+1)%this.segments:a+1;n=(d+1)%this.segmentsRadius;
  12341. b=this.grid[a][d];c=this.grid[f][d];f=this.grid[f][n];n=this.grid[a][n];k=new THREE.UV(a/this.segments,d/this.segmentsRadius);m=new THREE.UV((a+1)/this.segments,d/this.segmentsRadius);p=new THREE.UV((a+1)/this.segments,(d+1)/this.segmentsRadius);g=new THREE.UV(a/this.segments,(d+1)/this.segmentsRadius);this.faces.push(new THREE.Face4(b,c,f,n));this.faceVertexUvs[0].push([k,m,p,g])}this.computeCentroids();this.computeFaceNormals();this.computeVertexNormals()};THREE.TubeGeometry.prototype=new THREE.Geometry;
  12342. THREE.TubeGeometry.prototype.constructor=THREE.TubeGeometry;
  12343. THREE.TubeGeometry.FrenetFrames=function(b,a,c){new THREE.Vector3;var d=new THREE.Vector3;new THREE.Vector3;var e=[],f=[],g=[],h=new THREE.Vector3,i=new THREE.Matrix4,a=a+1,j,l,n;this.tangents=e;this.normals=f;this.binormals=g;for(j=0;j<a;j++){l=j/(a-1);e[j]=b.getTangentAt(l);e[j].normalize()}f[0]=new THREE.Vector3;g[0]=new THREE.Vector3;b=Number.MAX_VALUE;j=Math.abs(e[0].x);l=Math.abs(e[0].y);n=Math.abs(e[0].z);if(j<=b){b=j;d.set(1,0,0)}if(l<=b){b=l;d.set(0,1,0)}n<=b&&d.set(0,0,1);h.cross(e[0],d).normalize();
  12344. f[0].cross(e[0],h);g[0].cross(e[0],f[0]);for(j=1;j<a;j++){f[j]=f[j-1].clone();g[j]=g[j-1].clone();h.cross(e[j-1],e[j]);if(h.length()>1.0E-4){h.normalize();d=Math.acos(e[j-1].dot(e[j]));i.makeRotationAxis(h,d).multiplyVector3(f[j])}g[j].cross(e[j],f[j])}if(c){d=Math.acos(f[0].dot(f[a-1]));d=d/(a-1);e[0].dot(h.cross(f[0],f[a-1]))>0&&(d=-d);for(j=1;j<a;j++){i.makeRotationAxis(e[j],d*j).multiplyVector3(f[j]);g[j].cross(e[j],f[j])}}};
  12345. THREE.PolyhedronGeometry=function(b,a,c,d){function e(a){var b=a.normalize().clone();b.index=i.vertices.push(b)-1;var c=Math.atan2(a.z,-a.x)/2/Math.PI+0.5,a=Math.atan2(-a.y,Math.sqrt(a.x*a.x+a.z*a.z))/Math.PI+0.5;b.uv=new THREE.UV(c,a);return b}function f(a,b,c,d){if(d<1){d=new THREE.Face3(a.index,b.index,c.index,[a.clone(),b.clone(),c.clone()]);d.centroid.addSelf(a).addSelf(b).addSelf(c).divideScalar(3);d.normal=d.centroid.clone().normalize();i.faces.push(d);d=Math.atan2(d.centroid.z,-d.centroid.x);
  12346. i.faceVertexUvs[0].push([h(a.uv,a,d),h(b.uv,b,d),h(c.uv,c,d)])}else{d=d-1;f(a,g(a,b),g(a,c),d);f(g(a,b),b,g(b,c),d);f(g(a,c),g(b,c),c,d);f(g(a,b),g(b,c),g(a,c),d)}}function g(a,b){n[a.index]||(n[a.index]=[]);n[b.index]||(n[b.index]=[]);var c=n[a.index][b.index];c===void 0&&(n[a.index][b.index]=n[b.index][a.index]=c=e((new THREE.Vector3).add(a,b).divideScalar(2)));return c}function h(a,b,c){c<0&&a.u===1&&(a=new THREE.UV(a.u-1,a.v));b.x===0&&b.z===0&&(a=new THREE.UV(c/2/Math.PI+0.5,a.v));return a}THREE.Geometry.call(this);
  12347. for(var c=c||1,d=d||0,i=this,j=0,l=b.length;j<l;j++)e(new THREE.Vector3(b[j][0],b[j][1],b[j][2]));for(var n=[],b=this.vertices,j=0,l=a.length;j<l;j++)f(b[a[j][0]],b[a[j][1]],b[a[j][2]],d);this.mergeVertices();j=0;for(l=this.vertices.length;j<l;j++)this.vertices[j].multiplyScalar(c);this.computeCentroids();this.boundingSphere={radius:c}};THREE.PolyhedronGeometry.prototype=new THREE.Geometry;THREE.PolyhedronGeometry.prototype.constructor=THREE.PolyhedronGeometry;
  12348. THREE.IcosahedronGeometry=function(b,a){var c=(1+Math.sqrt(5))/2;THREE.PolyhedronGeometry.call(this,[[-1,c,0],[1,c,0],[-1,-c,0],[1,-c,0],[0,-1,c],[0,1,c],[0,-1,-c],[0,1,-c],[c,0,-1],[c,0,1],[-c,0,-1],[-c,0,1]],[[0,11,5],[0,5,1],[0,1,7],[0,7,10],[0,10,11],[1,5,9],[5,11,4],[11,10,2],[10,7,6],[7,1,8],[3,9,4],[3,4,2],[3,2,6],[3,6,8],[3,8,9],[4,9,5],[2,4,11],[6,2,10],[8,6,7],[9,8,1]],b,a)};THREE.IcosahedronGeometry.prototype=new THREE.Geometry;THREE.IcosahedronGeometry.prototype.constructor=THREE.IcosahedronGeometry;
  12349. THREE.OctahedronGeometry=function(b,a){THREE.PolyhedronGeometry.call(this,[[1,0,0],[-1,0,0],[0,1,0],[0,-1,0],[0,0,1],[0,0,-1]],[[0,2,4],[0,4,3],[0,3,5],[0,5,2],[1,2,5],[1,5,3],[1,3,4],[1,4,2]],b,a)};THREE.OctahedronGeometry.prototype=new THREE.Geometry;THREE.OctahedronGeometry.prototype.constructor=THREE.OctahedronGeometry;THREE.TetrahedronGeometry=function(b,a){THREE.PolyhedronGeometry.call(this,[[1,1,1],[-1,-1,1],[-1,1,-1],[1,-1,-1]],[[2,1,0],[0,3,2],[1,3,0],[2,3,1]],b,a)};
  12350. THREE.TetrahedronGeometry.prototype=new THREE.Geometry;THREE.TetrahedronGeometry.prototype.constructor=THREE.TetrahedronGeometry;
  12351. THREE.ParametricGeometry=function(b,a,c){THREE.Geometry.call(this);var d=this.vertices,e=this.faces,f=this.faceVertexUvs[0],g,h,i,j,l=a+1;for(g=0;g<=a;g++){j=g/a;for(h=0;h<=b;h++){i=h/b;i=c(i,j);d.push(i)}}var n,k,m,p;for(g=0;g<a;g++)for(h=0;h<b;h++){c=g*l+h;d=g*l+h+1;j=(g+1)*l+h;i=(g+1)*l+h+1;n=new THREE.UV(g/b,h/a);k=new THREE.UV(g/b,(h+1)/a);m=new THREE.UV((g+1)/b,h/a);p=new THREE.UV((g+1)/b,(h+1)/a);e.push(new THREE.Face3(c,d,j));e.push(new THREE.Face3(d,i,j));f.push([n,k,m]);f.push([k,p,m])}console.log(this);
  12352. b=this.mergeVertices();console.log("removed ",b," vertices by merging");this.computeCentroids();this.computeFaceNormals();this.computeVertexNormals()};THREE.ParametricGeometry.prototype=new THREE.Geometry;THREE.ParametricGeometry.prototype.constructor=THREE.ParametricGeometry;
  12353. THREE.AxisHelper=function(){THREE.Object3D.call(this);var b=new THREE.Geometry;b.vertices.push(new THREE.Vector3);b.vertices.push(new THREE.Vector3(0,100,0));var a=new THREE.CylinderGeometry(0,5,25,5,1),c;c=new THREE.Line(b,new THREE.LineBasicMaterial({color:16711680}));c.rotation.z=-Math.PI/2;this.add(c);c=new THREE.Mesh(a,new THREE.MeshBasicMaterial({color:16711680}));c.position.x=100;c.rotation.z=-Math.PI/2;this.add(c);c=new THREE.Line(b,new THREE.LineBasicMaterial({color:65280}));this.add(c);
  12354. c=new THREE.Mesh(a,new THREE.MeshBasicMaterial({color:65280}));c.position.y=100;this.add(c);c=new THREE.Line(b,new THREE.LineBasicMaterial({color:255}));c.rotation.x=Math.PI/2;this.add(c);c=new THREE.Mesh(a,new THREE.MeshBasicMaterial({color:255}));c.position.z=100;c.rotation.x=Math.PI/2;this.add(c)};THREE.AxisHelper.prototype=new THREE.Object3D;THREE.AxisHelper.prototype.constructor=THREE.AxisHelper;
  12355. THREE.ArrowHelper=function(b,a,c,d){THREE.Object3D.call(this);d===void 0&&(d=16776960);c===void 0&&(c=20);var e=new THREE.Geometry;e.vertices.push(new THREE.Vector3(0,0,0));e.vertices.push(new THREE.Vector3(0,1,0));this.line=new THREE.Line(e,new THREE.LineBasicMaterial({color:d}));this.add(this.line);e=new THREE.CylinderGeometry(0,0.05,0.25,5,1);this.cone=new THREE.Mesh(e,new THREE.MeshBasicMaterial({color:d}));this.cone.position.set(0,1,0);this.add(this.cone);if(a instanceof THREE.Vector3)this.position=
  12356. a;this.setDirection(b);this.setLength(c)};THREE.ArrowHelper.prototype=new THREE.Object3D;THREE.ArrowHelper.prototype.constructor=THREE.ArrowHelper;THREE.ArrowHelper.prototype.setDirection=function(b){var a=(new THREE.Vector3(0,1,0)).crossSelf(b),b=Math.acos((new THREE.Vector3(0,1,0)).dot(b.clone().normalize()));this.matrix=(new THREE.Matrix4).makeRotationAxis(a.normalize(),b);this.rotation.getRotationFromMatrix(this.matrix,this.scale)};
  12357. THREE.ArrowHelper.prototype.setLength=function(b){this.scale.set(b,b,b)};THREE.ArrowHelper.prototype.setColor=function(b){this.line.material.color.setHex(b);this.cone.material.color.setHex(b)};
  12358. THREE.CameraHelper=function(b){function a(a,b,d){c(a,d);c(b,d)}function c(a,b){d.lineGeometry.vertices.push(new THREE.Vector3);d.lineGeometry.colors.push(new THREE.Color(b));d.pointMap[a]===void 0&&(d.pointMap[a]=[]);d.pointMap[a].push(d.lineGeometry.vertices.length-1)}THREE.Object3D.call(this);var d=this;this.lineGeometry=new THREE.Geometry;this.lineMaterial=new THREE.LineBasicMaterial({color:16777215,vertexColors:THREE.FaceColors});this.pointMap={};a("n1","n2",16755200);a("n2","n4",16755200);a("n4",
  12359. "n3",16755200);a("n3","n1",16755200);a("f1","f2",16755200);a("f2","f4",16755200);a("f4","f3",16755200);a("f3","f1",16755200);a("n1","f1",16755200);a("n2","f2",16755200);a("n3","f3",16755200);a("n4","f4",16755200);a("p","n1",16711680);a("p","n2",16711680);a("p","n3",16711680);a("p","n4",16711680);a("u1","u2",43775);a("u2","u3",43775);a("u3","u1",43775);a("c","t",16777215);a("p","c",3355443);a("cn1","cn2",3355443);a("cn3","cn4",3355443);a("cf1","cf2",3355443);a("cf3","cf4",3355443);this.camera=b;this.update(b);
  12360. this.lines=new THREE.Line(this.lineGeometry,this.lineMaterial,THREE.LinePieces);this.add(this.lines)};THREE.CameraHelper.prototype=new THREE.Object3D;THREE.CameraHelper.prototype.constructor=THREE.CameraHelper;
  12361. THREE.CameraHelper.prototype.update=function(){function b(b,d,e,f){THREE.CameraHelper.__v.set(d,e,f);THREE.CameraHelper.__projector.unprojectVector(THREE.CameraHelper.__v,THREE.CameraHelper.__c);b=a.pointMap[b];if(b!==void 0){d=0;for(e=b.length;d<e;d++)a.lineGeometry.vertices[b[d]].copy(THREE.CameraHelper.__v)}}var a=this;THREE.CameraHelper.__c.projectionMatrix.copy(this.camera.projectionMatrix);b("c",0,0,-1);b("t",0,0,1);b("n1",-1,-1,-1);b("n2",1,-1,-1);b("n3",-1,1,-1);b("n4",1,1,-1);b("f1",-1,-1,
  12362. 1);b("f2",1,-1,1);b("f3",-1,1,1);b("f4",1,1,1);b("u1",0.7,1.1,-1);b("u2",-0.7,1.1,-1);b("u3",0,2,-1);b("cf1",-1,0,1);b("cf2",1,0,1);b("cf3",0,-1,1);b("cf4",0,1,1);b("cn1",-1,0,-1);b("cn2",1,0,-1);b("cn3",0,-1,-1);b("cn4",0,1,-1);this.lineGeometry.verticesNeedUpdate=true};THREE.CameraHelper.__projector=new THREE.Projector;THREE.CameraHelper.__v=new THREE.Vector3;THREE.CameraHelper.__c=new THREE.Camera;
  12363. THREE.SubdivisionModifier=function(b){this.subdivisions=b===void 0?1:b;this.useOldVertexColors=false;this.supportUVs=true;this.debug=false};THREE.SubdivisionModifier.prototype.constructor=THREE.SubdivisionModifier;THREE.SubdivisionModifier.prototype.modify=function(b){for(var a=this.subdivisions;a-- >0;)this.smooth(b)};
  12364. THREE.SubdivisionModifier.prototype.smooth=function(b){function a(){k.debug&&console.log.apply(console,arguments)}function c(){console&&console.log.apply(console,arguments)}function d(b,c,d,e,g,h,i){var j=new THREE.Face4(b,c,d,e,null,g.color,g.material);if(k.useOldVertexColors){j.vertexColors=[];for(var m,p,o,q=0;q<4;q++){o=h[q];m=new THREE.Color;m.setRGB(0,0,0);for(var r=0;r<o.length;r++){p=g.vertexColors[o[r]-1];m.r=m.r+p.r;m.g=m.g+p.g;m.b=m.b+p.b}m.r=m.r/o.length;m.g=m.g/o.length;m.b=m.b/o.length;
  12365. j.vertexColors[q]=m}}l.push(j);if(k.supportUVs){g=[f(b,""),f(c,i),f(d,i),f(e,i)];g[0]?g[1]?g[2]?g[3]?n.push(g):a("d :( ",e+":"+i):a("c :( ",d+":"+i):a("b :( ",c+":"+i):a("a :( ",b+":"+i)}}function e(a,b){return Math.min(a,b)+"_"+Math.max(a,b)}function f(b,d){var e=b+":"+d,f=s[e];if(!f){b>=t&&b<t+p.length?a("face pt"):a("edge pt");c("warning, UV not found for",e);return null}return f}function g(a,b,d){var e=a+":"+b;e in s?c("dup vertexNo",a,"oldFaceNo",b,"value",d,"key",e,s[e]):s[e]=d}function h(a,
  12366. b){I[a]===void 0&&(I[a]=[]);I[a].push(b)}function i(a,b,c){K[a]===void 0&&(K[a]={});K[a][b]=c}var j=[],l=[],n=[],k=this,m=b.vertices,p=b.faces,j=m.concat(),q=[],r={},u={},s={},t=m.length,o,x,z,A,v,w=b.faceVertexUvs[0],F;a("originalFaces, uvs, originalVerticesLength",p.length,w.length,t);if(k.supportUVs){o=0;for(x=w.length;o<x;o++){z=0;for(A=w[o].length;z<A;z++){F=p[o]["abcd".charAt(z)];g(F,o,w[o][z])}}}if(w.length==0)k.supportUVs=false;o=0;for(v in s)o++;if(!o){k.supportUVs=false;a("no uvs")}a("-- Original Faces + Vertices UVs completed",
  12367. s,"vs",w.length);o=0;for(x=p.length;o<x;o++){v=p[o];q.push(v.centroid);j.push(v.centroid);if(k.supportUVs){w=new THREE.UV;if(v instanceof THREE.Face3){w.u=f(v.a,o).u+f(v.b,o).u+f(v.c,o).u;w.v=f(v.a,o).v+f(v.b,o).v+f(v.c,o).v;w.u=w.u/3;w.v=w.v/3}else if(v instanceof THREE.Face4){w.u=f(v.a,o).u+f(v.b,o).u+f(v.c,o).u+f(v.d,o).u;w.v=f(v.a,o).v+f(v.b,o).v+f(v.c,o).v+f(v.d,o).v;w.u=w.u/4;w.v=w.v/4}g(t+o,"",w)}}a("-- added UVs for new Faces",s);x=function(a){function b(a,c){h[a]===void 0&&(h[a]=[]);h[a].push(c)}
  12368. var c,d,f,g,h={};c=0;for(d=a.faces.length;c<d;c++){f=a.faces[c];if(f instanceof THREE.Face3){g=e(f.a,f.b);b(g,c);g=e(f.b,f.c);b(g,c);g=e(f.c,f.a);b(g,c)}else if(f instanceof THREE.Face4){g=e(f.a,f.b);b(g,c);g=e(f.b,f.c);b(g,c);g=e(f.c,f.d);b(g,c);g=e(f.d,f.a);b(g,c)}}return h}(b);F=0;var C,B,I={},K={};for(o in x){w=x[o];C=o.split("_");B=C[0];C=C[1];h(B,[B,C]);h(C,[B,C]);z=0;for(A=w.length;z<A;z++){v=w[z];i(B,v,o);i(C,v,o)}w.length<2&&(u[o]=true)}a("vertexEdgeMap",I,"vertexFaceMap",K);for(o in x){w=
  12369. x[o];v=w[0];A=w[1];C=o.split("_");B=C[0];C=C[1];w=new THREE.Vector3;if(u[o]){w.addSelf(m[B]);w.addSelf(m[C]);w.multiplyScalar(0.5)}else{w.addSelf(q[v]);w.addSelf(q[A]);w.addSelf(m[B]);w.addSelf(m[C]);w.multiplyScalar(0.25)}r[o]=t+p.length+F;j.push(w);F++;if(k.supportUVs){w=new THREE.UV;w.u=f(B,v).u+f(C,v).u;w.v=f(B,v).v+f(C,v).v;w.u=w.u/2;w.v=w.v/2;g(r[o],v,w);if(!u[o]){w=new THREE.UV;w.u=f(B,A).u+f(C,A).u;w.v=f(B,A).v+f(C,A).v;w.u=w.u/2;w.v=w.v/2;g(r[o],A,w)}}}a("-- Step 2 done");var E,D;A=["123",
  12370. "12","2","23"];C=["123","23","3","31"];var G=["123","31","1","12"],N=["1234","12","2","23"],H=["1234","23","3","34"],L=["1234","34","4","41"],J=["1234","41","1","12"];o=0;for(x=q.length;o<x;o++){v=p[o];w=t+o;if(v instanceof THREE.Face3){F=e(v.a,v.b);B=e(v.b,v.c);E=e(v.c,v.a);d(w,r[F],v.b,r[B],v,A,o);d(w,r[B],v.c,r[E],v,C,o);d(w,r[E],v.a,r[F],v,G,o)}else if(v instanceof THREE.Face4){F=e(v.a,v.b);B=e(v.b,v.c);E=e(v.c,v.d);D=e(v.d,v.a);d(w,r[F],v.b,r[B],v,N,o);d(w,r[B],v.c,r[E],v,H,o);d(w,r[E],v.d,r[D],
  12371. v,L,o);d(w,r[D],v.a,r[F],v,J,o)}else a("face should be a face!",v)}r=new THREE.Vector3;v=new THREE.Vector3;o=0;for(x=m.length;o<x;o++)if(I[o]!==void 0){r.set(0,0,0);v.set(0,0,0);B=new THREE.Vector3(0,0,0);w=0;for(z in K[o]){r.addSelf(q[z]);w++}A=0;F=I[o].length;for(z=0;z<F;z++)u[e(I[o][z][0],I[o][z][1])]&&A++;if(A!=2){r.divideScalar(w);for(z=0;z<F;z++){w=I[o][z];w=m[w[0]].clone().addSelf(m[w[1]]).divideScalar(2);v.addSelf(w)}v.divideScalar(F);B.addSelf(m[o]);B.multiplyScalar(F-3);B.addSelf(r);B.addSelf(v.multiplyScalar(2));
  12372. B.divideScalar(F);j[o]=B}}b.vertices=j;b.faces=l;b.faceVertexUvs[0]=n;delete b.__tmpVertices;b.computeCentroids();b.computeFaceNormals();b.computeVertexNormals()};THREE.ImmediateRenderObject=function(){THREE.Object3D.call(this);this.render=function(){}};THREE.ImmediateRenderObject.prototype=new THREE.Object3D;THREE.ImmediateRenderObject.prototype.constructor=THREE.ImmediateRenderObject;
  12373. THREE.LensFlare=function(b,a,c,d,e){THREE.Object3D.call(this);this.lensFlares=[];this.positionScreen=new THREE.Vector3;this.customUpdateCallback=void 0;b!==void 0&&this.add(b,a,c,d,e)};THREE.LensFlare.prototype=new THREE.Object3D;THREE.LensFlare.prototype.constructor=THREE.LensFlare;THREE.LensFlare.prototype.supr=THREE.Object3D.prototype;
  12374. THREE.LensFlare.prototype.add=function(b,a,c,d,e,f){a===void 0&&(a=-1);c===void 0&&(c=0);f===void 0&&(f=1);e===void 0&&(e=new THREE.Color(16777215));if(d===void 0)d=THREE.NormalBlending;c=Math.min(c,Math.max(0,c));this.lensFlares.push({texture:b,size:a,distance:c,x:0,y:0,z:0,scale:1,rotation:1,opacity:f,color:e,blending:d})};
  12375. THREE.LensFlare.prototype.updateLensFlares=function(){var b,a=this.lensFlares.length,c,d=-this.positionScreen.x*2,e=-this.positionScreen.y*2;for(b=0;b<a;b++){c=this.lensFlares[b];c.x=this.positionScreen.x+d*c.distance;c.y=this.positionScreen.y+e*c.distance;c.wantedRotation=c.x*Math.PI*0.25;c.rotation=c.rotation+(c.wantedRotation-c.rotation)*0.25}};
  12376. THREE.MorphBlendMesh=function(b,a){THREE.Mesh.call(this,b,a);this.animationsMap={};this.animationsList=[];var c=this.geometry.morphTargets.length;this.createAnimation("__default",0,c-1,c/1);this.setAnimationWeight("__default",1)};THREE.MorphBlendMesh.prototype=new THREE.Mesh;THREE.MorphBlendMesh.prototype.constructor=THREE.MorphBlendMesh;
  12377. THREE.MorphBlendMesh.prototype.createAnimation=function(b,a,c,d){a={startFrame:a,endFrame:c,length:c-a+1,fps:d,duration:(c-a)/d,lastFrame:0,currentFrame:0,active:false,time:0,direction:1,weight:1,directionBackwards:false,mirroredLoop:false};this.animationsMap[b]=a;this.animationsList.push(a)};
  12378. THREE.MorphBlendMesh.prototype.autoCreateAnimations=function(b){for(var a=/([a-z]+)(\d+)/,c,d={},e=this.geometry,f=0,g=e.morphTargets.length;f<g;f++){var h=e.morphTargets[f].name.match(a);if(h&&h.length>1){var i=h[1];d[i]||(d[i]={start:Infinity,end:-Infinity});h=d[i];if(f<h.start)h.start=f;if(f>h.end)h.end=f;c||(c=i)}}for(i in d){h=d[i];this.createAnimation(i,h.start,h.end,b)}this.firstAnimation=c};
  12379. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward=function(b){if(b=this.animationsMap[b]){b.direction=1;b.directionBackwards=false}};THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward=function(b){if(b=this.animationsMap[b]){b.direction=-1;b.directionBackwards=true}};THREE.MorphBlendMesh.prototype.setAnimationFPS=function(b,a){var c=this.animationsMap[b];if(c){c.fps=a;c.duration=(c.end-c.start)/c.fps}};
  12380. THREE.MorphBlendMesh.prototype.setAnimationDuration=function(b,a){var c=this.animationsMap[b];if(c){c.duration=a;c.fps=(c.end-c.start)/c.duration}};THREE.MorphBlendMesh.prototype.setAnimationWeight=function(b,a){var c=this.animationsMap[b];if(c)c.weight=a};THREE.MorphBlendMesh.prototype.setAnimationTime=function(b,a){var c=this.animationsMap[b];if(c)c.time=a};THREE.MorphBlendMesh.prototype.getAnimationTime=function(b){var a=0;if(b=this.animationsMap[b])a=b.time;return a};
  12381. THREE.MorphBlendMesh.prototype.getAnimationDuration=function(b){var a=-1;if(b=this.animationsMap[b])a=b.duration;return a};THREE.MorphBlendMesh.prototype.playAnimation=function(b){var a=this.animationsMap[b];if(a){a.time=0;a.active=true}else console.warn("animation["+b+"] undefined")};THREE.MorphBlendMesh.prototype.stopAnimation=function(b){if(b=this.animationsMap[b])b.active=false};
  12382. THREE.MorphBlendMesh.prototype.update=function(b){for(var a=0,c=this.animationsList.length;a<c;a++){var d=this.animationsList[a];if(d.active){var e=d.duration/d.length;d.time=d.time+d.direction*b;if(d.mirroredLoop){if(d.time>d.duration||d.time<0){d.direction=d.direction*-1;if(d.time>d.duration){d.time=d.duration;d.directionBackwards=true}if(d.time<0){d.time=0;d.directionBackwards=false}}}else{d.time=d.time%d.duration;if(d.time<0)d.time=d.time+d.duration}var f=d.startFrame+THREE.Math.clamp(Math.floor(d.time/
  12383. e),0,d.length-1),g=d.weight;if(f!==d.currentFrame){this.morphTargetInfluences[d.lastFrame]=0;this.morphTargetInfluences[d.currentFrame]=1*g;this.morphTargetInfluences[f]=0;d.lastFrame=d.currentFrame;d.currentFrame=f}e=d.time%e/e;d.directionBackwards&&(e=1-e);this.morphTargetInfluences[d.currentFrame]=e*g;this.morphTargetInfluences[d.lastFrame]=(1-e)*g}}};
  12384. THREE.LensFlarePlugin=function(){function b(b){var c=a.createProgram(),d=a.createShader(a.FRAGMENT_SHADER),e=a.createShader(a.VERTEX_SHADER);a.shaderSource(d,b.fragmentShader);a.shaderSource(e,b.vertexShader);a.compileShader(d);a.compileShader(e);a.attachShader(c,d);a.attachShader(c,e);a.linkProgram(c);return c}var a,c,d,e,f,g,h,i,j,l,n,k,m;this.init=function(p){a=p.context;c=p;d=new Float32Array(16);e=new Uint16Array(6);p=0;d[p++]=-1;d[p++]=-1;d[p++]=0;d[p++]=0;d[p++]=1;d[p++]=-1;d[p++]=1;d[p++]=
  12385. 0;d[p++]=1;d[p++]=1;d[p++]=1;d[p++]=1;d[p++]=-1;d[p++]=1;d[p++]=0;d[p++]=1;p=0;e[p++]=0;e[p++]=1;e[p++]=2;e[p++]=0;e[p++]=2;e[p++]=3;f=a.createBuffer();g=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,f);a.bufferData(a.ARRAY_BUFFER,d,a.STATIC_DRAW);a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,g);a.bufferData(a.ELEMENT_ARRAY_BUFFER,e,a.STATIC_DRAW);h=a.createTexture();i=a.createTexture();a.bindTexture(a.TEXTURE_2D,h);a.texImage2D(a.TEXTURE_2D,0,a.RGB,16,16,0,a.RGB,a.UNSIGNED_BYTE,null);a.texParameteri(a.TEXTURE_2D,
  12386. a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST);a.bindTexture(a.TEXTURE_2D,i);a.texImage2D(a.TEXTURE_2D,0,a.RGBA,16,16,0,a.RGBA,a.UNSIGNED_BYTE,null);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE);a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.NEAREST);
  12387. a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.NEAREST);if(a.getParameter(a.MAX_VERTEX_TEXTURE_IMAGE_UNITS)<=0){j=false;l=b(THREE.ShaderFlares.lensFlare)}else{j=true;l=b(THREE.ShaderFlares.lensFlareVertexTexture)}n={};k={};n.vertex=a.getAttribLocation(l,"position");n.uv=a.getAttribLocation(l,"uv");k.renderType=a.getUniformLocation(l,"renderType");k.map=a.getUniformLocation(l,"map");k.occlusionMap=a.getUniformLocation(l,"occlusionMap");k.opacity=a.getUniformLocation(l,"opacity");k.color=a.getUniformLocation(l,
  12388. "color");k.scale=a.getUniformLocation(l,"scale");k.rotation=a.getUniformLocation(l,"rotation");k.screenPosition=a.getUniformLocation(l,"screenPosition");m=false};this.render=function(b,d,e,u){var b=b.__webglFlares,s=b.length;if(s){var t=new THREE.Vector3,o=u/e,x=e*0.5,z=u*0.5,A=16/u,v=new THREE.Vector2(A*o,A),w=new THREE.Vector3(1,1,0),F=new THREE.Vector2(1,1),C=k,A=n;a.useProgram(l);if(!m){a.enableVertexAttribArray(n.vertex);a.enableVertexAttribArray(n.uv);m=true}a.uniform1i(C.occlusionMap,0);a.uniform1i(C.map,
  12389. 1);a.bindBuffer(a.ARRAY_BUFFER,f);a.vertexAttribPointer(A.vertex,2,a.FLOAT,false,16,0);a.vertexAttribPointer(A.uv,2,a.FLOAT,false,16,8);a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,g);a.disable(a.CULL_FACE);a.depthMask(false);var B,I,K,E,D;for(B=0;B<s;B++){A=16/u;v.set(A*o,A);E=b[B];t.set(E.matrixWorld.elements[12],E.matrixWorld.elements[13],E.matrixWorld.elements[14]);d.matrixWorldInverse.multiplyVector3(t);d.projectionMatrix.multiplyVector3(t);w.copy(t);F.x=w.x*x+x;F.y=w.y*z+z;if(j||F.x>0&&F.x<e&&F.y>0&&
  12390. F.y<u){a.activeTexture(a.TEXTURE1);a.bindTexture(a.TEXTURE_2D,h);a.copyTexImage2D(a.TEXTURE_2D,0,a.RGB,F.x-8,F.y-8,16,16,0);a.uniform1i(C.renderType,0);a.uniform2f(C.scale,v.x,v.y);a.uniform3f(C.screenPosition,w.x,w.y,w.z);a.disable(a.BLEND);a.enable(a.DEPTH_TEST);a.drawElements(a.TRIANGLES,6,a.UNSIGNED_SHORT,0);a.activeTexture(a.TEXTURE0);a.bindTexture(a.TEXTURE_2D,i);a.copyTexImage2D(a.TEXTURE_2D,0,a.RGBA,F.x-8,F.y-8,16,16,0);a.uniform1i(C.renderType,1);a.disable(a.DEPTH_TEST);a.activeTexture(a.TEXTURE1);
  12391. a.bindTexture(a.TEXTURE_2D,h);a.drawElements(a.TRIANGLES,6,a.UNSIGNED_SHORT,0);E.positionScreen.copy(w);E.customUpdateCallback?E.customUpdateCallback(E):E.updateLensFlares();a.uniform1i(C.renderType,2);a.enable(a.BLEND);I=0;for(K=E.lensFlares.length;I<K;I++){D=E.lensFlares[I];if(D.opacity>0.001&&D.scale>0.001){w.x=D.x;w.y=D.y;w.z=D.z;A=D.size*D.scale/u;v.x=A*o;v.y=A;a.uniform3f(C.screenPosition,w.x,w.y,w.z);a.uniform2f(C.scale,v.x,v.y);a.uniform1f(C.rotation,D.rotation);a.uniform1f(C.opacity,D.opacity);
  12392. a.uniform3f(C.color,D.color.r,D.color.g,D.color.b);c.setBlending(D.blending,D.blendEquation,D.blendSrc,D.blendDst);c.setTexture(D.texture,1);a.drawElements(a.TRIANGLES,6,a.UNSIGNED_SHORT,0)}}}}a.enable(a.CULL_FACE);a.enable(a.DEPTH_TEST);a.depthMask(true)}}};
  12393. THREE.ShadowMapPlugin=function(){var b,a,c,d,e=new THREE.Frustum,f=new THREE.Matrix4,g=new THREE.Vector3,h=new THREE.Vector3;this.init=function(e){b=e.context;a=e;var e=THREE.ShaderLib.depthRGBA,f=THREE.UniformsUtils.clone(e.uniforms);c=new THREE.ShaderMaterial({fragmentShader:e.fragmentShader,vertexShader:e.vertexShader,uniforms:f});d=new THREE.ShaderMaterial({fragmentShader:e.fragmentShader,vertexShader:e.vertexShader,uniforms:f,morphTargets:true});c._shadowPass=true;d._shadowPass=true};this.render=
  12394. function(b,c){a.shadowMapEnabled&&a.shadowMapAutoUpdate&&this.update(b,c)};this.update=function(i,j){var l,n,k,m,p,q,r,u,s,t=[];m=0;b.clearColor(1,1,1,1);b.disable(b.BLEND);b.enable(b.CULL_FACE);a.shadowMapCullFrontFaces?b.cullFace(b.FRONT):b.cullFace(b.BACK);a.setDepthTest(true);l=0;for(n=i.__lights.length;l<n;l++){k=i.__lights[l];if(k.castShadow)if(k instanceof THREE.DirectionalLight&&k.shadowCascade)for(p=0;p<k.shadowCascadeCount;p++){var o;if(k.shadowCascadeArray[p])o=k.shadowCascadeArray[p];
  12395. else{s=k;r=p;o=new THREE.DirectionalLight;o.isVirtual=true;o.onlyShadow=true;o.castShadow=true;o.shadowCameraNear=s.shadowCameraNear;o.shadowCameraFar=s.shadowCameraFar;o.shadowCameraLeft=s.shadowCameraLeft;o.shadowCameraRight=s.shadowCameraRight;o.shadowCameraBottom=s.shadowCameraBottom;o.shadowCameraTop=s.shadowCameraTop;o.shadowCameraVisible=s.shadowCameraVisible;o.shadowDarkness=s.shadowDarkness;o.shadowBias=s.shadowCascadeBias[r];o.shadowMapWidth=s.shadowCascadeWidth[r];o.shadowMapHeight=s.shadowCascadeHeight[r];
  12396. o.pointsWorld=[];o.pointsFrustum=[];u=o.pointsWorld;q=o.pointsFrustum;for(var x=0;x<8;x++){u[x]=new THREE.Vector3;q[x]=new THREE.Vector3}u=s.shadowCascadeNearZ[r];s=s.shadowCascadeFarZ[r];q[0].set(-1,-1,u);q[1].set(1,-1,u);q[2].set(-1,1,u);q[3].set(1,1,u);q[4].set(-1,-1,s);q[5].set(1,-1,s);q[6].set(-1,1,s);q[7].set(1,1,s);o.originalCamera=j;q=new THREE.Gyroscope;q.position=k.shadowCascadeOffset;q.add(o);q.add(o.target);j.add(q);k.shadowCascadeArray[p]=o;console.log("Created virtualLight",o)}r=k;u=
  12397. p;s=r.shadowCascadeArray[u];s.position.copy(r.position);s.target.position.copy(r.target.position);s.lookAt(s.target);s.shadowCameraVisible=r.shadowCameraVisible;s.shadowDarkness=r.shadowDarkness;s.shadowBias=r.shadowCascadeBias[u];q=r.shadowCascadeNearZ[u];r=r.shadowCascadeFarZ[u];s=s.pointsFrustum;s[0].z=q;s[1].z=q;s[2].z=q;s[3].z=q;s[4].z=r;s[5].z=r;s[6].z=r;s[7].z=r;t[m]=o;m++}else{t[m]=k;m++}}l=0;for(n=t.length;l<n;l++){k=t[l];if(!k.shadowMap){k.shadowMap=new THREE.WebGLRenderTarget(k.shadowMapWidth,
  12398. k.shadowMapHeight,{minFilter:THREE.LinearFilter,magFilter:THREE.LinearFilter,format:THREE.RGBAFormat});k.shadowMapSize=new THREE.Vector2(k.shadowMapWidth,k.shadowMapHeight);k.shadowMatrix=new THREE.Matrix4}if(!k.shadowCamera){if(k instanceof THREE.SpotLight)k.shadowCamera=new THREE.PerspectiveCamera(k.shadowCameraFov,k.shadowMapWidth/k.shadowMapHeight,k.shadowCameraNear,k.shadowCameraFar);else if(k instanceof THREE.DirectionalLight)k.shadowCamera=new THREE.OrthographicCamera(k.shadowCameraLeft,k.shadowCameraRight,
  12399. k.shadowCameraTop,k.shadowCameraBottom,k.shadowCameraNear,k.shadowCameraFar);else{console.error("Unsupported light type for shadow");continue}i.add(k.shadowCamera);a.autoUpdateScene&&i.updateMatrixWorld()}if(k.shadowCameraVisible&&!k.cameraHelper){k.cameraHelper=new THREE.CameraHelper(k.shadowCamera);k.shadowCamera.add(k.cameraHelper)}if(k.isVirtual&&o.originalCamera==j){p=j;m=k.shadowCamera;q=k.pointsFrustum;s=k.pointsWorld;g.set(Infinity,Infinity,Infinity);h.set(-Infinity,-Infinity,-Infinity);for(r=
  12400. 0;r<8;r++){u=s[r];u.copy(q[r]);THREE.ShadowMapPlugin.__projector.unprojectVector(u,p);m.matrixWorldInverse.multiplyVector3(u);if(u.x<g.x)g.x=u.x;if(u.x>h.x)h.x=u.x;if(u.y<g.y)g.y=u.y;if(u.y>h.y)h.y=u.y;if(u.z<g.z)g.z=u.z;if(u.z>h.z)h.z=u.z}m.left=g.x;m.right=h.x;m.top=h.y;m.bottom=g.y;m.updateProjectionMatrix()}m=k.shadowMap;q=k.shadowMatrix;p=k.shadowCamera;p.position.copy(k.matrixWorld.getPosition());p.lookAt(k.target.matrixWorld.getPosition());p.updateMatrixWorld();p.matrixWorldInverse.getInverse(p.matrixWorld);
  12401. if(k.cameraHelper)k.cameraHelper.lines.visible=k.shadowCameraVisible;k.shadowCameraVisible&&k.cameraHelper.update();q.set(0.5,0,0,0.5,0,0.5,0,0.5,0,0,0.5,0.5,0,0,0,1);q.multiplySelf(p.projectionMatrix);q.multiplySelf(p.matrixWorldInverse);if(!p._viewMatrixArray)p._viewMatrixArray=new Float32Array(16);if(!p._projectionMatrixArray)p._projectionMatrixArray=new Float32Array(16);p.matrixWorldInverse.flattenToArray(p._viewMatrixArray);p.projectionMatrix.flattenToArray(p._projectionMatrixArray);f.multiply(p.projectionMatrix,
  12402. p.matrixWorldInverse);e.setFromMatrix(f);a.setRenderTarget(m);a.clear();s=i.__webglObjects;k=0;for(m=s.length;k<m;k++){r=s[k];q=r.object;r.render=false;if(q.visible&&q.castShadow&&(!(q instanceof THREE.Mesh)||!q.frustumCulled||e.contains(q))){q._modelViewMatrix.multiply(p.matrixWorldInverse,q.matrixWorld);r.render=true}}k=0;for(m=s.length;k<m;k++){r=s[k];if(r.render){q=r.object;r=r.buffer;u=q.customDepthMaterial?q.customDepthMaterial:q.geometry.morphTargets.length?d:c;r instanceof THREE.BufferGeometry?
  12403. a.renderBufferDirect(p,i.__lights,null,u,r,q):a.renderBuffer(p,i.__lights,null,u,r,q)}}s=i.__webglObjectsImmediate;k=0;for(m=s.length;k<m;k++){r=s[k];q=r.object;if(q.visible&&q.castShadow){q._modelViewMatrix.multiply(p.matrixWorldInverse,q.matrixWorld);a.renderImmediateObject(p,i.__lights,null,c,q)}}}l=a.getClearColor();n=a.getClearAlpha();b.clearColor(l.r,l.g,l.b,n);b.enable(b.BLEND);a.shadowMapCullFrontFaces&&b.cullFace(b.BACK)}};THREE.ShadowMapPlugin.__projector=new THREE.Projector;
  12404. THREE.SpritePlugin=function(){function b(a,b){return b.z-a.z}var a,c,d,e,f,g,h,i,j,l;this.init=function(b){a=b.context;c=b;d=new Float32Array(16);e=new Uint16Array(6);b=0;d[b++]=-1;d[b++]=-1;d[b++]=0;d[b++]=1;d[b++]=1;d[b++]=-1;d[b++]=1;d[b++]=1;d[b++]=1;d[b++]=1;d[b++]=1;d[b++]=0;d[b++]=-1;d[b++]=1;d[b++]=0;b=d[b++]=0;e[b++]=0;e[b++]=1;e[b++]=2;e[b++]=0;e[b++]=2;e[b++]=3;f=a.createBuffer();g=a.createBuffer();a.bindBuffer(a.ARRAY_BUFFER,f);a.bufferData(a.ARRAY_BUFFER,d,a.STATIC_DRAW);a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,
  12405. g);a.bufferData(a.ELEMENT_ARRAY_BUFFER,e,a.STATIC_DRAW);var b=THREE.ShaderSprite.sprite,k=a.createProgram(),m=a.createShader(a.FRAGMENT_SHADER),p=a.createShader(a.VERTEX_SHADER);a.shaderSource(m,b.fragmentShader);a.shaderSource(p,b.vertexShader);a.compileShader(m);a.compileShader(p);a.attachShader(k,m);a.attachShader(k,p);a.linkProgram(k);h=k;i={};j={};i.position=a.getAttribLocation(h,"position");i.uv=a.getAttribLocation(h,"uv");j.uvOffset=a.getUniformLocation(h,"uvOffset");j.uvScale=a.getUniformLocation(h,
  12406. "uvScale");j.rotation=a.getUniformLocation(h,"rotation");j.scale=a.getUniformLocation(h,"scale");j.alignment=a.getUniformLocation(h,"alignment");j.color=a.getUniformLocation(h,"color");j.map=a.getUniformLocation(h,"map");j.opacity=a.getUniformLocation(h,"opacity");j.useScreenCoordinates=a.getUniformLocation(h,"useScreenCoordinates");j.affectedByDistance=a.getUniformLocation(h,"affectedByDistance");j.screenPosition=a.getUniformLocation(h,"screenPosition");j.modelViewMatrix=a.getUniformLocation(h,"modelViewMatrix");
  12407. j.projectionMatrix=a.getUniformLocation(h,"projectionMatrix");l=false};this.render=function(d,e,m,p){var d=d.__webglSprites,q=d.length;if(q){var r=i,u=j,s=p/m,m=m*0.5,t=p*0.5,o=true;a.useProgram(h);if(!l){a.enableVertexAttribArray(r.position);a.enableVertexAttribArray(r.uv);l=true}a.disable(a.CULL_FACE);a.enable(a.BLEND);a.depthMask(true);a.bindBuffer(a.ARRAY_BUFFER,f);a.vertexAttribPointer(r.position,2,a.FLOAT,false,16,0);a.vertexAttribPointer(r.uv,2,a.FLOAT,false,16,8);a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,
  12408. g);a.uniformMatrix4fv(u.projectionMatrix,false,e._projectionMatrixArray);a.activeTexture(a.TEXTURE0);a.uniform1i(u.map,0);for(var x,z=[],r=0;r<q;r++){x=d[r];if(x.visible&&x.opacity!==0)if(x.useScreenCoordinates)x.z=-x.position.z;else{x._modelViewMatrix.multiply(e.matrixWorldInverse,x.matrixWorld);x.z=-x._modelViewMatrix.elements[14]}}d.sort(b);for(r=0;r<q;r++){x=d[r];if(x.visible&&x.opacity!==0&&x.map&&x.map.image&&x.map.image.width){if(x.useScreenCoordinates){a.uniform1i(u.useScreenCoordinates,1);
  12409. a.uniform3f(u.screenPosition,(x.position.x-m)/m,(t-x.position.y)/t,Math.max(0,Math.min(1,x.position.z)))}else{a.uniform1i(u.useScreenCoordinates,0);a.uniform1i(u.affectedByDistance,x.affectedByDistance?1:0);a.uniformMatrix4fv(u.modelViewMatrix,false,x._modelViewMatrix.elements)}e=x.map.image.width/(x.scaleByViewport?p:1);z[0]=e*s*x.scale.x;z[1]=e*x.scale.y;a.uniform2f(u.uvScale,x.uvScale.x,x.uvScale.y);a.uniform2f(u.uvOffset,x.uvOffset.x,x.uvOffset.y);a.uniform2f(u.alignment,x.alignment.x,x.alignment.y);
  12410. a.uniform1f(u.opacity,x.opacity);a.uniform3f(u.color,x.color.r,x.color.g,x.color.b);a.uniform1f(u.rotation,x.rotation);a.uniform2fv(u.scale,z);if(x.mergeWith3D&&!o){a.enable(a.DEPTH_TEST);o=true}else if(!x.mergeWith3D&&o){a.disable(a.DEPTH_TEST);o=false}c.setBlending(x.blending,x.blendEquation,x.blendSrc,x.blendDst);c.setTexture(x.map,0);a.drawElements(a.TRIANGLES,6,a.UNSIGNED_SHORT,0)}}a.enable(a.CULL_FACE);a.enable(a.DEPTH_TEST);a.depthMask(true)}}};
  12411. THREE.DepthPassPlugin=function(){this.enabled=false;this.renderTarget=null;var b,a,c,d,e=new THREE.Frustum,f=new THREE.Matrix4;this.init=function(e){b=e.context;a=e;var e=THREE.ShaderLib.depthRGBA,f=THREE.UniformsUtils.clone(e.uniforms);c=new THREE.ShaderMaterial({fragmentShader:e.fragmentShader,vertexShader:e.vertexShader,uniforms:f});d=new THREE.ShaderMaterial({fragmentShader:e.fragmentShader,vertexShader:e.vertexShader,uniforms:f,morphTargets:true});c._shadowPass=true;d._shadowPass=true};this.render=
  12412. function(a,b){this.enabled&&this.update(a,b)};this.update=function(g,h){var i,j,l,n,k,m;b.clearColor(1,1,1,1);b.disable(b.BLEND);a.setDepthTest(true);a.autoUpdateScene&&g.updateMatrixWorld();if(!h._viewMatrixArray)h._viewMatrixArray=new Float32Array(16);if(!h._projectionMatrixArray)h._projectionMatrixArray=new Float32Array(16);h.matrixWorldInverse.getInverse(h.matrixWorld);h.matrixWorldInverse.flattenToArray(h._viewMatrixArray);h.projectionMatrix.flattenToArray(h._projectionMatrixArray);f.multiply(h.projectionMatrix,
  12413. h.matrixWorldInverse);e.setFromMatrix(f);a.setRenderTarget(this.renderTarget);a.clear();m=g.__webglObjects;i=0;for(j=m.length;i<j;i++){l=m[i];k=l.object;l.render=false;if(k.visible&&(!(k instanceof THREE.Mesh)||!k.frustumCulled||e.contains(k))){k._modelViewMatrix.multiply(h.matrixWorldInverse,k.matrixWorld);l.render=true}}i=0;for(j=m.length;i<j;i++){l=m[i];if(l.render){k=l.object;l=l.buffer;a.setObjectFaces(k);n=k.customDepthMaterial?k.customDepthMaterial:k.geometry.morphTargets.length?d:c;l instanceof
  12414. THREE.BufferGeometry?a.renderBufferDirect(h,g.__lights,null,n,l,k):a.renderBuffer(h,g.__lights,null,n,l,k)}}m=g.__webglObjectsImmediate;i=0;for(j=m.length;i<j;i++){l=m[i];k=l.object;if(k.visible&&k.castShadow){k._modelViewMatrix.multiply(h.matrixWorldInverse,k.matrixWorld);a.renderImmediateObject(h,g.__lights,null,c,k)}}i=a.getClearColor();j=a.getClearAlpha();b.clearColor(i.r,i.g,i.b,j);b.enable(b.BLEND)}};
  12415. THREE.WebGLRenderer&&(THREE.AnaglyphWebGLRenderer=function(b){THREE.WebGLRenderer.call(this,b);this.autoUpdateScene=false;var a=this,c=this.setSize,d=this.render,e=new THREE.PerspectiveCamera,f=new THREE.PerspectiveCamera,g=new THREE.Matrix4,h=new THREE.Matrix4,i,j,l,n;e.matrixAutoUpdate=f.matrixAutoUpdate=false;var b={minFilter:THREE.LinearFilter,magFilter:THREE.NearestFilter,format:THREE.RGBAFormat},k=new THREE.WebGLRenderTarget(512,512,b),m=new THREE.WebGLRenderTarget(512,512,b),p=new THREE.PerspectiveCamera(53,
  12416. 1,1,1E4);p.position.z=2;var b=new THREE.ShaderMaterial({uniforms:{mapLeft:{type:"t",value:0,texture:k},mapRight:{type:"t",value:1,texture:m}},vertexShader:"varying vec2 vUv;\nvoid main() {\nvUv = vec2( uv.x, 1.0 - uv.y );\ngl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",fragmentShader:"uniform sampler2D mapLeft;\nuniform sampler2D mapRight;\nvarying vec2 vUv;\nvoid main() {\nvec4 colorL, colorR;\nvec2 uv = vUv;\ncolorL = texture2D( mapLeft, uv );\ncolorR = texture2D( mapRight, uv );\ngl_FragColor = vec4( colorL.g * 0.7 + colorL.b * 0.3, colorR.g, colorR.b, colorL.a + colorR.a ) * 1.1;\n}"}),
  12417. q=new THREE.Scene,b=new THREE.Mesh(new THREE.PlaneGeometry(2,2),b);b.rotation.x=Math.PI/2;q.add(b);q.add(p);this.setSize=function(b,d){c.call(a,b,d);k.width=b;k.height=d;m.width=b;m.height=d};this.render=function(b,c){b.updateMatrixWorld();if(i!==c.aspect||j!==c.near||l!==c.far||n!==c.fov){i=c.aspect;j=c.near;l=c.far;n=c.fov;var s=c.projectionMatrix.clone(),t=125/30*0.5,o=t*j/125,x=j*Math.tan(n*Math.PI/360),z;g.elements[12]=t;h.elements[12]=-t;t=-x*i+o;z=x*i+o;s.elements[0]=2*j/(z-t);s.elements[8]=
  12418. (z+t)/(z-t);e.projectionMatrix.copy(s);t=-x*i-o;z=x*i-o;s.elements[0]=2*j/(z-t);s.elements[8]=(z+t)/(z-t);f.projectionMatrix.copy(s)}e.matrixWorld.copy(c.matrixWorld).multiplySelf(h);e.position.copy(c.position);e.near=c.near;e.far=c.far;d.call(a,b,e,k,true);f.matrixWorld.copy(c.matrixWorld).multiplySelf(g);f.position.copy(c.position);f.near=c.near;f.far=c.far;d.call(a,b,f,m,true);q.updateMatrixWorld();d.call(a,q,p)}});
  12419. THREE.WebGLRenderer&&(THREE.CrosseyedWebGLRenderer=function(b){THREE.WebGLRenderer.call(this,b);this.autoClear=false;var a=this,c=this.setSize,d=this.render,e,f,g=new THREE.PerspectiveCamera;g.target=new THREE.Vector3(0,0,0);var h=new THREE.PerspectiveCamera;h.target=new THREE.Vector3(0,0,0);a.separation=10;if(b&&b.separation!==void 0)a.separation=b.separation;this.setSize=function(b,d){c.call(a,b,d);e=b/2;f=d};this.render=function(b,c){this.clear();g.fov=c.fov;g.aspect=0.5*c.aspect;g.near=c.near;
  12420. g.far=c.far;g.updateProjectionMatrix();g.position.copy(c.position);g.target.copy(c.target);g.translateX(a.separation);g.lookAt(g.target);h.projectionMatrix=g.projectionMatrix;h.position.copy(c.position);h.target.copy(c.target);h.translateX(-a.separation);h.lookAt(h.target);this.setViewport(0,0,e,f);d.call(a,b,g);this.setViewport(e,0,e,f);d.call(a,b,h,false)}});
  12421. THREE.ShaderFlares={lensFlareVertexTexture:{vertexShader:"uniform vec3 screenPosition;\nuniform vec2 scale;\nuniform float rotation;\nuniform int renderType;\nuniform sampler2D occlusionMap;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nvUV = uv;\nvec2 pos = position;\nif( renderType == 2 ) {\nvec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +\ntexture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +\ntexture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +\ntexture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +\ntexture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +\ntexture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +\ntexture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +\ntexture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +\ntexture2D( occlusionMap, vec2( 0.5, 0.5 ) );\nvVisibility = ( visibility.r / 9.0 ) *\n( 1.0 - visibility.g / 9.0 ) *\n( visibility.b / 9.0 ) *\n( 1.0 - visibility.a / 9.0 );\npos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\npos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n}\ngl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",fragmentShader:"precision mediump float;\nuniform sampler2D map;\nuniform float opacity;\nuniform int renderType;\nuniform vec3 color;\nvarying vec2 vUV;\nvarying float vVisibility;\nvoid main() {\nif( renderType == 0 ) {\ngl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );\n} else if( renderType == 1 ) {\ngl_FragColor = texture2D( map, vUV );\n} else {\nvec4 texture = texture2D( map, vUV );\ntexture.a *= opacity * vVisibility;\ngl_FragColor = texture;\ngl_FragColor.rgb *= color;\n}\n}"},
  12422. lensFlare:{vertexShader:"uniform vec3 screenPosition;\nuniform vec2 scale;\nuniform float rotation;\nuniform int renderType;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvoid main() {\nvUV = uv;\nvec2 pos = position;\nif( renderType == 2 ) {\npos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;\npos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;\n}\ngl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );\n}",fragmentShader:"precision mediump float;\nuniform sampler2D map;\nuniform sampler2D occlusionMap;\nuniform float opacity;\nuniform int renderType;\nuniform vec3 color;\nvarying vec2 vUV;\nvoid main() {\nif( renderType == 0 ) {\ngl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );\n} else if( renderType == 1 ) {\ngl_FragColor = texture2D( map, vUV );\n} else {\nfloat visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +\ntexture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +\ntexture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +\ntexture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;\nvisibility = ( 1.0 - visibility / 4.0 );\nvec4 texture = texture2D( map, vUV );\ntexture.a *= opacity * visibility;\ngl_FragColor = texture;\ngl_FragColor.rgb *= color;\n}\n}"}};
  12423. THREE.ShaderSprite={sprite:{vertexShader:"uniform int useScreenCoordinates;\nuniform int affectedByDistance;\nuniform vec3 screenPosition;\nuniform mat4 modelViewMatrix;\nuniform mat4 projectionMatrix;\nuniform float rotation;\nuniform vec2 scale;\nuniform vec2 alignment;\nuniform vec2 uvOffset;\nuniform vec2 uvScale;\nattribute vec2 position;\nattribute vec2 uv;\nvarying vec2 vUV;\nvoid main() {\nvUV = uvOffset + uv * uvScale;\nvec2 alignedPosition = position + alignment;\nvec2 rotatedPosition;\nrotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;\nrotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;\nvec4 finalPosition;\nif( useScreenCoordinates != 0 ) {\nfinalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );\n} else {\nfinalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );\nfinalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );\n}\ngl_Position = finalPosition;\n}",
  12424. fragmentShader:"precision mediump float;\nuniform vec3 color;\nuniform sampler2D map;\nuniform float opacity;\nvarying vec2 vUV;\nvoid main() {\nvec4 texture = texture2D( map, vUV );\ngl_FragColor = vec4( color * texture.xyz, texture.a * opacity );\n}"}};
  12425. >>>>>>> dev
粤ICP备19079148号