three.js 780 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '72dev' };
  6. // browserify support
  7. if ( typeof module === 'object' ) {
  8. module.exports = THREE;
  9. }
  10. // polyfills
  11. if ( Math.sign === undefined ) {
  12. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  13. Math.sign = function ( x ) {
  14. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : +x;
  15. };
  16. }
  17. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  18. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  19. // GL STATE CONSTANTS
  20. THREE.CullFaceNone = 0;
  21. THREE.CullFaceBack = 1;
  22. THREE.CullFaceFront = 2;
  23. THREE.CullFaceFrontBack = 3;
  24. THREE.FrontFaceDirectionCW = 0;
  25. THREE.FrontFaceDirectionCCW = 1;
  26. // SHADOWING TYPES
  27. THREE.BasicShadowMap = 0;
  28. THREE.PCFShadowMap = 1;
  29. THREE.PCFSoftShadowMap = 2;
  30. // MATERIAL CONSTANTS
  31. // side
  32. THREE.FrontSide = 0;
  33. THREE.BackSide = 1;
  34. THREE.DoubleSide = 2;
  35. // shading
  36. THREE.NoShading = 0;
  37. THREE.FlatShading = 1;
  38. THREE.SmoothShading = 2;
  39. // colors
  40. THREE.NoColors = 0;
  41. THREE.FaceColors = 1;
  42. THREE.VertexColors = 2;
  43. // blending modes
  44. THREE.NoBlending = 0;
  45. THREE.NormalBlending = 1;
  46. THREE.AdditiveBlending = 2;
  47. THREE.SubtractiveBlending = 3;
  48. THREE.MultiplyBlending = 4;
  49. THREE.CustomBlending = 5;
  50. // custom blending equations
  51. // (numbers start from 100 not to clash with other
  52. // mappings to OpenGL constants defined in Texture.js)
  53. THREE.AddEquation = 100;
  54. THREE.SubtractEquation = 101;
  55. THREE.ReverseSubtractEquation = 102;
  56. THREE.MinEquation = 103;
  57. THREE.MaxEquation = 104;
  58. // custom blending destination factors
  59. THREE.ZeroFactor = 200;
  60. THREE.OneFactor = 201;
  61. THREE.SrcColorFactor = 202;
  62. THREE.OneMinusSrcColorFactor = 203;
  63. THREE.SrcAlphaFactor = 204;
  64. THREE.OneMinusSrcAlphaFactor = 205;
  65. THREE.DstAlphaFactor = 206;
  66. THREE.OneMinusDstAlphaFactor = 207;
  67. // custom blending source factors
  68. //THREE.ZeroFactor = 200;
  69. //THREE.OneFactor = 201;
  70. //THREE.SrcAlphaFactor = 204;
  71. //THREE.OneMinusSrcAlphaFactor = 205;
  72. //THREE.DstAlphaFactor = 206;
  73. //THREE.OneMinusDstAlphaFactor = 207;
  74. THREE.DstColorFactor = 208;
  75. THREE.OneMinusDstColorFactor = 209;
  76. THREE.SrcAlphaSaturateFactor = 210;
  77. // depth modes
  78. THREE.NeverDepth = 0;
  79. THREE.AlwaysDepth = 1;
  80. THREE.LessDepth = 2;
  81. THREE.LessEqualDepth = 3;
  82. THREE.EqualDepth = 4;
  83. THREE.GreaterEqualDepth = 5;
  84. THREE.GreaterDepth = 6;
  85. THREE.NotEqualDepth = 7;
  86. // TEXTURE CONSTANTS
  87. THREE.MultiplyOperation = 0;
  88. THREE.MixOperation = 1;
  89. THREE.AddOperation = 2;
  90. // Mapping modes
  91. THREE.UVMapping = 300;
  92. THREE.CubeReflectionMapping = 301;
  93. THREE.CubeRefractionMapping = 302;
  94. THREE.EquirectangularReflectionMapping = 303;
  95. THREE.EquirectangularRefractionMapping = 304;
  96. THREE.SphericalReflectionMapping = 305;
  97. // Wrapping modes
  98. THREE.RepeatWrapping = 1000;
  99. THREE.ClampToEdgeWrapping = 1001;
  100. THREE.MirroredRepeatWrapping = 1002;
  101. // Filters
  102. THREE.NearestFilter = 1003;
  103. THREE.NearestMipMapNearestFilter = 1004;
  104. THREE.NearestMipMapLinearFilter = 1005;
  105. THREE.LinearFilter = 1006;
  106. THREE.LinearMipMapNearestFilter = 1007;
  107. THREE.LinearMipMapLinearFilter = 1008;
  108. // Data types
  109. THREE.UnsignedByteType = 1009;
  110. THREE.ByteType = 1010;
  111. THREE.ShortType = 1011;
  112. THREE.UnsignedShortType = 1012;
  113. THREE.IntType = 1013;
  114. THREE.UnsignedIntType = 1014;
  115. THREE.FloatType = 1015;
  116. THREE.HalfFloatType = 1025;
  117. // Pixel types
  118. //THREE.UnsignedByteType = 1009;
  119. THREE.UnsignedShort4444Type = 1016;
  120. THREE.UnsignedShort5551Type = 1017;
  121. THREE.UnsignedShort565Type = 1018;
  122. // Pixel formats
  123. THREE.AlphaFormat = 1019;
  124. THREE.RGBFormat = 1020;
  125. THREE.RGBAFormat = 1021;
  126. THREE.LuminanceFormat = 1022;
  127. THREE.LuminanceAlphaFormat = 1023;
  128. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  129. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  130. // DDS / ST3C Compressed texture formats
  131. THREE.RGB_S3TC_DXT1_Format = 2001;
  132. THREE.RGBA_S3TC_DXT1_Format = 2002;
  133. THREE.RGBA_S3TC_DXT3_Format = 2003;
  134. THREE.RGBA_S3TC_DXT5_Format = 2004;
  135. // PVRTC compressed texture formats
  136. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  137. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  138. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  139. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  140. // DEPRECATED
  141. THREE.Projector = function () {
  142. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  143. this.projectVector = function ( vector, camera ) {
  144. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  145. vector.project( camera );
  146. };
  147. this.unprojectVector = function ( vector, camera ) {
  148. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  149. vector.unproject( camera );
  150. };
  151. this.pickingRay = function ( vector, camera ) {
  152. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  153. };
  154. };
  155. THREE.CanvasRenderer = function () {
  156. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  157. this.domElement = document.createElement( 'canvas' );
  158. this.clear = function () {};
  159. this.render = function () {};
  160. this.setClearColor = function () {};
  161. this.setSize = function () {};
  162. };
  163. // File:src/math/Color.js
  164. /**
  165. * @author mrdoob / http://mrdoob.com/
  166. */
  167. THREE.Color = function ( color ) {
  168. if ( arguments.length === 3 ) {
  169. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  170. }
  171. return this.set( color )
  172. };
  173. THREE.Color.prototype = {
  174. constructor: THREE.Color,
  175. r: 1, g: 1, b: 1,
  176. set: function ( value ) {
  177. if ( value instanceof THREE.Color ) {
  178. this.copy( value );
  179. } else if ( typeof value === 'number' ) {
  180. this.setHex( value );
  181. } else if ( typeof value === 'string' ) {
  182. this.setStyle( value );
  183. }
  184. return this;
  185. },
  186. setHex: function ( hex ) {
  187. hex = Math.floor( hex );
  188. this.r = ( hex >> 16 & 255 ) / 255;
  189. this.g = ( hex >> 8 & 255 ) / 255;
  190. this.b = ( hex & 255 ) / 255;
  191. return this;
  192. },
  193. setRGB: function ( r, g, b ) {
  194. this.r = r;
  195. this.g = g;
  196. this.b = b;
  197. return this;
  198. },
  199. setHSL: function ( h, s, l ) {
  200. // h,s,l ranges are in 0.0 - 1.0
  201. if ( s === 0 ) {
  202. this.r = this.g = this.b = l;
  203. } else {
  204. var hue2rgb = function ( p, q, t ) {
  205. if ( t < 0 ) t += 1;
  206. if ( t > 1 ) t -= 1;
  207. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  208. if ( t < 1 / 2 ) return q;
  209. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  210. return p;
  211. };
  212. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  213. var q = ( 2 * l ) - p;
  214. this.r = hue2rgb( q, p, h + 1 / 3 );
  215. this.g = hue2rgb( q, p, h );
  216. this.b = hue2rgb( q, p, h - 1 / 3 );
  217. }
  218. return this;
  219. },
  220. setStyle: function ( style ) {
  221. // rgb(255,0,0)
  222. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  223. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  224. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  225. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  226. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  227. return this;
  228. }
  229. // rgb(100%,0%,0%)
  230. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  231. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  232. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  233. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  234. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  235. return this;
  236. }
  237. // #ff0000
  238. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  239. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  240. this.setHex( parseInt( color[ 1 ], 16 ) );
  241. return this;
  242. }
  243. // #f00
  244. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  245. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  246. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  247. return this;
  248. }
  249. // red
  250. if ( /^(\w+)$/i.test( style ) ) {
  251. this.setHex( THREE.ColorKeywords[ style ] );
  252. return this;
  253. }
  254. },
  255. copy: function ( color ) {
  256. this.r = color.r;
  257. this.g = color.g;
  258. this.b = color.b;
  259. return this;
  260. },
  261. copyGammaToLinear: function ( color, gammaFactor ) {
  262. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  263. this.r = Math.pow( color.r, gammaFactor );
  264. this.g = Math.pow( color.g, gammaFactor );
  265. this.b = Math.pow( color.b, gammaFactor );
  266. return this;
  267. },
  268. copyLinearToGamma: function ( color, gammaFactor ) {
  269. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  270. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  271. this.r = Math.pow( color.r, safeInverse );
  272. this.g = Math.pow( color.g, safeInverse );
  273. this.b = Math.pow( color.b, safeInverse );
  274. return this;
  275. },
  276. convertGammaToLinear: function () {
  277. var r = this.r, g = this.g, b = this.b;
  278. this.r = r * r;
  279. this.g = g * g;
  280. this.b = b * b;
  281. return this;
  282. },
  283. convertLinearToGamma: function () {
  284. this.r = Math.sqrt( this.r );
  285. this.g = Math.sqrt( this.g );
  286. this.b = Math.sqrt( this.b );
  287. return this;
  288. },
  289. getHex: function () {
  290. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  291. },
  292. getHexString: function () {
  293. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  294. },
  295. getHSL: function ( optionalTarget ) {
  296. // h,s,l ranges are in 0.0 - 1.0
  297. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  298. var r = this.r, g = this.g, b = this.b;
  299. var max = Math.max( r, g, b );
  300. var min = Math.min( r, g, b );
  301. var hue, saturation;
  302. var lightness = ( min + max ) / 2.0;
  303. if ( min === max ) {
  304. hue = 0;
  305. saturation = 0;
  306. } else {
  307. var delta = max - min;
  308. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  309. switch ( max ) {
  310. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  311. case g: hue = ( b - r ) / delta + 2; break;
  312. case b: hue = ( r - g ) / delta + 4; break;
  313. }
  314. hue /= 6;
  315. }
  316. hsl.h = hue;
  317. hsl.s = saturation;
  318. hsl.l = lightness;
  319. return hsl;
  320. },
  321. getStyle: function () {
  322. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  323. },
  324. offsetHSL: function ( h, s, l ) {
  325. var hsl = this.getHSL();
  326. hsl.h += h; hsl.s += s; hsl.l += l;
  327. this.setHSL( hsl.h, hsl.s, hsl.l );
  328. return this;
  329. },
  330. add: function ( color ) {
  331. this.r += color.r;
  332. this.g += color.g;
  333. this.b += color.b;
  334. return this;
  335. },
  336. addColors: function ( color1, color2 ) {
  337. this.r = color1.r + color2.r;
  338. this.g = color1.g + color2.g;
  339. this.b = color1.b + color2.b;
  340. return this;
  341. },
  342. addScalar: function ( s ) {
  343. this.r += s;
  344. this.g += s;
  345. this.b += s;
  346. return this;
  347. },
  348. multiply: function ( color ) {
  349. this.r *= color.r;
  350. this.g *= color.g;
  351. this.b *= color.b;
  352. return this;
  353. },
  354. multiplyScalar: function ( s ) {
  355. this.r *= s;
  356. this.g *= s;
  357. this.b *= s;
  358. return this;
  359. },
  360. lerp: function ( color, alpha ) {
  361. this.r += ( color.r - this.r ) * alpha;
  362. this.g += ( color.g - this.g ) * alpha;
  363. this.b += ( color.b - this.b ) * alpha;
  364. return this;
  365. },
  366. equals: function ( c ) {
  367. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  368. },
  369. fromArray: function ( array ) {
  370. this.r = array[ 0 ];
  371. this.g = array[ 1 ];
  372. this.b = array[ 2 ];
  373. return this;
  374. },
  375. toArray: function ( array, offset ) {
  376. if ( array === undefined ) array = [];
  377. if ( offset === undefined ) offset = 0;
  378. array[ offset ] = this.r;
  379. array[ offset + 1 ] = this.g;
  380. array[ offset + 2 ] = this.b;
  381. return array;
  382. },
  383. clone: function () {
  384. return new THREE.Color().setRGB( this.r, this.g, this.b );
  385. }
  386. };
  387. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  388. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  389. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  390. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  391. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  392. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  393. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  394. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  395. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  396. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  397. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  398. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  399. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  400. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  401. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  402. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  403. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  404. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  405. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  406. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  407. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  408. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  409. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  410. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  411. // File:src/math/Quaternion.js
  412. /**
  413. * @author mikael emtinger / http://gomo.se/
  414. * @author alteredq / http://alteredqualia.com/
  415. * @author WestLangley / http://github.com/WestLangley
  416. * @author bhouston / http://exocortex.com
  417. */
  418. THREE.Quaternion = function ( x, y, z, w ) {
  419. this._x = x || 0;
  420. this._y = y || 0;
  421. this._z = z || 0;
  422. this._w = ( w !== undefined ) ? w : 1;
  423. };
  424. THREE.Quaternion.prototype = {
  425. constructor: THREE.Quaternion,
  426. _x: 0,_y: 0, _z: 0, _w: 0,
  427. get x () {
  428. return this._x;
  429. },
  430. set x ( value ) {
  431. this._x = value;
  432. this.onChangeCallback();
  433. },
  434. get y () {
  435. return this._y;
  436. },
  437. set y ( value ) {
  438. this._y = value;
  439. this.onChangeCallback();
  440. },
  441. get z () {
  442. return this._z;
  443. },
  444. set z ( value ) {
  445. this._z = value;
  446. this.onChangeCallback();
  447. },
  448. get w () {
  449. return this._w;
  450. },
  451. set w ( value ) {
  452. this._w = value;
  453. this.onChangeCallback();
  454. },
  455. set: function ( x, y, z, w ) {
  456. this._x = x;
  457. this._y = y;
  458. this._z = z;
  459. this._w = w;
  460. this.onChangeCallback();
  461. return this;
  462. },
  463. copy: function ( quaternion ) {
  464. this._x = quaternion.x;
  465. this._y = quaternion.y;
  466. this._z = quaternion.z;
  467. this._w = quaternion.w;
  468. this.onChangeCallback();
  469. return this;
  470. },
  471. setFromEuler: function ( euler, update ) {
  472. if ( euler instanceof THREE.Euler === false ) {
  473. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  474. }
  475. // http://www.mathworks.com/matlabcentral/fileexchange/
  476. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  477. // content/SpinCalc.m
  478. var c1 = Math.cos( euler._x / 2 );
  479. var c2 = Math.cos( euler._y / 2 );
  480. var c3 = Math.cos( euler._z / 2 );
  481. var s1 = Math.sin( euler._x / 2 );
  482. var s2 = Math.sin( euler._y / 2 );
  483. var s3 = Math.sin( euler._z / 2 );
  484. if ( euler.order === 'XYZ' ) {
  485. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  486. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  487. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  488. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  489. } else if ( euler.order === 'YXZ' ) {
  490. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  491. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  492. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  493. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  494. } else if ( euler.order === 'ZXY' ) {
  495. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  496. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  497. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  498. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  499. } else if ( euler.order === 'ZYX' ) {
  500. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  501. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  502. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  503. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  504. } else if ( euler.order === 'YZX' ) {
  505. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  506. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  507. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  508. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  509. } else if ( euler.order === 'XZY' ) {
  510. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  511. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  512. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  513. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  514. }
  515. if ( update !== false ) this.onChangeCallback();
  516. return this;
  517. },
  518. setFromAxisAngle: function ( axis, angle ) {
  519. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  520. // assumes axis is normalized
  521. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  522. this._x = axis.x * s;
  523. this._y = axis.y * s;
  524. this._z = axis.z * s;
  525. this._w = Math.cos( halfAngle );
  526. this.onChangeCallback();
  527. return this;
  528. },
  529. setFromRotationMatrix: function ( m ) {
  530. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  531. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  532. var te = m.elements,
  533. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  534. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  535. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  536. trace = m11 + m22 + m33,
  537. s;
  538. if ( trace > 0 ) {
  539. s = 0.5 / Math.sqrt( trace + 1.0 );
  540. this._w = 0.25 / s;
  541. this._x = ( m32 - m23 ) * s;
  542. this._y = ( m13 - m31 ) * s;
  543. this._z = ( m21 - m12 ) * s;
  544. } else if ( m11 > m22 && m11 > m33 ) {
  545. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  546. this._w = ( m32 - m23 ) / s;
  547. this._x = 0.25 * s;
  548. this._y = ( m12 + m21 ) / s;
  549. this._z = ( m13 + m31 ) / s;
  550. } else if ( m22 > m33 ) {
  551. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  552. this._w = ( m13 - m31 ) / s;
  553. this._x = ( m12 + m21 ) / s;
  554. this._y = 0.25 * s;
  555. this._z = ( m23 + m32 ) / s;
  556. } else {
  557. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  558. this._w = ( m21 - m12 ) / s;
  559. this._x = ( m13 + m31 ) / s;
  560. this._y = ( m23 + m32 ) / s;
  561. this._z = 0.25 * s;
  562. }
  563. this.onChangeCallback();
  564. return this;
  565. },
  566. setFromUnitVectors: function () {
  567. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  568. // assumes direction vectors vFrom and vTo are normalized
  569. var v1, r;
  570. var EPS = 0.000001;
  571. return function ( vFrom, vTo ) {
  572. if ( v1 === undefined ) v1 = new THREE.Vector3();
  573. r = vFrom.dot( vTo ) + 1;
  574. if ( r < EPS ) {
  575. r = 0;
  576. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  577. v1.set( - vFrom.y, vFrom.x, 0 );
  578. } else {
  579. v1.set( 0, - vFrom.z, vFrom.y );
  580. }
  581. } else {
  582. v1.crossVectors( vFrom, vTo );
  583. }
  584. this._x = v1.x;
  585. this._y = v1.y;
  586. this._z = v1.z;
  587. this._w = r;
  588. this.normalize();
  589. return this;
  590. }
  591. }(),
  592. inverse: function () {
  593. this.conjugate().normalize();
  594. return this;
  595. },
  596. conjugate: function () {
  597. this._x *= - 1;
  598. this._y *= - 1;
  599. this._z *= - 1;
  600. this.onChangeCallback();
  601. return this;
  602. },
  603. dot: function ( v ) {
  604. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  605. },
  606. lengthSq: function () {
  607. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  608. },
  609. length: function () {
  610. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  611. },
  612. normalize: function () {
  613. var l = this.length();
  614. if ( l === 0 ) {
  615. this._x = 0;
  616. this._y = 0;
  617. this._z = 0;
  618. this._w = 1;
  619. } else {
  620. l = 1 / l;
  621. this._x = this._x * l;
  622. this._y = this._y * l;
  623. this._z = this._z * l;
  624. this._w = this._w * l;
  625. }
  626. this.onChangeCallback();
  627. return this;
  628. },
  629. multiply: function ( q, p ) {
  630. if ( p !== undefined ) {
  631. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  632. return this.multiplyQuaternions( q, p );
  633. }
  634. return this.multiplyQuaternions( this, q );
  635. },
  636. multiplyQuaternions: function ( a, b ) {
  637. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  638. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  639. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  640. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  641. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  642. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  643. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  644. this.onChangeCallback();
  645. return this;
  646. },
  647. multiplyVector3: function ( vector ) {
  648. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  649. return vector.applyQuaternion( this );
  650. },
  651. slerp: function ( qb, t ) {
  652. if ( t === 0 ) return this;
  653. if ( t === 1 ) return this.copy( qb );
  654. var x = this._x, y = this._y, z = this._z, w = this._w;
  655. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  656. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  657. if ( cosHalfTheta < 0 ) {
  658. this._w = - qb._w;
  659. this._x = - qb._x;
  660. this._y = - qb._y;
  661. this._z = - qb._z;
  662. cosHalfTheta = - cosHalfTheta;
  663. } else {
  664. this.copy( qb );
  665. }
  666. if ( cosHalfTheta >= 1.0 ) {
  667. this._w = w;
  668. this._x = x;
  669. this._y = y;
  670. this._z = z;
  671. return this;
  672. }
  673. var halfTheta = Math.acos( cosHalfTheta );
  674. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  675. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  676. this._w = 0.5 * ( w + this._w );
  677. this._x = 0.5 * ( x + this._x );
  678. this._y = 0.5 * ( y + this._y );
  679. this._z = 0.5 * ( z + this._z );
  680. return this;
  681. }
  682. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  683. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  684. this._w = ( w * ratioA + this._w * ratioB );
  685. this._x = ( x * ratioA + this._x * ratioB );
  686. this._y = ( y * ratioA + this._y * ratioB );
  687. this._z = ( z * ratioA + this._z * ratioB );
  688. this.onChangeCallback();
  689. return this;
  690. },
  691. equals: function ( quaternion ) {
  692. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  693. },
  694. fromArray: function ( array, offset ) {
  695. if ( offset === undefined ) offset = 0;
  696. this._x = array[ offset ];
  697. this._y = array[ offset + 1 ];
  698. this._z = array[ offset + 2 ];
  699. this._w = array[ offset + 3 ];
  700. this.onChangeCallback();
  701. return this;
  702. },
  703. toArray: function ( array, offset ) {
  704. if ( array === undefined ) array = [];
  705. if ( offset === undefined ) offset = 0;
  706. array[ offset ] = this._x;
  707. array[ offset + 1 ] = this._y;
  708. array[ offset + 2 ] = this._z;
  709. array[ offset + 3 ] = this._w;
  710. return array;
  711. },
  712. onChange: function ( callback ) {
  713. this.onChangeCallback = callback;
  714. return this;
  715. },
  716. onChangeCallback: function () {},
  717. clone: function () {
  718. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  719. }
  720. };
  721. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  722. return qm.copy( qa ).slerp( qb, t );
  723. };
  724. // File:src/math/Vector2.js
  725. /**
  726. * @author mrdoob / http://mrdoob.com/
  727. * @author philogb / http://blog.thejit.org/
  728. * @author egraether / http://egraether.com/
  729. * @author zz85 / http://www.lab4games.net/zz85/blog
  730. */
  731. THREE.Vector2 = function ( x, y ) {
  732. this.x = x || 0;
  733. this.y = y || 0;
  734. };
  735. THREE.Vector2.prototype = {
  736. constructor: THREE.Vector2,
  737. set: function ( x, y ) {
  738. this.x = x;
  739. this.y = y;
  740. return this;
  741. },
  742. setX: function ( x ) {
  743. this.x = x;
  744. return this;
  745. },
  746. setY: function ( y ) {
  747. this.y = y;
  748. return this;
  749. },
  750. setComponent: function ( index, value ) {
  751. switch ( index ) {
  752. case 0: this.x = value; break;
  753. case 1: this.y = value; break;
  754. default: throw new Error( 'index is out of range: ' + index );
  755. }
  756. },
  757. getComponent: function ( index ) {
  758. switch ( index ) {
  759. case 0: return this.x;
  760. case 1: return this.y;
  761. default: throw new Error( 'index is out of range: ' + index );
  762. }
  763. },
  764. copy: function ( v ) {
  765. this.x = v.x;
  766. this.y = v.y;
  767. return this;
  768. },
  769. add: function ( v, w ) {
  770. if ( w !== undefined ) {
  771. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  772. return this.addVectors( v, w );
  773. }
  774. this.x += v.x;
  775. this.y += v.y;
  776. return this;
  777. },
  778. addScalar: function ( s ) {
  779. this.x += s;
  780. this.y += s;
  781. return this;
  782. },
  783. addVectors: function ( a, b ) {
  784. this.x = a.x + b.x;
  785. this.y = a.y + b.y;
  786. return this;
  787. },
  788. sub: function ( v, w ) {
  789. if ( w !== undefined ) {
  790. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  791. return this.subVectors( v, w );
  792. }
  793. this.x -= v.x;
  794. this.y -= v.y;
  795. return this;
  796. },
  797. subScalar: function ( s ) {
  798. this.x -= s;
  799. this.y -= s;
  800. return this;
  801. },
  802. subVectors: function ( a, b ) {
  803. this.x = a.x - b.x;
  804. this.y = a.y - b.y;
  805. return this;
  806. },
  807. multiply: function ( v ) {
  808. this.x *= v.x;
  809. this.y *= v.y;
  810. return this;
  811. },
  812. multiplyScalar: function ( s ) {
  813. this.x *= s;
  814. this.y *= s;
  815. return this;
  816. },
  817. divide: function ( v ) {
  818. this.x /= v.x;
  819. this.y /= v.y;
  820. return this;
  821. },
  822. divideScalar: function ( scalar ) {
  823. if ( scalar !== 0 ) {
  824. var invScalar = 1 / scalar;
  825. this.x *= invScalar;
  826. this.y *= invScalar;
  827. } else {
  828. this.x = 0;
  829. this.y = 0;
  830. }
  831. return this;
  832. },
  833. min: function ( v ) {
  834. if ( this.x > v.x ) {
  835. this.x = v.x;
  836. }
  837. if ( this.y > v.y ) {
  838. this.y = v.y;
  839. }
  840. return this;
  841. },
  842. max: function ( v ) {
  843. if ( this.x < v.x ) {
  844. this.x = v.x;
  845. }
  846. if ( this.y < v.y ) {
  847. this.y = v.y;
  848. }
  849. return this;
  850. },
  851. clamp: function ( min, max ) {
  852. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  853. if ( this.x < min.x ) {
  854. this.x = min.x;
  855. } else if ( this.x > max.x ) {
  856. this.x = max.x;
  857. }
  858. if ( this.y < min.y ) {
  859. this.y = min.y;
  860. } else if ( this.y > max.y ) {
  861. this.y = max.y;
  862. }
  863. return this;
  864. },
  865. clampScalar: ( function () {
  866. var min, max;
  867. return function ( minVal, maxVal ) {
  868. if ( min === undefined ) {
  869. min = new THREE.Vector2();
  870. max = new THREE.Vector2();
  871. }
  872. min.set( minVal, minVal );
  873. max.set( maxVal, maxVal );
  874. return this.clamp( min, max );
  875. };
  876. } )(),
  877. floor: function () {
  878. this.x = Math.floor( this.x );
  879. this.y = Math.floor( this.y );
  880. return this;
  881. },
  882. ceil: function () {
  883. this.x = Math.ceil( this.x );
  884. this.y = Math.ceil( this.y );
  885. return this;
  886. },
  887. round: function () {
  888. this.x = Math.round( this.x );
  889. this.y = Math.round( this.y );
  890. return this;
  891. },
  892. roundToZero: function () {
  893. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  894. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  895. return this;
  896. },
  897. negate: function () {
  898. this.x = - this.x;
  899. this.y = - this.y;
  900. return this;
  901. },
  902. dot: function ( v ) {
  903. return this.x * v.x + this.y * v.y;
  904. },
  905. lengthSq: function () {
  906. return this.x * this.x + this.y * this.y;
  907. },
  908. length: function () {
  909. return Math.sqrt( this.x * this.x + this.y * this.y );
  910. },
  911. normalize: function () {
  912. return this.divideScalar( this.length() );
  913. },
  914. distanceTo: function ( v ) {
  915. return Math.sqrt( this.distanceToSquared( v ) );
  916. },
  917. distanceToSquared: function ( v ) {
  918. var dx = this.x - v.x, dy = this.y - v.y;
  919. return dx * dx + dy * dy;
  920. },
  921. setLength: function ( l ) {
  922. var oldLength = this.length();
  923. if ( oldLength !== 0 && l !== oldLength ) {
  924. this.multiplyScalar( l / oldLength );
  925. }
  926. return this;
  927. },
  928. lerp: function ( v, alpha ) {
  929. this.x += ( v.x - this.x ) * alpha;
  930. this.y += ( v.y - this.y ) * alpha;
  931. return this;
  932. },
  933. lerpVectors: function ( v1, v2, alpha ) {
  934. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  935. return this;
  936. },
  937. equals: function ( v ) {
  938. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  939. },
  940. fromArray: function ( array, offset ) {
  941. if ( offset === undefined ) offset = 0;
  942. this.x = array[ offset ];
  943. this.y = array[ offset + 1 ];
  944. return this;
  945. },
  946. toArray: function ( array, offset ) {
  947. if ( array === undefined ) array = [];
  948. if ( offset === undefined ) offset = 0;
  949. array[ offset ] = this.x;
  950. array[ offset + 1 ] = this.y;
  951. return array;
  952. },
  953. fromAttribute: function ( attribute, index, offset ) {
  954. if ( offset === undefined ) offset = 0;
  955. index = index * attribute.itemSize + offset;
  956. this.x = attribute.array[ index ];
  957. this.y = attribute.array[ index + 1 ];
  958. return this;
  959. },
  960. clone: function () {
  961. return new THREE.Vector2( this.x, this.y );
  962. }
  963. };
  964. // File:src/math/Vector3.js
  965. /**
  966. * @author mrdoob / http://mrdoob.com/
  967. * @author *kile / http://kile.stravaganza.org/
  968. * @author philogb / http://blog.thejit.org/
  969. * @author mikael emtinger / http://gomo.se/
  970. * @author egraether / http://egraether.com/
  971. * @author WestLangley / http://github.com/WestLangley
  972. */
  973. THREE.Vector3 = function ( x, y, z ) {
  974. this.x = x || 0;
  975. this.y = y || 0;
  976. this.z = z || 0;
  977. };
  978. THREE.Vector3.prototype = {
  979. constructor: THREE.Vector3,
  980. set: function ( x, y, z ) {
  981. this.x = x;
  982. this.y = y;
  983. this.z = z;
  984. return this;
  985. },
  986. setX: function ( x ) {
  987. this.x = x;
  988. return this;
  989. },
  990. setY: function ( y ) {
  991. this.y = y;
  992. return this;
  993. },
  994. setZ: function ( z ) {
  995. this.z = z;
  996. return this;
  997. },
  998. setComponent: function ( index, value ) {
  999. switch ( index ) {
  1000. case 0: this.x = value; break;
  1001. case 1: this.y = value; break;
  1002. case 2: this.z = value; break;
  1003. default: throw new Error( 'index is out of range: ' + index );
  1004. }
  1005. },
  1006. getComponent: function ( index ) {
  1007. switch ( index ) {
  1008. case 0: return this.x;
  1009. case 1: return this.y;
  1010. case 2: return this.z;
  1011. default: throw new Error( 'index is out of range: ' + index );
  1012. }
  1013. },
  1014. copy: function ( v ) {
  1015. this.x = v.x;
  1016. this.y = v.y;
  1017. this.z = v.z;
  1018. return this;
  1019. },
  1020. add: function ( v, w ) {
  1021. if ( w !== undefined ) {
  1022. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1023. return this.addVectors( v, w );
  1024. }
  1025. this.x += v.x;
  1026. this.y += v.y;
  1027. this.z += v.z;
  1028. return this;
  1029. },
  1030. addScalar: function ( s ) {
  1031. this.x += s;
  1032. this.y += s;
  1033. this.z += s;
  1034. return this;
  1035. },
  1036. addVectors: function ( a, b ) {
  1037. this.x = a.x + b.x;
  1038. this.y = a.y + b.y;
  1039. this.z = a.z + b.z;
  1040. return this;
  1041. },
  1042. sub: function ( v, w ) {
  1043. if ( w !== undefined ) {
  1044. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1045. return this.subVectors( v, w );
  1046. }
  1047. this.x -= v.x;
  1048. this.y -= v.y;
  1049. this.z -= v.z;
  1050. return this;
  1051. },
  1052. subScalar: function ( s ) {
  1053. this.x -= s;
  1054. this.y -= s;
  1055. this.z -= s;
  1056. return this;
  1057. },
  1058. subVectors: function ( a, b ) {
  1059. this.x = a.x - b.x;
  1060. this.y = a.y - b.y;
  1061. this.z = a.z - b.z;
  1062. return this;
  1063. },
  1064. multiply: function ( v, w ) {
  1065. if ( w !== undefined ) {
  1066. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1067. return this.multiplyVectors( v, w );
  1068. }
  1069. this.x *= v.x;
  1070. this.y *= v.y;
  1071. this.z *= v.z;
  1072. return this;
  1073. },
  1074. multiplyScalar: function ( scalar ) {
  1075. this.x *= scalar;
  1076. this.y *= scalar;
  1077. this.z *= scalar;
  1078. return this;
  1079. },
  1080. multiplyVectors: function ( a, b ) {
  1081. this.x = a.x * b.x;
  1082. this.y = a.y * b.y;
  1083. this.z = a.z * b.z;
  1084. return this;
  1085. },
  1086. applyEuler: function () {
  1087. var quaternion;
  1088. return function ( euler ) {
  1089. if ( euler instanceof THREE.Euler === false ) {
  1090. console.error( 'THREE.Vector3: .applyEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  1091. }
  1092. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1093. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1094. return this;
  1095. };
  1096. }(),
  1097. applyAxisAngle: function () {
  1098. var quaternion;
  1099. return function ( axis, angle ) {
  1100. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1101. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1102. return this;
  1103. };
  1104. }(),
  1105. applyMatrix3: function ( m ) {
  1106. var x = this.x;
  1107. var y = this.y;
  1108. var z = this.z;
  1109. var e = m.elements;
  1110. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1111. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1112. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1113. return this;
  1114. },
  1115. applyMatrix4: function ( m ) {
  1116. // input: THREE.Matrix4 affine matrix
  1117. var x = this.x, y = this.y, z = this.z;
  1118. var e = m.elements;
  1119. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1120. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1121. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1122. return this;
  1123. },
  1124. applyProjection: function ( m ) {
  1125. // input: THREE.Matrix4 projection matrix
  1126. var x = this.x, y = this.y, z = this.z;
  1127. var e = m.elements;
  1128. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1129. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1130. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1131. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1132. return this;
  1133. },
  1134. applyQuaternion: function ( q ) {
  1135. var x = this.x;
  1136. var y = this.y;
  1137. var z = this.z;
  1138. var qx = q.x;
  1139. var qy = q.y;
  1140. var qz = q.z;
  1141. var qw = q.w;
  1142. // calculate quat * vector
  1143. var ix = qw * x + qy * z - qz * y;
  1144. var iy = qw * y + qz * x - qx * z;
  1145. var iz = qw * z + qx * y - qy * x;
  1146. var iw = - qx * x - qy * y - qz * z;
  1147. // calculate result * inverse quat
  1148. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1149. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1150. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1151. return this;
  1152. },
  1153. project: function () {
  1154. var matrix;
  1155. return function ( camera ) {
  1156. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1157. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1158. return this.applyProjection( matrix );
  1159. };
  1160. }(),
  1161. unproject: function () {
  1162. var matrix;
  1163. return function ( camera ) {
  1164. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1165. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1166. return this.applyProjection( matrix );
  1167. };
  1168. }(),
  1169. transformDirection: function ( m ) {
  1170. // input: THREE.Matrix4 affine matrix
  1171. // vector interpreted as a direction
  1172. var x = this.x, y = this.y, z = this.z;
  1173. var e = m.elements;
  1174. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1175. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1176. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1177. this.normalize();
  1178. return this;
  1179. },
  1180. divide: function ( v ) {
  1181. this.x /= v.x;
  1182. this.y /= v.y;
  1183. this.z /= v.z;
  1184. return this;
  1185. },
  1186. divideScalar: function ( scalar ) {
  1187. if ( scalar !== 0 ) {
  1188. var invScalar = 1 / scalar;
  1189. this.x *= invScalar;
  1190. this.y *= invScalar;
  1191. this.z *= invScalar;
  1192. } else {
  1193. this.x = 0;
  1194. this.y = 0;
  1195. this.z = 0;
  1196. }
  1197. return this;
  1198. },
  1199. min: function ( v ) {
  1200. if ( this.x > v.x ) {
  1201. this.x = v.x;
  1202. }
  1203. if ( this.y > v.y ) {
  1204. this.y = v.y;
  1205. }
  1206. if ( this.z > v.z ) {
  1207. this.z = v.z;
  1208. }
  1209. return this;
  1210. },
  1211. max: function ( v ) {
  1212. if ( this.x < v.x ) {
  1213. this.x = v.x;
  1214. }
  1215. if ( this.y < v.y ) {
  1216. this.y = v.y;
  1217. }
  1218. if ( this.z < v.z ) {
  1219. this.z = v.z;
  1220. }
  1221. return this;
  1222. },
  1223. clamp: function ( min, max ) {
  1224. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1225. if ( this.x < min.x ) {
  1226. this.x = min.x;
  1227. } else if ( this.x > max.x ) {
  1228. this.x = max.x;
  1229. }
  1230. if ( this.y < min.y ) {
  1231. this.y = min.y;
  1232. } else if ( this.y > max.y ) {
  1233. this.y = max.y;
  1234. }
  1235. if ( this.z < min.z ) {
  1236. this.z = min.z;
  1237. } else if ( this.z > max.z ) {
  1238. this.z = max.z;
  1239. }
  1240. return this;
  1241. },
  1242. clampScalar: ( function () {
  1243. var min, max;
  1244. return function ( minVal, maxVal ) {
  1245. if ( min === undefined ) {
  1246. min = new THREE.Vector3();
  1247. max = new THREE.Vector3();
  1248. }
  1249. min.set( minVal, minVal, minVal );
  1250. max.set( maxVal, maxVal, maxVal );
  1251. return this.clamp( min, max );
  1252. };
  1253. } )(),
  1254. floor: function () {
  1255. this.x = Math.floor( this.x );
  1256. this.y = Math.floor( this.y );
  1257. this.z = Math.floor( this.z );
  1258. return this;
  1259. },
  1260. ceil: function () {
  1261. this.x = Math.ceil( this.x );
  1262. this.y = Math.ceil( this.y );
  1263. this.z = Math.ceil( this.z );
  1264. return this;
  1265. },
  1266. round: function () {
  1267. this.x = Math.round( this.x );
  1268. this.y = Math.round( this.y );
  1269. this.z = Math.round( this.z );
  1270. return this;
  1271. },
  1272. roundToZero: function () {
  1273. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1274. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1275. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1276. return this;
  1277. },
  1278. negate: function () {
  1279. this.x = - this.x;
  1280. this.y = - this.y;
  1281. this.z = - this.z;
  1282. return this;
  1283. },
  1284. dot: function ( v ) {
  1285. return this.x * v.x + this.y * v.y + this.z * v.z;
  1286. },
  1287. lengthSq: function () {
  1288. return this.x * this.x + this.y * this.y + this.z * this.z;
  1289. },
  1290. length: function () {
  1291. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1292. },
  1293. lengthManhattan: function () {
  1294. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1295. },
  1296. normalize: function () {
  1297. return this.divideScalar( this.length() );
  1298. },
  1299. setLength: function ( l ) {
  1300. var oldLength = this.length();
  1301. if ( oldLength !== 0 && l !== oldLength ) {
  1302. this.multiplyScalar( l / oldLength );
  1303. }
  1304. return this;
  1305. },
  1306. lerp: function ( v, alpha ) {
  1307. this.x += ( v.x - this.x ) * alpha;
  1308. this.y += ( v.y - this.y ) * alpha;
  1309. this.z += ( v.z - this.z ) * alpha;
  1310. return this;
  1311. },
  1312. lerpVectors: function ( v1, v2, alpha ) {
  1313. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1314. return this;
  1315. },
  1316. cross: function ( v, w ) {
  1317. if ( w !== undefined ) {
  1318. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1319. return this.crossVectors( v, w );
  1320. }
  1321. var x = this.x, y = this.y, z = this.z;
  1322. this.x = y * v.z - z * v.y;
  1323. this.y = z * v.x - x * v.z;
  1324. this.z = x * v.y - y * v.x;
  1325. return this;
  1326. },
  1327. crossVectors: function ( a, b ) {
  1328. var ax = a.x, ay = a.y, az = a.z;
  1329. var bx = b.x, by = b.y, bz = b.z;
  1330. this.x = ay * bz - az * by;
  1331. this.y = az * bx - ax * bz;
  1332. this.z = ax * by - ay * bx;
  1333. return this;
  1334. },
  1335. projectOnVector: function () {
  1336. var v1, dot;
  1337. return function ( vector ) {
  1338. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1339. v1.copy( vector ).normalize();
  1340. dot = this.dot( v1 );
  1341. return this.copy( v1 ).multiplyScalar( dot );
  1342. };
  1343. }(),
  1344. projectOnPlane: function () {
  1345. var v1;
  1346. return function ( planeNormal ) {
  1347. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1348. v1.copy( this ).projectOnVector( planeNormal );
  1349. return this.sub( v1 );
  1350. }
  1351. }(),
  1352. reflect: function () {
  1353. // reflect incident vector off plane orthogonal to normal
  1354. // normal is assumed to have unit length
  1355. var v1;
  1356. return function ( normal ) {
  1357. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1358. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1359. }
  1360. }(),
  1361. angleTo: function ( v ) {
  1362. var theta = this.dot( v ) / ( this.length() * v.length() );
  1363. // clamp, to handle numerical problems
  1364. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1365. },
  1366. distanceTo: function ( v ) {
  1367. return Math.sqrt( this.distanceToSquared( v ) );
  1368. },
  1369. distanceToSquared: function ( v ) {
  1370. var dx = this.x - v.x;
  1371. var dy = this.y - v.y;
  1372. var dz = this.z - v.z;
  1373. return dx * dx + dy * dy + dz * dz;
  1374. },
  1375. setEulerFromRotationMatrix: function ( m, order ) {
  1376. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  1377. },
  1378. setEulerFromQuaternion: function ( q, order ) {
  1379. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  1380. },
  1381. getPositionFromMatrix: function ( m ) {
  1382. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  1383. return this.setFromMatrixPosition( m );
  1384. },
  1385. getScaleFromMatrix: function ( m ) {
  1386. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  1387. return this.setFromMatrixScale( m );
  1388. },
  1389. getColumnFromMatrix: function ( index, matrix ) {
  1390. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  1391. return this.setFromMatrixColumn( index, matrix );
  1392. },
  1393. setFromMatrixPosition: function ( m ) {
  1394. this.x = m.elements[ 12 ];
  1395. this.y = m.elements[ 13 ];
  1396. this.z = m.elements[ 14 ];
  1397. return this;
  1398. },
  1399. setFromMatrixScale: function ( m ) {
  1400. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1401. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1402. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1403. this.x = sx;
  1404. this.y = sy;
  1405. this.z = sz;
  1406. return this;
  1407. },
  1408. setFromMatrixColumn: function ( index, matrix ) {
  1409. var offset = index * 4;
  1410. var me = matrix.elements;
  1411. this.x = me[ offset ];
  1412. this.y = me[ offset + 1 ];
  1413. this.z = me[ offset + 2 ];
  1414. return this;
  1415. },
  1416. equals: function ( v ) {
  1417. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1418. },
  1419. fromArray: function ( array, offset ) {
  1420. if ( offset === undefined ) offset = 0;
  1421. this.x = array[ offset ];
  1422. this.y = array[ offset + 1 ];
  1423. this.z = array[ offset + 2 ];
  1424. return this;
  1425. },
  1426. toArray: function ( array, offset ) {
  1427. if ( array === undefined ) array = [];
  1428. if ( offset === undefined ) offset = 0;
  1429. array[ offset ] = this.x;
  1430. array[ offset + 1 ] = this.y;
  1431. array[ offset + 2 ] = this.z;
  1432. return array;
  1433. },
  1434. fromAttribute: function ( attribute, index, offset ) {
  1435. if ( offset === undefined ) offset = 0;
  1436. index = index * attribute.itemSize + offset;
  1437. this.x = attribute.array[ index ];
  1438. this.y = attribute.array[ index + 1 ];
  1439. this.z = attribute.array[ index + 2 ];
  1440. return this;
  1441. },
  1442. clone: function () {
  1443. return new THREE.Vector3( this.x, this.y, this.z );
  1444. }
  1445. };
  1446. // File:src/math/Vector4.js
  1447. /**
  1448. * @author supereggbert / http://www.paulbrunt.co.uk/
  1449. * @author philogb / http://blog.thejit.org/
  1450. * @author mikael emtinger / http://gomo.se/
  1451. * @author egraether / http://egraether.com/
  1452. * @author WestLangley / http://github.com/WestLangley
  1453. */
  1454. THREE.Vector4 = function ( x, y, z, w ) {
  1455. this.x = x || 0;
  1456. this.y = y || 0;
  1457. this.z = z || 0;
  1458. this.w = ( w !== undefined ) ? w : 1;
  1459. };
  1460. THREE.Vector4.prototype = {
  1461. constructor: THREE.Vector4,
  1462. set: function ( x, y, z, w ) {
  1463. this.x = x;
  1464. this.y = y;
  1465. this.z = z;
  1466. this.w = w;
  1467. return this;
  1468. },
  1469. setX: function ( x ) {
  1470. this.x = x;
  1471. return this;
  1472. },
  1473. setY: function ( y ) {
  1474. this.y = y;
  1475. return this;
  1476. },
  1477. setZ: function ( z ) {
  1478. this.z = z;
  1479. return this;
  1480. },
  1481. setW: function ( w ) {
  1482. this.w = w;
  1483. return this;
  1484. },
  1485. setComponent: function ( index, value ) {
  1486. switch ( index ) {
  1487. case 0: this.x = value; break;
  1488. case 1: this.y = value; break;
  1489. case 2: this.z = value; break;
  1490. case 3: this.w = value; break;
  1491. default: throw new Error( 'index is out of range: ' + index );
  1492. }
  1493. },
  1494. getComponent: function ( index ) {
  1495. switch ( index ) {
  1496. case 0: return this.x;
  1497. case 1: return this.y;
  1498. case 2: return this.z;
  1499. case 3: return this.w;
  1500. default: throw new Error( 'index is out of range: ' + index );
  1501. }
  1502. },
  1503. copy: function ( v ) {
  1504. this.x = v.x;
  1505. this.y = v.y;
  1506. this.z = v.z;
  1507. this.w = ( v.w !== undefined ) ? v.w : 1;
  1508. return this;
  1509. },
  1510. add: function ( v, w ) {
  1511. if ( w !== undefined ) {
  1512. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1513. return this.addVectors( v, w );
  1514. }
  1515. this.x += v.x;
  1516. this.y += v.y;
  1517. this.z += v.z;
  1518. this.w += v.w;
  1519. return this;
  1520. },
  1521. addScalar: function ( s ) {
  1522. this.x += s;
  1523. this.y += s;
  1524. this.z += s;
  1525. this.w += s;
  1526. return this;
  1527. },
  1528. addVectors: function ( a, b ) {
  1529. this.x = a.x + b.x;
  1530. this.y = a.y + b.y;
  1531. this.z = a.z + b.z;
  1532. this.w = a.w + b.w;
  1533. return this;
  1534. },
  1535. sub: function ( v, w ) {
  1536. if ( w !== undefined ) {
  1537. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1538. return this.subVectors( v, w );
  1539. }
  1540. this.x -= v.x;
  1541. this.y -= v.y;
  1542. this.z -= v.z;
  1543. this.w -= v.w;
  1544. return this;
  1545. },
  1546. subScalar: function ( s ) {
  1547. this.x -= s;
  1548. this.y -= s;
  1549. this.z -= s;
  1550. this.w -= s;
  1551. return this;
  1552. },
  1553. subVectors: function ( a, b ) {
  1554. this.x = a.x - b.x;
  1555. this.y = a.y - b.y;
  1556. this.z = a.z - b.z;
  1557. this.w = a.w - b.w;
  1558. return this;
  1559. },
  1560. multiplyScalar: function ( scalar ) {
  1561. this.x *= scalar;
  1562. this.y *= scalar;
  1563. this.z *= scalar;
  1564. this.w *= scalar;
  1565. return this;
  1566. },
  1567. applyMatrix4: function ( m ) {
  1568. var x = this.x;
  1569. var y = this.y;
  1570. var z = this.z;
  1571. var w = this.w;
  1572. var e = m.elements;
  1573. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1574. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1575. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1576. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1577. return this;
  1578. },
  1579. divideScalar: function ( scalar ) {
  1580. if ( scalar !== 0 ) {
  1581. var invScalar = 1 / scalar;
  1582. this.x *= invScalar;
  1583. this.y *= invScalar;
  1584. this.z *= invScalar;
  1585. this.w *= invScalar;
  1586. } else {
  1587. this.x = 0;
  1588. this.y = 0;
  1589. this.z = 0;
  1590. this.w = 1;
  1591. }
  1592. return this;
  1593. },
  1594. setAxisAngleFromQuaternion: function ( q ) {
  1595. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1596. // q is assumed to be normalized
  1597. this.w = 2 * Math.acos( q.w );
  1598. var s = Math.sqrt( 1 - q.w * q.w );
  1599. if ( s < 0.0001 ) {
  1600. this.x = 1;
  1601. this.y = 0;
  1602. this.z = 0;
  1603. } else {
  1604. this.x = q.x / s;
  1605. this.y = q.y / s;
  1606. this.z = q.z / s;
  1607. }
  1608. return this;
  1609. },
  1610. setAxisAngleFromRotationMatrix: function ( m ) {
  1611. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1612. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1613. var angle, x, y, z, // variables for result
  1614. epsilon = 0.01, // margin to allow for rounding errors
  1615. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1616. te = m.elements,
  1617. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1618. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1619. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1620. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1621. && ( Math.abs( m13 - m31 ) < epsilon )
  1622. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1623. // singularity found
  1624. // first check for identity matrix which must have +1 for all terms
  1625. // in leading diagonal and zero in other terms
  1626. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1627. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1628. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1629. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1630. // this singularity is identity matrix so angle = 0
  1631. this.set( 1, 0, 0, 0 );
  1632. return this; // zero angle, arbitrary axis
  1633. }
  1634. // otherwise this singularity is angle = 180
  1635. angle = Math.PI;
  1636. var xx = ( m11 + 1 ) / 2;
  1637. var yy = ( m22 + 1 ) / 2;
  1638. var zz = ( m33 + 1 ) / 2;
  1639. var xy = ( m12 + m21 ) / 4;
  1640. var xz = ( m13 + m31 ) / 4;
  1641. var yz = ( m23 + m32 ) / 4;
  1642. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1643. if ( xx < epsilon ) {
  1644. x = 0;
  1645. y = 0.707106781;
  1646. z = 0.707106781;
  1647. } else {
  1648. x = Math.sqrt( xx );
  1649. y = xy / x;
  1650. z = xz / x;
  1651. }
  1652. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1653. if ( yy < epsilon ) {
  1654. x = 0.707106781;
  1655. y = 0;
  1656. z = 0.707106781;
  1657. } else {
  1658. y = Math.sqrt( yy );
  1659. x = xy / y;
  1660. z = yz / y;
  1661. }
  1662. } else { // m33 is the largest diagonal term so base result on this
  1663. if ( zz < epsilon ) {
  1664. x = 0.707106781;
  1665. y = 0.707106781;
  1666. z = 0;
  1667. } else {
  1668. z = Math.sqrt( zz );
  1669. x = xz / z;
  1670. y = yz / z;
  1671. }
  1672. }
  1673. this.set( x, y, z, angle );
  1674. return this; // return 180 deg rotation
  1675. }
  1676. // as we have reached here there are no singularities so we can handle normally
  1677. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1678. + ( m13 - m31 ) * ( m13 - m31 )
  1679. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1680. if ( Math.abs( s ) < 0.001 ) s = 1;
  1681. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1682. // caught by singularity test above, but I've left it in just in case
  1683. this.x = ( m32 - m23 ) / s;
  1684. this.y = ( m13 - m31 ) / s;
  1685. this.z = ( m21 - m12 ) / s;
  1686. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1687. return this;
  1688. },
  1689. min: function ( v ) {
  1690. if ( this.x > v.x ) {
  1691. this.x = v.x;
  1692. }
  1693. if ( this.y > v.y ) {
  1694. this.y = v.y;
  1695. }
  1696. if ( this.z > v.z ) {
  1697. this.z = v.z;
  1698. }
  1699. if ( this.w > v.w ) {
  1700. this.w = v.w;
  1701. }
  1702. return this;
  1703. },
  1704. max: function ( v ) {
  1705. if ( this.x < v.x ) {
  1706. this.x = v.x;
  1707. }
  1708. if ( this.y < v.y ) {
  1709. this.y = v.y;
  1710. }
  1711. if ( this.z < v.z ) {
  1712. this.z = v.z;
  1713. }
  1714. if ( this.w < v.w ) {
  1715. this.w = v.w;
  1716. }
  1717. return this;
  1718. },
  1719. clamp: function ( min, max ) {
  1720. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1721. if ( this.x < min.x ) {
  1722. this.x = min.x;
  1723. } else if ( this.x > max.x ) {
  1724. this.x = max.x;
  1725. }
  1726. if ( this.y < min.y ) {
  1727. this.y = min.y;
  1728. } else if ( this.y > max.y ) {
  1729. this.y = max.y;
  1730. }
  1731. if ( this.z < min.z ) {
  1732. this.z = min.z;
  1733. } else if ( this.z > max.z ) {
  1734. this.z = max.z;
  1735. }
  1736. if ( this.w < min.w ) {
  1737. this.w = min.w;
  1738. } else if ( this.w > max.w ) {
  1739. this.w = max.w;
  1740. }
  1741. return this;
  1742. },
  1743. clampScalar: ( function () {
  1744. var min, max;
  1745. return function ( minVal, maxVal ) {
  1746. if ( min === undefined ) {
  1747. min = new THREE.Vector4();
  1748. max = new THREE.Vector4();
  1749. }
  1750. min.set( minVal, minVal, minVal, minVal );
  1751. max.set( maxVal, maxVal, maxVal, maxVal );
  1752. return this.clamp( min, max );
  1753. };
  1754. } )(),
  1755. floor: function () {
  1756. this.x = Math.floor( this.x );
  1757. this.y = Math.floor( this.y );
  1758. this.z = Math.floor( this.z );
  1759. this.w = Math.floor( this.w );
  1760. return this;
  1761. },
  1762. ceil: function () {
  1763. this.x = Math.ceil( this.x );
  1764. this.y = Math.ceil( this.y );
  1765. this.z = Math.ceil( this.z );
  1766. this.w = Math.ceil( this.w );
  1767. return this;
  1768. },
  1769. round: function () {
  1770. this.x = Math.round( this.x );
  1771. this.y = Math.round( this.y );
  1772. this.z = Math.round( this.z );
  1773. this.w = Math.round( this.w );
  1774. return this;
  1775. },
  1776. roundToZero: function () {
  1777. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1778. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1779. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1780. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1781. return this;
  1782. },
  1783. negate: function () {
  1784. this.x = - this.x;
  1785. this.y = - this.y;
  1786. this.z = - this.z;
  1787. this.w = - this.w;
  1788. return this;
  1789. },
  1790. dot: function ( v ) {
  1791. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1792. },
  1793. lengthSq: function () {
  1794. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1795. },
  1796. length: function () {
  1797. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1798. },
  1799. lengthManhattan: function () {
  1800. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1801. },
  1802. normalize: function () {
  1803. return this.divideScalar( this.length() );
  1804. },
  1805. setLength: function ( l ) {
  1806. var oldLength = this.length();
  1807. if ( oldLength !== 0 && l !== oldLength ) {
  1808. this.multiplyScalar( l / oldLength );
  1809. }
  1810. return this;
  1811. },
  1812. lerp: function ( v, alpha ) {
  1813. this.x += ( v.x - this.x ) * alpha;
  1814. this.y += ( v.y - this.y ) * alpha;
  1815. this.z += ( v.z - this.z ) * alpha;
  1816. this.w += ( v.w - this.w ) * alpha;
  1817. return this;
  1818. },
  1819. lerpVectors: function ( v1, v2, alpha ) {
  1820. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1821. return this;
  1822. },
  1823. equals: function ( v ) {
  1824. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1825. },
  1826. fromArray: function ( array, offset ) {
  1827. if ( offset === undefined ) offset = 0;
  1828. this.x = array[ offset ];
  1829. this.y = array[ offset + 1 ];
  1830. this.z = array[ offset + 2 ];
  1831. this.w = array[ offset + 3 ];
  1832. return this;
  1833. },
  1834. toArray: function ( array, offset ) {
  1835. if ( array === undefined ) array = [];
  1836. if ( offset === undefined ) offset = 0;
  1837. array[ offset ] = this.x;
  1838. array[ offset + 1 ] = this.y;
  1839. array[ offset + 2 ] = this.z;
  1840. array[ offset + 3 ] = this.w;
  1841. return array;
  1842. },
  1843. fromAttribute: function ( attribute, index, offset ) {
  1844. if ( offset === undefined ) offset = 0;
  1845. index = index * attribute.itemSize + offset;
  1846. this.x = attribute.array[ index ];
  1847. this.y = attribute.array[ index + 1 ];
  1848. this.z = attribute.array[ index + 2 ];
  1849. this.w = attribute.array[ index + 3 ];
  1850. return this;
  1851. },
  1852. clone: function () {
  1853. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1854. }
  1855. };
  1856. // File:src/math/Euler.js
  1857. /**
  1858. * @author mrdoob / http://mrdoob.com/
  1859. * @author WestLangley / http://github.com/WestLangley
  1860. * @author bhouston / http://exocortex.com
  1861. */
  1862. THREE.Euler = function ( x, y, z, order ) {
  1863. this._x = x || 0;
  1864. this._y = y || 0;
  1865. this._z = z || 0;
  1866. this._order = order || THREE.Euler.DefaultOrder;
  1867. };
  1868. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1869. THREE.Euler.DefaultOrder = 'XYZ';
  1870. THREE.Euler.prototype = {
  1871. constructor: THREE.Euler,
  1872. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1873. get x () {
  1874. return this._x;
  1875. },
  1876. set x ( value ) {
  1877. this._x = value;
  1878. this.onChangeCallback();
  1879. },
  1880. get y () {
  1881. return this._y;
  1882. },
  1883. set y ( value ) {
  1884. this._y = value;
  1885. this.onChangeCallback();
  1886. },
  1887. get z () {
  1888. return this._z;
  1889. },
  1890. set z ( value ) {
  1891. this._z = value;
  1892. this.onChangeCallback();
  1893. },
  1894. get order () {
  1895. return this._order;
  1896. },
  1897. set order ( value ) {
  1898. this._order = value;
  1899. this.onChangeCallback();
  1900. },
  1901. set: function ( x, y, z, order ) {
  1902. this._x = x;
  1903. this._y = y;
  1904. this._z = z;
  1905. this._order = order || this._order;
  1906. this.onChangeCallback();
  1907. return this;
  1908. },
  1909. copy: function ( euler ) {
  1910. this._x = euler._x;
  1911. this._y = euler._y;
  1912. this._z = euler._z;
  1913. this._order = euler._order;
  1914. this.onChangeCallback();
  1915. return this;
  1916. },
  1917. setFromRotationMatrix: function ( m, order, update ) {
  1918. var clamp = THREE.Math.clamp;
  1919. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1920. var te = m.elements;
  1921. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  1922. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  1923. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1924. order = order || this._order;
  1925. if ( order === 'XYZ' ) {
  1926. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  1927. if ( Math.abs( m13 ) < 0.99999 ) {
  1928. this._x = Math.atan2( - m23, m33 );
  1929. this._z = Math.atan2( - m12, m11 );
  1930. } else {
  1931. this._x = Math.atan2( m32, m22 );
  1932. this._z = 0;
  1933. }
  1934. } else if ( order === 'YXZ' ) {
  1935. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  1936. if ( Math.abs( m23 ) < 0.99999 ) {
  1937. this._y = Math.atan2( m13, m33 );
  1938. this._z = Math.atan2( m21, m22 );
  1939. } else {
  1940. this._y = Math.atan2( - m31, m11 );
  1941. this._z = 0;
  1942. }
  1943. } else if ( order === 'ZXY' ) {
  1944. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  1945. if ( Math.abs( m32 ) < 0.99999 ) {
  1946. this._y = Math.atan2( - m31, m33 );
  1947. this._z = Math.atan2( - m12, m22 );
  1948. } else {
  1949. this._y = 0;
  1950. this._z = Math.atan2( m21, m11 );
  1951. }
  1952. } else if ( order === 'ZYX' ) {
  1953. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  1954. if ( Math.abs( m31 ) < 0.99999 ) {
  1955. this._x = Math.atan2( m32, m33 );
  1956. this._z = Math.atan2( m21, m11 );
  1957. } else {
  1958. this._x = 0;
  1959. this._z = Math.atan2( - m12, m22 );
  1960. }
  1961. } else if ( order === 'YZX' ) {
  1962. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  1963. if ( Math.abs( m21 ) < 0.99999 ) {
  1964. this._x = Math.atan2( - m23, m22 );
  1965. this._y = Math.atan2( - m31, m11 );
  1966. } else {
  1967. this._x = 0;
  1968. this._y = Math.atan2( m13, m33 );
  1969. }
  1970. } else if ( order === 'XZY' ) {
  1971. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  1972. if ( Math.abs( m12 ) < 0.99999 ) {
  1973. this._x = Math.atan2( m32, m22 );
  1974. this._y = Math.atan2( m13, m11 );
  1975. } else {
  1976. this._x = Math.atan2( - m23, m33 );
  1977. this._y = 0;
  1978. }
  1979. } else {
  1980. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order )
  1981. }
  1982. this._order = order;
  1983. if ( update !== false ) this.onChangeCallback();
  1984. return this;
  1985. },
  1986. setFromQuaternion: function () {
  1987. var matrix;
  1988. return function ( q, order, update ) {
  1989. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1990. matrix.makeRotationFromQuaternion( q );
  1991. this.setFromRotationMatrix( matrix, order, update );
  1992. return this;
  1993. };
  1994. }(),
  1995. setFromVector3: function ( v, order ) {
  1996. return this.set( v.x, v.y, v.z, order || this._order );
  1997. },
  1998. reorder: function () {
  1999. // WARNING: this discards revolution information -bhouston
  2000. var q = new THREE.Quaternion();
  2001. return function ( newOrder ) {
  2002. q.setFromEuler( this );
  2003. this.setFromQuaternion( q, newOrder );
  2004. };
  2005. }(),
  2006. equals: function ( euler ) {
  2007. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2008. },
  2009. fromArray: function ( array ) {
  2010. this._x = array[ 0 ];
  2011. this._y = array[ 1 ];
  2012. this._z = array[ 2 ];
  2013. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2014. this.onChangeCallback();
  2015. return this;
  2016. },
  2017. toArray: function ( array, offset ) {
  2018. if ( array === undefined ) array = [];
  2019. if ( offset === undefined ) offset = 0;
  2020. array[ offset ] = this._x;
  2021. array[ offset + 1 ] = this._y;
  2022. array[ offset + 2 ] = this._z;
  2023. array[ offset + 3 ] = this._order;
  2024. return array;
  2025. },
  2026. toVector3: function ( optionalResult ) {
  2027. if ( optionalResult ) {
  2028. return optionalResult.set( this._x, this._y, this._z );
  2029. } else {
  2030. return new THREE.Vector3( this._x, this._y, this._z );
  2031. }
  2032. },
  2033. onChange: function ( callback ) {
  2034. this.onChangeCallback = callback;
  2035. return this;
  2036. },
  2037. onChangeCallback: function () {},
  2038. clone: function () {
  2039. return new THREE.Euler( this._x, this._y, this._z, this._order );
  2040. }
  2041. };
  2042. // File:src/math/Line3.js
  2043. /**
  2044. * @author bhouston / http://exocortex.com
  2045. */
  2046. THREE.Line3 = function ( start, end ) {
  2047. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2048. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2049. };
  2050. THREE.Line3.prototype = {
  2051. constructor: THREE.Line3,
  2052. set: function ( start, end ) {
  2053. this.start.copy( start );
  2054. this.end.copy( end );
  2055. return this;
  2056. },
  2057. copy: function ( line ) {
  2058. this.start.copy( line.start );
  2059. this.end.copy( line.end );
  2060. return this;
  2061. },
  2062. center: function ( optionalTarget ) {
  2063. var result = optionalTarget || new THREE.Vector3();
  2064. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2065. },
  2066. delta: function ( optionalTarget ) {
  2067. var result = optionalTarget || new THREE.Vector3();
  2068. return result.subVectors( this.end, this.start );
  2069. },
  2070. distanceSq: function () {
  2071. return this.start.distanceToSquared( this.end );
  2072. },
  2073. distance: function () {
  2074. return this.start.distanceTo( this.end );
  2075. },
  2076. at: function ( t, optionalTarget ) {
  2077. var result = optionalTarget || new THREE.Vector3();
  2078. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2079. },
  2080. closestPointToPointParameter: function () {
  2081. var startP = new THREE.Vector3();
  2082. var startEnd = new THREE.Vector3();
  2083. return function ( point, clampToLine ) {
  2084. startP.subVectors( point, this.start );
  2085. startEnd.subVectors( this.end, this.start );
  2086. var startEnd2 = startEnd.dot( startEnd );
  2087. var startEnd_startP = startEnd.dot( startP );
  2088. var t = startEnd_startP / startEnd2;
  2089. if ( clampToLine ) {
  2090. t = THREE.Math.clamp( t, 0, 1 );
  2091. }
  2092. return t;
  2093. };
  2094. }(),
  2095. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2096. var t = this.closestPointToPointParameter( point, clampToLine );
  2097. var result = optionalTarget || new THREE.Vector3();
  2098. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2099. },
  2100. applyMatrix4: function ( matrix ) {
  2101. this.start.applyMatrix4( matrix );
  2102. this.end.applyMatrix4( matrix );
  2103. return this;
  2104. },
  2105. equals: function ( line ) {
  2106. return line.start.equals( this.start ) && line.end.equals( this.end );
  2107. },
  2108. clone: function () {
  2109. return new THREE.Line3().copy( this );
  2110. }
  2111. };
  2112. // File:src/math/Box2.js
  2113. /**
  2114. * @author bhouston / http://exocortex.com
  2115. */
  2116. THREE.Box2 = function ( min, max ) {
  2117. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  2118. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2119. };
  2120. THREE.Box2.prototype = {
  2121. constructor: THREE.Box2,
  2122. set: function ( min, max ) {
  2123. this.min.copy( min );
  2124. this.max.copy( max );
  2125. return this;
  2126. },
  2127. setFromPoints: function ( points ) {
  2128. this.makeEmpty();
  2129. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2130. this.expandByPoint( points[ i ] )
  2131. }
  2132. return this;
  2133. },
  2134. setFromCenterAndSize: function () {
  2135. var v1 = new THREE.Vector2();
  2136. return function ( center, size ) {
  2137. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2138. this.min.copy( center ).sub( halfSize );
  2139. this.max.copy( center ).add( halfSize );
  2140. return this;
  2141. };
  2142. }(),
  2143. copy: function ( box ) {
  2144. this.min.copy( box.min );
  2145. this.max.copy( box.max );
  2146. return this;
  2147. },
  2148. makeEmpty: function () {
  2149. this.min.x = this.min.y = Infinity;
  2150. this.max.x = this.max.y = - Infinity;
  2151. return this;
  2152. },
  2153. empty: function () {
  2154. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2155. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2156. },
  2157. center: function ( optionalTarget ) {
  2158. var result = optionalTarget || new THREE.Vector2();
  2159. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2160. },
  2161. size: function ( optionalTarget ) {
  2162. var result = optionalTarget || new THREE.Vector2();
  2163. return result.subVectors( this.max, this.min );
  2164. },
  2165. expandByPoint: function ( point ) {
  2166. this.min.min( point );
  2167. this.max.max( point );
  2168. return this;
  2169. },
  2170. expandByVector: function ( vector ) {
  2171. this.min.sub( vector );
  2172. this.max.add( vector );
  2173. return this;
  2174. },
  2175. expandByScalar: function ( scalar ) {
  2176. this.min.addScalar( - scalar );
  2177. this.max.addScalar( scalar );
  2178. return this;
  2179. },
  2180. containsPoint: function ( point ) {
  2181. if ( point.x < this.min.x || point.x > this.max.x ||
  2182. point.y < this.min.y || point.y > this.max.y ) {
  2183. return false;
  2184. }
  2185. return true;
  2186. },
  2187. containsBox: function ( box ) {
  2188. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2189. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2190. return true;
  2191. }
  2192. return false;
  2193. },
  2194. getParameter: function ( point, optionalTarget ) {
  2195. // This can potentially have a divide by zero if the box
  2196. // has a size dimension of 0.
  2197. var result = optionalTarget || new THREE.Vector2();
  2198. return result.set(
  2199. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2200. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2201. );
  2202. },
  2203. isIntersectionBox: function ( box ) {
  2204. // using 6 splitting planes to rule out intersections.
  2205. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2206. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2207. return false;
  2208. }
  2209. return true;
  2210. },
  2211. clampPoint: function ( point, optionalTarget ) {
  2212. var result = optionalTarget || new THREE.Vector2();
  2213. return result.copy( point ).clamp( this.min, this.max );
  2214. },
  2215. distanceToPoint: function () {
  2216. var v1 = new THREE.Vector2();
  2217. return function ( point ) {
  2218. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2219. return clampedPoint.sub( point ).length();
  2220. };
  2221. }(),
  2222. intersect: function ( box ) {
  2223. this.min.max( box.min );
  2224. this.max.min( box.max );
  2225. return this;
  2226. },
  2227. union: function ( box ) {
  2228. this.min.min( box.min );
  2229. this.max.max( box.max );
  2230. return this;
  2231. },
  2232. translate: function ( offset ) {
  2233. this.min.add( offset );
  2234. this.max.add( offset );
  2235. return this;
  2236. },
  2237. equals: function ( box ) {
  2238. return box.min.equals( this.min ) && box.max.equals( this.max );
  2239. },
  2240. clone: function () {
  2241. return new THREE.Box2().copy( this );
  2242. }
  2243. };
  2244. // File:src/math/Box3.js
  2245. /**
  2246. * @author bhouston / http://exocortex.com
  2247. * @author WestLangley / http://github.com/WestLangley
  2248. */
  2249. THREE.Box3 = function ( min, max ) {
  2250. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2251. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2252. };
  2253. THREE.Box3.prototype = {
  2254. constructor: THREE.Box3,
  2255. set: function ( min, max ) {
  2256. this.min.copy( min );
  2257. this.max.copy( max );
  2258. return this;
  2259. },
  2260. setFromPoints: function ( points ) {
  2261. this.makeEmpty();
  2262. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2263. this.expandByPoint( points[ i ] );
  2264. }
  2265. return this;
  2266. },
  2267. setFromCenterAndSize: function () {
  2268. var v1 = new THREE.Vector3();
  2269. return function ( center, size ) {
  2270. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2271. this.min.copy( center ).sub( halfSize );
  2272. this.max.copy( center ).add( halfSize );
  2273. return this;
  2274. };
  2275. }(),
  2276. setFromObject: function () {
  2277. // Computes the world-axis-aligned bounding box of an object (including its children),
  2278. // accounting for both the object's, and children's, world transforms
  2279. var v1 = new THREE.Vector3();
  2280. return function ( object ) {
  2281. var scope = this;
  2282. object.updateMatrixWorld( true );
  2283. this.makeEmpty();
  2284. object.traverse( function ( node ) {
  2285. var geometry = node.geometry;
  2286. if ( geometry !== undefined ) {
  2287. if ( geometry instanceof THREE.Geometry ) {
  2288. var vertices = geometry.vertices;
  2289. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2290. v1.copy( vertices[ i ] );
  2291. v1.applyMatrix4( node.matrixWorld );
  2292. scope.expandByPoint( v1 );
  2293. }
  2294. } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) {
  2295. var positions = geometry.attributes[ 'position' ].array;
  2296. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  2297. v1.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  2298. v1.applyMatrix4( node.matrixWorld );
  2299. scope.expandByPoint( v1 );
  2300. }
  2301. }
  2302. }
  2303. } );
  2304. return this;
  2305. };
  2306. }(),
  2307. copy: function ( box ) {
  2308. this.min.copy( box.min );
  2309. this.max.copy( box.max );
  2310. return this;
  2311. },
  2312. makeEmpty: function () {
  2313. this.min.x = this.min.y = this.min.z = Infinity;
  2314. this.max.x = this.max.y = this.max.z = - Infinity;
  2315. return this;
  2316. },
  2317. empty: function () {
  2318. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2319. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2320. },
  2321. center: function ( optionalTarget ) {
  2322. var result = optionalTarget || new THREE.Vector3();
  2323. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2324. },
  2325. size: function ( optionalTarget ) {
  2326. var result = optionalTarget || new THREE.Vector3();
  2327. return result.subVectors( this.max, this.min );
  2328. },
  2329. expandByPoint: function ( point ) {
  2330. this.min.min( point );
  2331. this.max.max( point );
  2332. return this;
  2333. },
  2334. expandByVector: function ( vector ) {
  2335. this.min.sub( vector );
  2336. this.max.add( vector );
  2337. return this;
  2338. },
  2339. expandByScalar: function ( scalar ) {
  2340. this.min.addScalar( - scalar );
  2341. this.max.addScalar( scalar );
  2342. return this;
  2343. },
  2344. containsPoint: function ( point ) {
  2345. if ( point.x < this.min.x || point.x > this.max.x ||
  2346. point.y < this.min.y || point.y > this.max.y ||
  2347. point.z < this.min.z || point.z > this.max.z ) {
  2348. return false;
  2349. }
  2350. return true;
  2351. },
  2352. containsBox: function ( box ) {
  2353. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2354. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2355. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2356. return true;
  2357. }
  2358. return false;
  2359. },
  2360. getParameter: function ( point, optionalTarget ) {
  2361. // This can potentially have a divide by zero if the box
  2362. // has a size dimension of 0.
  2363. var result = optionalTarget || new THREE.Vector3();
  2364. return result.set(
  2365. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2366. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2367. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2368. );
  2369. },
  2370. isIntersectionBox: function ( box ) {
  2371. // using 6 splitting planes to rule out intersections.
  2372. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2373. box.max.y < this.min.y || box.min.y > this.max.y ||
  2374. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2375. return false;
  2376. }
  2377. return true;
  2378. },
  2379. clampPoint: function ( point, optionalTarget ) {
  2380. var result = optionalTarget || new THREE.Vector3();
  2381. return result.copy( point ).clamp( this.min, this.max );
  2382. },
  2383. distanceToPoint: function () {
  2384. var v1 = new THREE.Vector3();
  2385. return function ( point ) {
  2386. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2387. return clampedPoint.sub( point ).length();
  2388. };
  2389. }(),
  2390. getBoundingSphere: function () {
  2391. var v1 = new THREE.Vector3();
  2392. return function ( optionalTarget ) {
  2393. var result = optionalTarget || new THREE.Sphere();
  2394. result.center = this.center();
  2395. result.radius = this.size( v1 ).length() * 0.5;
  2396. return result;
  2397. };
  2398. }(),
  2399. intersect: function ( box ) {
  2400. this.min.max( box.min );
  2401. this.max.min( box.max );
  2402. return this;
  2403. },
  2404. union: function ( box ) {
  2405. this.min.min( box.min );
  2406. this.max.max( box.max );
  2407. return this;
  2408. },
  2409. applyMatrix4: function () {
  2410. var points = [
  2411. new THREE.Vector3(),
  2412. new THREE.Vector3(),
  2413. new THREE.Vector3(),
  2414. new THREE.Vector3(),
  2415. new THREE.Vector3(),
  2416. new THREE.Vector3(),
  2417. new THREE.Vector3(),
  2418. new THREE.Vector3()
  2419. ];
  2420. return function ( matrix ) {
  2421. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2422. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2423. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2424. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2425. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2426. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2427. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2428. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2429. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2430. this.makeEmpty();
  2431. this.setFromPoints( points );
  2432. return this;
  2433. };
  2434. }(),
  2435. translate: function ( offset ) {
  2436. this.min.add( offset );
  2437. this.max.add( offset );
  2438. return this;
  2439. },
  2440. equals: function ( box ) {
  2441. return box.min.equals( this.min ) && box.max.equals( this.max );
  2442. },
  2443. clone: function () {
  2444. return new THREE.Box3().copy( this );
  2445. }
  2446. };
  2447. // File:src/math/Matrix3.js
  2448. /**
  2449. * @author alteredq / http://alteredqualia.com/
  2450. * @author WestLangley / http://github.com/WestLangley
  2451. * @author bhouston / http://exocortex.com
  2452. */
  2453. THREE.Matrix3 = function () {
  2454. this.elements = new Float32Array( [
  2455. 1, 0, 0,
  2456. 0, 1, 0,
  2457. 0, 0, 1
  2458. ] );
  2459. if ( arguments.length > 0 ) {
  2460. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2461. }
  2462. };
  2463. THREE.Matrix3.prototype = {
  2464. constructor: THREE.Matrix3,
  2465. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2466. var te = this.elements;
  2467. te[ 0 ] = n11; te[ 3 ] = n12; te[ 6 ] = n13;
  2468. te[ 1 ] = n21; te[ 4 ] = n22; te[ 7 ] = n23;
  2469. te[ 2 ] = n31; te[ 5 ] = n32; te[ 8 ] = n33;
  2470. return this;
  2471. },
  2472. identity: function () {
  2473. this.set(
  2474. 1, 0, 0,
  2475. 0, 1, 0,
  2476. 0, 0, 1
  2477. );
  2478. return this;
  2479. },
  2480. copy: function ( m ) {
  2481. var me = m.elements;
  2482. this.set(
  2483. me[ 0 ], me[ 3 ], me[ 6 ],
  2484. me[ 1 ], me[ 4 ], me[ 7 ],
  2485. me[ 2 ], me[ 5 ], me[ 8 ]
  2486. );
  2487. return this;
  2488. },
  2489. multiplyVector3: function ( vector ) {
  2490. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2491. return vector.applyMatrix3( this );
  2492. },
  2493. multiplyVector3Array: function ( a ) {
  2494. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2495. return this.applyToVector3Array( a );
  2496. },
  2497. applyToVector3Array: function () {
  2498. var v1;
  2499. return function ( array, offset, length ) {
  2500. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2501. if ( offset === undefined ) offset = 0;
  2502. if ( length === undefined ) length = array.length;
  2503. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2504. v1.fromArray( array, j );
  2505. v1.applyMatrix3( this );
  2506. v1.toArray( array, j );
  2507. }
  2508. return array;
  2509. };
  2510. }(),
  2511. applyToBuffer: function () {
  2512. var v1;
  2513. return function applyToBuffer( buffer, offset, length ) {
  2514. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2515. if ( offset === undefined ) offset = 0;
  2516. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2517. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2518. v1.x = buffer.getX( j );
  2519. v1.y = buffer.getY( j );
  2520. v1.z = buffer.getZ( j );
  2521. v1.applyMatrix3( this );
  2522. buffer.setXYZ( v1.x, v1.y, v1.z );
  2523. }
  2524. return buffer;
  2525. };
  2526. }(),
  2527. multiplyScalar: function ( s ) {
  2528. var te = this.elements;
  2529. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2530. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2531. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2532. return this;
  2533. },
  2534. determinant: function () {
  2535. var te = this.elements;
  2536. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2537. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2538. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2539. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2540. },
  2541. getInverse: function ( matrix, throwOnInvertible ) {
  2542. // input: THREE.Matrix4
  2543. // ( based on http://code.google.com/p/webgl-mjs/ )
  2544. var me = matrix.elements;
  2545. var te = this.elements;
  2546. te[ 0 ] = me[ 10 ] * me[ 5 ] - me[ 6 ] * me[ 9 ];
  2547. te[ 1 ] = - me[ 10 ] * me[ 1 ] + me[ 2 ] * me[ 9 ];
  2548. te[ 2 ] = me[ 6 ] * me[ 1 ] - me[ 2 ] * me[ 5 ];
  2549. te[ 3 ] = - me[ 10 ] * me[ 4 ] + me[ 6 ] * me[ 8 ];
  2550. te[ 4 ] = me[ 10 ] * me[ 0 ] - me[ 2 ] * me[ 8 ];
  2551. te[ 5 ] = - me[ 6 ] * me[ 0 ] + me[ 2 ] * me[ 4 ];
  2552. te[ 6 ] = me[ 9 ] * me[ 4 ] - me[ 5 ] * me[ 8 ];
  2553. te[ 7 ] = - me[ 9 ] * me[ 0 ] + me[ 1 ] * me[ 8 ];
  2554. te[ 8 ] = me[ 5 ] * me[ 0 ] - me[ 1 ] * me[ 4 ];
  2555. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2556. // no inverse
  2557. if ( det === 0 ) {
  2558. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2559. if ( throwOnInvertible || false ) {
  2560. throw new Error( msg );
  2561. } else {
  2562. console.warn( msg );
  2563. }
  2564. this.identity();
  2565. return this;
  2566. }
  2567. this.multiplyScalar( 1.0 / det );
  2568. return this;
  2569. },
  2570. transpose: function () {
  2571. var tmp, m = this.elements;
  2572. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2573. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2574. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2575. return this;
  2576. },
  2577. flattenToArrayOffset: function ( array, offset ) {
  2578. var te = this.elements;
  2579. array[ offset ] = te[ 0 ];
  2580. array[ offset + 1 ] = te[ 1 ];
  2581. array[ offset + 2 ] = te[ 2 ];
  2582. array[ offset + 3 ] = te[ 3 ];
  2583. array[ offset + 4 ] = te[ 4 ];
  2584. array[ offset + 5 ] = te[ 5 ];
  2585. array[ offset + 6 ] = te[ 6 ];
  2586. array[ offset + 7 ] = te[ 7 ];
  2587. array[ offset + 8 ] = te[ 8 ];
  2588. return array;
  2589. },
  2590. getNormalMatrix: function ( m ) {
  2591. // input: THREE.Matrix4
  2592. this.getInverse( m ).transpose();
  2593. return this;
  2594. },
  2595. transposeIntoArray: function ( r ) {
  2596. var m = this.elements;
  2597. r[ 0 ] = m[ 0 ];
  2598. r[ 1 ] = m[ 3 ];
  2599. r[ 2 ] = m[ 6 ];
  2600. r[ 3 ] = m[ 1 ];
  2601. r[ 4 ] = m[ 4 ];
  2602. r[ 5 ] = m[ 7 ];
  2603. r[ 6 ] = m[ 2 ];
  2604. r[ 7 ] = m[ 5 ];
  2605. r[ 8 ] = m[ 8 ];
  2606. return this;
  2607. },
  2608. fromArray: function ( array ) {
  2609. this.elements.set( array );
  2610. return this;
  2611. },
  2612. toArray: function () {
  2613. var te = this.elements;
  2614. return [
  2615. te[ 0 ], te[ 1 ], te[ 2 ],
  2616. te[ 3 ], te[ 4 ], te[ 5 ],
  2617. te[ 6 ], te[ 7 ], te[ 8 ]
  2618. ];
  2619. },
  2620. clone: function () {
  2621. return new THREE.Matrix3().fromArray( this.elements );
  2622. }
  2623. };
  2624. // File:src/math/Matrix4.js
  2625. /**
  2626. * @author mrdoob / http://mrdoob.com/
  2627. * @author supereggbert / http://www.paulbrunt.co.uk/
  2628. * @author philogb / http://blog.thejit.org/
  2629. * @author jordi_ros / http://plattsoft.com
  2630. * @author D1plo1d / http://github.com/D1plo1d
  2631. * @author alteredq / http://alteredqualia.com/
  2632. * @author mikael emtinger / http://gomo.se/
  2633. * @author timknip / http://www.floorplanner.com/
  2634. * @author bhouston / http://exocortex.com
  2635. * @author WestLangley / http://github.com/WestLangley
  2636. */
  2637. THREE.Matrix4 = function () {
  2638. this.elements = new Float32Array( [
  2639. 1, 0, 0, 0,
  2640. 0, 1, 0, 0,
  2641. 0, 0, 1, 0,
  2642. 0, 0, 0, 1
  2643. ] );
  2644. if ( arguments.length > 0 ) {
  2645. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2646. }
  2647. };
  2648. THREE.Matrix4.prototype = {
  2649. constructor: THREE.Matrix4,
  2650. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2651. var te = this.elements;
  2652. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2653. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2654. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2655. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2656. return this;
  2657. },
  2658. identity: function () {
  2659. this.set(
  2660. 1, 0, 0, 0,
  2661. 0, 1, 0, 0,
  2662. 0, 0, 1, 0,
  2663. 0, 0, 0, 1
  2664. );
  2665. return this;
  2666. },
  2667. copy: function ( m ) {
  2668. this.elements.set( m.elements );
  2669. return this;
  2670. },
  2671. extractPosition: function ( m ) {
  2672. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  2673. return this.copyPosition( m );
  2674. },
  2675. copyPosition: function ( m ) {
  2676. var te = this.elements;
  2677. var me = m.elements;
  2678. te[ 12 ] = me[ 12 ];
  2679. te[ 13 ] = me[ 13 ];
  2680. te[ 14 ] = me[ 14 ];
  2681. return this;
  2682. },
  2683. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2684. var te = this.elements;
  2685. xAxis.set( te[ 0 ], te[ 1 ], te[ 2 ] );
  2686. yAxis.set( te[ 4 ], te[ 5 ], te[ 6 ] );
  2687. zAxis.set( te[ 8 ], te[ 9 ], te[ 10 ] );
  2688. return this;
  2689. },
  2690. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2691. this.set(
  2692. xAxis.x, yAxis.x, zAxis.x, 0,
  2693. xAxis.y, yAxis.y, zAxis.y, 0,
  2694. xAxis.z, yAxis.z, zAxis.z, 0,
  2695. 0, 0, 0, 1
  2696. );
  2697. return this;
  2698. },
  2699. extractRotation: function () {
  2700. var v1;
  2701. return function ( m ) {
  2702. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2703. var te = this.elements;
  2704. var me = m.elements;
  2705. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  2706. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  2707. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  2708. te[ 0 ] = me[ 0 ] * scaleX;
  2709. te[ 1 ] = me[ 1 ] * scaleX;
  2710. te[ 2 ] = me[ 2 ] * scaleX;
  2711. te[ 4 ] = me[ 4 ] * scaleY;
  2712. te[ 5 ] = me[ 5 ] * scaleY;
  2713. te[ 6 ] = me[ 6 ] * scaleY;
  2714. te[ 8 ] = me[ 8 ] * scaleZ;
  2715. te[ 9 ] = me[ 9 ] * scaleZ;
  2716. te[ 10 ] = me[ 10 ] * scaleZ;
  2717. return this;
  2718. };
  2719. }(),
  2720. makeRotationFromEuler: function ( euler ) {
  2721. if ( euler instanceof THREE.Euler === false ) {
  2722. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2723. }
  2724. var te = this.elements;
  2725. var x = euler.x, y = euler.y, z = euler.z;
  2726. var a = Math.cos( x ), b = Math.sin( x );
  2727. var c = Math.cos( y ), d = Math.sin( y );
  2728. var e = Math.cos( z ), f = Math.sin( z );
  2729. if ( euler.order === 'XYZ' ) {
  2730. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2731. te[ 0 ] = c * e;
  2732. te[ 4 ] = - c * f;
  2733. te[ 8 ] = d;
  2734. te[ 1 ] = af + be * d;
  2735. te[ 5 ] = ae - bf * d;
  2736. te[ 9 ] = - b * c;
  2737. te[ 2 ] = bf - ae * d;
  2738. te[ 6 ] = be + af * d;
  2739. te[ 10 ] = a * c;
  2740. } else if ( euler.order === 'YXZ' ) {
  2741. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2742. te[ 0 ] = ce + df * b;
  2743. te[ 4 ] = de * b - cf;
  2744. te[ 8 ] = a * d;
  2745. te[ 1 ] = a * f;
  2746. te[ 5 ] = a * e;
  2747. te[ 9 ] = - b;
  2748. te[ 2 ] = cf * b - de;
  2749. te[ 6 ] = df + ce * b;
  2750. te[ 10 ] = a * c;
  2751. } else if ( euler.order === 'ZXY' ) {
  2752. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2753. te[ 0 ] = ce - df * b;
  2754. te[ 4 ] = - a * f;
  2755. te[ 8 ] = de + cf * b;
  2756. te[ 1 ] = cf + de * b;
  2757. te[ 5 ] = a * e;
  2758. te[ 9 ] = df - ce * b;
  2759. te[ 2 ] = - a * d;
  2760. te[ 6 ] = b;
  2761. te[ 10 ] = a * c;
  2762. } else if ( euler.order === 'ZYX' ) {
  2763. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2764. te[ 0 ] = c * e;
  2765. te[ 4 ] = be * d - af;
  2766. te[ 8 ] = ae * d + bf;
  2767. te[ 1 ] = c * f;
  2768. te[ 5 ] = bf * d + ae;
  2769. te[ 9 ] = af * d - be;
  2770. te[ 2 ] = - d;
  2771. te[ 6 ] = b * c;
  2772. te[ 10 ] = a * c;
  2773. } else if ( euler.order === 'YZX' ) {
  2774. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2775. te[ 0 ] = c * e;
  2776. te[ 4 ] = bd - ac * f;
  2777. te[ 8 ] = bc * f + ad;
  2778. te[ 1 ] = f;
  2779. te[ 5 ] = a * e;
  2780. te[ 9 ] = - b * e;
  2781. te[ 2 ] = - d * e;
  2782. te[ 6 ] = ad * f + bc;
  2783. te[ 10 ] = ac - bd * f;
  2784. } else if ( euler.order === 'XZY' ) {
  2785. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2786. te[ 0 ] = c * e;
  2787. te[ 4 ] = - f;
  2788. te[ 8 ] = d * e;
  2789. te[ 1 ] = ac * f + bd;
  2790. te[ 5 ] = a * e;
  2791. te[ 9 ] = ad * f - bc;
  2792. te[ 2 ] = bc * f - ad;
  2793. te[ 6 ] = b * e;
  2794. te[ 10 ] = bd * f + ac;
  2795. }
  2796. // last column
  2797. te[ 3 ] = 0;
  2798. te[ 7 ] = 0;
  2799. te[ 11 ] = 0;
  2800. // bottom row
  2801. te[ 12 ] = 0;
  2802. te[ 13 ] = 0;
  2803. te[ 14 ] = 0;
  2804. te[ 15 ] = 1;
  2805. return this;
  2806. },
  2807. setRotationFromQuaternion: function ( q ) {
  2808. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  2809. return this.makeRotationFromQuaternion( q );
  2810. },
  2811. makeRotationFromQuaternion: function ( q ) {
  2812. var te = this.elements;
  2813. var x = q.x, y = q.y, z = q.z, w = q.w;
  2814. var x2 = x + x, y2 = y + y, z2 = z + z;
  2815. var xx = x * x2, xy = x * y2, xz = x * z2;
  2816. var yy = y * y2, yz = y * z2, zz = z * z2;
  2817. var wx = w * x2, wy = w * y2, wz = w * z2;
  2818. te[ 0 ] = 1 - ( yy + zz );
  2819. te[ 4 ] = xy - wz;
  2820. te[ 8 ] = xz + wy;
  2821. te[ 1 ] = xy + wz;
  2822. te[ 5 ] = 1 - ( xx + zz );
  2823. te[ 9 ] = yz - wx;
  2824. te[ 2 ] = xz - wy;
  2825. te[ 6 ] = yz + wx;
  2826. te[ 10 ] = 1 - ( xx + yy );
  2827. // last column
  2828. te[ 3 ] = 0;
  2829. te[ 7 ] = 0;
  2830. te[ 11 ] = 0;
  2831. // bottom row
  2832. te[ 12 ] = 0;
  2833. te[ 13 ] = 0;
  2834. te[ 14 ] = 0;
  2835. te[ 15 ] = 1;
  2836. return this;
  2837. },
  2838. lookAt: function () {
  2839. var x, y, z;
  2840. return function ( eye, target, up ) {
  2841. if ( x === undefined ) x = new THREE.Vector3();
  2842. if ( y === undefined ) y = new THREE.Vector3();
  2843. if ( z === undefined ) z = new THREE.Vector3();
  2844. var te = this.elements;
  2845. z.subVectors( eye, target ).normalize();
  2846. if ( z.length() === 0 ) {
  2847. z.z = 1;
  2848. }
  2849. x.crossVectors( up, z ).normalize();
  2850. if ( x.length() === 0 ) {
  2851. z.x += 0.0001;
  2852. x.crossVectors( up, z ).normalize();
  2853. }
  2854. y.crossVectors( z, x );
  2855. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  2856. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  2857. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  2858. return this;
  2859. };
  2860. }(),
  2861. multiply: function ( m, n ) {
  2862. if ( n !== undefined ) {
  2863. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2864. return this.multiplyMatrices( m, n );
  2865. }
  2866. return this.multiplyMatrices( this, m );
  2867. },
  2868. multiplyMatrices: function ( a, b ) {
  2869. var ae = a.elements;
  2870. var be = b.elements;
  2871. var te = this.elements;
  2872. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  2873. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  2874. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  2875. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  2876. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  2877. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  2878. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  2879. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  2880. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2881. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2882. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2883. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2884. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2885. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2886. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2887. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2888. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2889. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2890. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2891. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2892. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2893. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2894. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2895. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2896. return this;
  2897. },
  2898. multiplyToArray: function ( a, b, r ) {
  2899. var te = this.elements;
  2900. this.multiplyMatrices( a, b );
  2901. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  2902. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  2903. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  2904. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  2905. return this;
  2906. },
  2907. multiplyScalar: function ( s ) {
  2908. var te = this.elements;
  2909. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  2910. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  2911. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  2912. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  2913. return this;
  2914. },
  2915. multiplyVector3: function ( vector ) {
  2916. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2917. return vector.applyProjection( this );
  2918. },
  2919. multiplyVector4: function ( vector ) {
  2920. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2921. return vector.applyMatrix4( this );
  2922. },
  2923. multiplyVector3Array: function ( a ) {
  2924. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2925. return this.applyToVector3Array( a );
  2926. },
  2927. applyToVector3Array: function () {
  2928. var v1;
  2929. return function ( array, offset, length ) {
  2930. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2931. if ( offset === undefined ) offset = 0;
  2932. if ( length === undefined ) length = array.length;
  2933. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2934. v1.fromArray( array, j );
  2935. v1.applyMatrix4( this );
  2936. v1.toArray( array, j );
  2937. }
  2938. return array;
  2939. };
  2940. }(),
  2941. applyToBuffer: function () {
  2942. var v1;
  2943. return function applyToBuffer( buffer, offset, length ) {
  2944. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2945. if ( offset === undefined ) offset = 0;
  2946. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2947. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2948. v1.x = buffer.getX( j );
  2949. v1.y = buffer.getY( j );
  2950. v1.z = buffer.getZ( j );
  2951. v1.applyMatrix4( this );
  2952. buffer.setXYZ( v1.x, v1.y, v1.z );
  2953. }
  2954. return buffer;
  2955. };
  2956. }(),
  2957. rotateAxis: function ( v ) {
  2958. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2959. v.transformDirection( this );
  2960. },
  2961. crossVector: function ( vector ) {
  2962. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2963. return vector.applyMatrix4( this );
  2964. },
  2965. determinant: function () {
  2966. var te = this.elements;
  2967. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  2968. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  2969. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  2970. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  2971. //TODO: make this more efficient
  2972. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2973. return (
  2974. n41 * (
  2975. + n14 * n23 * n32
  2976. - n13 * n24 * n32
  2977. - n14 * n22 * n33
  2978. + n12 * n24 * n33
  2979. + n13 * n22 * n34
  2980. - n12 * n23 * n34
  2981. ) +
  2982. n42 * (
  2983. + n11 * n23 * n34
  2984. - n11 * n24 * n33
  2985. + n14 * n21 * n33
  2986. - n13 * n21 * n34
  2987. + n13 * n24 * n31
  2988. - n14 * n23 * n31
  2989. ) +
  2990. n43 * (
  2991. + n11 * n24 * n32
  2992. - n11 * n22 * n34
  2993. - n14 * n21 * n32
  2994. + n12 * n21 * n34
  2995. + n14 * n22 * n31
  2996. - n12 * n24 * n31
  2997. ) +
  2998. n44 * (
  2999. - n13 * n22 * n31
  3000. - n11 * n23 * n32
  3001. + n11 * n22 * n33
  3002. + n13 * n21 * n32
  3003. - n12 * n21 * n33
  3004. + n12 * n23 * n31
  3005. )
  3006. );
  3007. },
  3008. transpose: function () {
  3009. var te = this.elements;
  3010. var tmp;
  3011. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3012. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3013. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3014. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3015. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3016. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3017. return this;
  3018. },
  3019. flattenToArrayOffset: function ( array, offset ) {
  3020. var te = this.elements;
  3021. array[ offset ] = te[ 0 ];
  3022. array[ offset + 1 ] = te[ 1 ];
  3023. array[ offset + 2 ] = te[ 2 ];
  3024. array[ offset + 3 ] = te[ 3 ];
  3025. array[ offset + 4 ] = te[ 4 ];
  3026. array[ offset + 5 ] = te[ 5 ];
  3027. array[ offset + 6 ] = te[ 6 ];
  3028. array[ offset + 7 ] = te[ 7 ];
  3029. array[ offset + 8 ] = te[ 8 ];
  3030. array[ offset + 9 ] = te[ 9 ];
  3031. array[ offset + 10 ] = te[ 10 ];
  3032. array[ offset + 11 ] = te[ 11 ];
  3033. array[ offset + 12 ] = te[ 12 ];
  3034. array[ offset + 13 ] = te[ 13 ];
  3035. array[ offset + 14 ] = te[ 14 ];
  3036. array[ offset + 15 ] = te[ 15 ];
  3037. return array;
  3038. },
  3039. getPosition: function () {
  3040. var v1;
  3041. return function () {
  3042. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3043. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3044. var te = this.elements;
  3045. return v1.set( te[ 12 ], te[ 13 ], te[ 14 ] );
  3046. };
  3047. }(),
  3048. setPosition: function ( v ) {
  3049. var te = this.elements;
  3050. te[ 12 ] = v.x;
  3051. te[ 13 ] = v.y;
  3052. te[ 14 ] = v.z;
  3053. return this;
  3054. },
  3055. getInverse: function ( m, throwOnInvertible ) {
  3056. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3057. var te = this.elements;
  3058. var me = m.elements;
  3059. var n11 = me[ 0 ], n12 = me[ 4 ], n13 = me[ 8 ], n14 = me[ 12 ];
  3060. var n21 = me[ 1 ], n22 = me[ 5 ], n23 = me[ 9 ], n24 = me[ 13 ];
  3061. var n31 = me[ 2 ], n32 = me[ 6 ], n33 = me[ 10 ], n34 = me[ 14 ];
  3062. var n41 = me[ 3 ], n42 = me[ 7 ], n43 = me[ 11 ], n44 = me[ 15 ];
  3063. te[ 0 ] = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44;
  3064. te[ 4 ] = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44;
  3065. te[ 8 ] = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44;
  3066. te[ 12 ] = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3067. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3068. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3069. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3070. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3071. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3072. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3073. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3074. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3075. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3076. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3077. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3078. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3079. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  3080. if ( det === 0 ) {
  3081. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3082. if ( throwOnInvertible || false ) {
  3083. throw new Error( msg );
  3084. } else {
  3085. console.warn( msg );
  3086. }
  3087. this.identity();
  3088. return this;
  3089. }
  3090. this.multiplyScalar( 1 / det );
  3091. return this;
  3092. },
  3093. translate: function ( v ) {
  3094. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  3095. },
  3096. rotateX: function ( angle ) {
  3097. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  3098. },
  3099. rotateY: function ( angle ) {
  3100. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  3101. },
  3102. rotateZ: function ( angle ) {
  3103. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  3104. },
  3105. rotateByAxis: function ( axis, angle ) {
  3106. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  3107. },
  3108. scale: function ( v ) {
  3109. var te = this.elements;
  3110. var x = v.x, y = v.y, z = v.z;
  3111. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3112. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3113. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3114. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3115. return this;
  3116. },
  3117. getMaxScaleOnAxis: function () {
  3118. var te = this.elements;
  3119. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3120. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3121. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3122. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  3123. },
  3124. makeTranslation: function ( x, y, z ) {
  3125. this.set(
  3126. 1, 0, 0, x,
  3127. 0, 1, 0, y,
  3128. 0, 0, 1, z,
  3129. 0, 0, 0, 1
  3130. );
  3131. return this;
  3132. },
  3133. makeRotationX: function ( theta ) {
  3134. var c = Math.cos( theta ), s = Math.sin( theta );
  3135. this.set(
  3136. 1, 0, 0, 0,
  3137. 0, c, - s, 0,
  3138. 0, s, c, 0,
  3139. 0, 0, 0, 1
  3140. );
  3141. return this;
  3142. },
  3143. makeRotationY: function ( theta ) {
  3144. var c = Math.cos( theta ), s = Math.sin( theta );
  3145. this.set(
  3146. c, 0, s, 0,
  3147. 0, 1, 0, 0,
  3148. - s, 0, c, 0,
  3149. 0, 0, 0, 1
  3150. );
  3151. return this;
  3152. },
  3153. makeRotationZ: function ( theta ) {
  3154. var c = Math.cos( theta ), s = Math.sin( theta );
  3155. this.set(
  3156. c, - s, 0, 0,
  3157. s, c, 0, 0,
  3158. 0, 0, 1, 0,
  3159. 0, 0, 0, 1
  3160. );
  3161. return this;
  3162. },
  3163. makeRotationAxis: function ( axis, angle ) {
  3164. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3165. var c = Math.cos( angle );
  3166. var s = Math.sin( angle );
  3167. var t = 1 - c;
  3168. var x = axis.x, y = axis.y, z = axis.z;
  3169. var tx = t * x, ty = t * y;
  3170. this.set(
  3171. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3172. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3173. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3174. 0, 0, 0, 1
  3175. );
  3176. return this;
  3177. },
  3178. makeScale: function ( x, y, z ) {
  3179. this.set(
  3180. x, 0, 0, 0,
  3181. 0, y, 0, 0,
  3182. 0, 0, z, 0,
  3183. 0, 0, 0, 1
  3184. );
  3185. return this;
  3186. },
  3187. compose: function ( position, quaternion, scale ) {
  3188. this.makeRotationFromQuaternion( quaternion );
  3189. this.scale( scale );
  3190. this.setPosition( position );
  3191. return this;
  3192. },
  3193. decompose: function () {
  3194. var vector, matrix;
  3195. return function ( position, quaternion, scale ) {
  3196. if ( vector === undefined ) vector = new THREE.Vector3();
  3197. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  3198. var te = this.elements;
  3199. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3200. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3201. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3202. // if determine is negative, we need to invert one scale
  3203. var det = this.determinant();
  3204. if ( det < 0 ) {
  3205. sx = - sx;
  3206. }
  3207. position.x = te[ 12 ];
  3208. position.y = te[ 13 ];
  3209. position.z = te[ 14 ];
  3210. // scale the rotation part
  3211. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3212. var invSX = 1 / sx;
  3213. var invSY = 1 / sy;
  3214. var invSZ = 1 / sz;
  3215. matrix.elements[ 0 ] *= invSX;
  3216. matrix.elements[ 1 ] *= invSX;
  3217. matrix.elements[ 2 ] *= invSX;
  3218. matrix.elements[ 4 ] *= invSY;
  3219. matrix.elements[ 5 ] *= invSY;
  3220. matrix.elements[ 6 ] *= invSY;
  3221. matrix.elements[ 8 ] *= invSZ;
  3222. matrix.elements[ 9 ] *= invSZ;
  3223. matrix.elements[ 10 ] *= invSZ;
  3224. quaternion.setFromRotationMatrix( matrix );
  3225. scale.x = sx;
  3226. scale.y = sy;
  3227. scale.z = sz;
  3228. return this;
  3229. };
  3230. }(),
  3231. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3232. var te = this.elements;
  3233. var x = 2 * near / ( right - left );
  3234. var y = 2 * near / ( top - bottom );
  3235. var a = ( right + left ) / ( right - left );
  3236. var b = ( top + bottom ) / ( top - bottom );
  3237. var c = - ( far + near ) / ( far - near );
  3238. var d = - 2 * far * near / ( far - near );
  3239. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3240. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3241. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3242. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3243. return this;
  3244. },
  3245. makePerspective: function ( fov, aspect, near, far ) {
  3246. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3247. var ymin = - ymax;
  3248. var xmin = ymin * aspect;
  3249. var xmax = ymax * aspect;
  3250. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3251. },
  3252. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3253. var te = this.elements;
  3254. var w = right - left;
  3255. var h = top - bottom;
  3256. var p = far - near;
  3257. var x = ( right + left ) / w;
  3258. var y = ( top + bottom ) / h;
  3259. var z = ( far + near ) / p;
  3260. te[ 0 ] = 2 / w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3261. te[ 1 ] = 0; te[ 5 ] = 2 / h; te[ 9 ] = 0; te[ 13 ] = - y;
  3262. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 / p; te[ 14 ] = - z;
  3263. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3264. return this;
  3265. },
  3266. fromArray: function ( array ) {
  3267. this.elements.set( array );
  3268. return this;
  3269. },
  3270. toArray: function () {
  3271. var te = this.elements;
  3272. return [
  3273. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3274. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3275. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3276. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3277. ];
  3278. },
  3279. clone: function () {
  3280. return new THREE.Matrix4().fromArray( this.elements );
  3281. }
  3282. };
  3283. // File:src/math/Ray.js
  3284. /**
  3285. * @author bhouston / http://exocortex.com
  3286. */
  3287. THREE.Ray = function ( origin, direction ) {
  3288. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3289. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3290. };
  3291. THREE.Ray.prototype = {
  3292. constructor: THREE.Ray,
  3293. set: function ( origin, direction ) {
  3294. this.origin.copy( origin );
  3295. this.direction.copy( direction );
  3296. return this;
  3297. },
  3298. copy: function ( ray ) {
  3299. this.origin.copy( ray.origin );
  3300. this.direction.copy( ray.direction );
  3301. return this;
  3302. },
  3303. at: function ( t, optionalTarget ) {
  3304. var result = optionalTarget || new THREE.Vector3();
  3305. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3306. },
  3307. recast: function () {
  3308. var v1 = new THREE.Vector3();
  3309. return function ( t ) {
  3310. this.origin.copy( this.at( t, v1 ) );
  3311. return this;
  3312. };
  3313. }(),
  3314. closestPointToPoint: function ( point, optionalTarget ) {
  3315. var result = optionalTarget || new THREE.Vector3();
  3316. result.subVectors( point, this.origin );
  3317. var directionDistance = result.dot( this.direction );
  3318. if ( directionDistance < 0 ) {
  3319. return result.copy( this.origin );
  3320. }
  3321. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3322. },
  3323. distanceToPoint: function () {
  3324. var v1 = new THREE.Vector3();
  3325. return function ( point ) {
  3326. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3327. // point behind the ray
  3328. if ( directionDistance < 0 ) {
  3329. return this.origin.distanceTo( point );
  3330. }
  3331. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3332. return v1.distanceTo( point );
  3333. };
  3334. }(),
  3335. distanceSqToSegment: function () {
  3336. var segCenter = new THREE.Vector3();
  3337. var segDir = new THREE.Vector3();
  3338. var diff = new THREE.Vector3();
  3339. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3340. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3341. // It returns the min distance between the ray and the segment
  3342. // defined by v0 and v1
  3343. // It can also set two optional targets :
  3344. // - The closest point on the ray
  3345. // - The closest point on the segment
  3346. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3347. segDir.copy( v1 ).sub( v0 ).normalize();
  3348. diff.copy( this.origin ).sub( segCenter );
  3349. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3350. var a01 = - this.direction.dot( segDir );
  3351. var b0 = diff.dot( this.direction );
  3352. var b1 = - diff.dot( segDir );
  3353. var c = diff.lengthSq();
  3354. var det = Math.abs( 1 - a01 * a01 );
  3355. var s0, s1, sqrDist, extDet;
  3356. if ( det > 0 ) {
  3357. // The ray and segment are not parallel.
  3358. s0 = a01 * b1 - b0;
  3359. s1 = a01 * b0 - b1;
  3360. extDet = segExtent * det;
  3361. if ( s0 >= 0 ) {
  3362. if ( s1 >= - extDet ) {
  3363. if ( s1 <= extDet ) {
  3364. // region 0
  3365. // Minimum at interior points of ray and segment.
  3366. var invDet = 1 / det;
  3367. s0 *= invDet;
  3368. s1 *= invDet;
  3369. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3370. } else {
  3371. // region 1
  3372. s1 = segExtent;
  3373. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3374. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3375. }
  3376. } else {
  3377. // region 5
  3378. s1 = - segExtent;
  3379. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3380. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3381. }
  3382. } else {
  3383. if ( s1 <= - extDet ) {
  3384. // region 4
  3385. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3386. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3387. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3388. } else if ( s1 <= extDet ) {
  3389. // region 3
  3390. s0 = 0;
  3391. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3392. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3393. } else {
  3394. // region 2
  3395. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3396. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3397. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3398. }
  3399. }
  3400. } else {
  3401. // Ray and segment are parallel.
  3402. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3403. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3404. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3405. }
  3406. if ( optionalPointOnRay ) {
  3407. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3408. }
  3409. if ( optionalPointOnSegment ) {
  3410. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3411. }
  3412. return sqrDist;
  3413. };
  3414. }(),
  3415. isIntersectionSphere: function ( sphere ) {
  3416. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3417. },
  3418. intersectSphere: function () {
  3419. // from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-sphere-intersection/
  3420. var v1 = new THREE.Vector3();
  3421. return function ( sphere, optionalTarget ) {
  3422. v1.subVectors( sphere.center, this.origin );
  3423. var tca = v1.dot( this.direction );
  3424. var d2 = v1.dot( v1 ) - tca * tca;
  3425. var radius2 = sphere.radius * sphere.radius;
  3426. if ( d2 > radius2 ) return null;
  3427. var thc = Math.sqrt( radius2 - d2 );
  3428. // t0 = first intersect point - entrance on front of sphere
  3429. var t0 = tca - thc;
  3430. // t1 = second intersect point - exit point on back of sphere
  3431. var t1 = tca + thc;
  3432. // test to see if both t0 and t1 are behind the ray - if so, return null
  3433. if ( t0 < 0 && t1 < 0 ) return null;
  3434. // test to see if t0 is behind the ray:
  3435. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3436. // in order to always return an intersect point that is in front of the ray.
  3437. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3438. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3439. return this.at( t0, optionalTarget );
  3440. }
  3441. }(),
  3442. isIntersectionPlane: function ( plane ) {
  3443. // check if the ray lies on the plane first
  3444. var distToPoint = plane.distanceToPoint( this.origin );
  3445. if ( distToPoint === 0 ) {
  3446. return true;
  3447. }
  3448. var denominator = plane.normal.dot( this.direction );
  3449. if ( denominator * distToPoint < 0 ) {
  3450. return true;
  3451. }
  3452. // ray origin is behind the plane (and is pointing behind it)
  3453. return false;
  3454. },
  3455. distanceToPlane: function ( plane ) {
  3456. var denominator = plane.normal.dot( this.direction );
  3457. if ( denominator === 0 ) {
  3458. // line is coplanar, return origin
  3459. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3460. return 0;
  3461. }
  3462. // Null is preferable to undefined since undefined means.... it is undefined
  3463. return null;
  3464. }
  3465. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3466. // Return if the ray never intersects the plane
  3467. return t >= 0 ? t : null;
  3468. },
  3469. intersectPlane: function ( plane, optionalTarget ) {
  3470. var t = this.distanceToPlane( plane );
  3471. if ( t === null ) {
  3472. return null;
  3473. }
  3474. return this.at( t, optionalTarget );
  3475. },
  3476. isIntersectionBox: function () {
  3477. var v = new THREE.Vector3();
  3478. return function ( box ) {
  3479. return this.intersectBox( box, v ) !== null;
  3480. };
  3481. }(),
  3482. intersectBox: function ( box, optionalTarget ) {
  3483. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3484. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3485. var invdirx = 1 / this.direction.x,
  3486. invdiry = 1 / this.direction.y,
  3487. invdirz = 1 / this.direction.z;
  3488. var origin = this.origin;
  3489. if ( invdirx >= 0 ) {
  3490. tmin = ( box.min.x - origin.x ) * invdirx;
  3491. tmax = ( box.max.x - origin.x ) * invdirx;
  3492. } else {
  3493. tmin = ( box.max.x - origin.x ) * invdirx;
  3494. tmax = ( box.min.x - origin.x ) * invdirx;
  3495. }
  3496. if ( invdiry >= 0 ) {
  3497. tymin = ( box.min.y - origin.y ) * invdiry;
  3498. tymax = ( box.max.y - origin.y ) * invdiry;
  3499. } else {
  3500. tymin = ( box.max.y - origin.y ) * invdiry;
  3501. tymax = ( box.min.y - origin.y ) * invdiry;
  3502. }
  3503. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3504. // These lines also handle the case where tmin or tmax is NaN
  3505. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3506. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3507. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3508. if ( invdirz >= 0 ) {
  3509. tzmin = ( box.min.z - origin.z ) * invdirz;
  3510. tzmax = ( box.max.z - origin.z ) * invdirz;
  3511. } else {
  3512. tzmin = ( box.max.z - origin.z ) * invdirz;
  3513. tzmax = ( box.min.z - origin.z ) * invdirz;
  3514. }
  3515. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3516. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3517. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3518. //return point closest to the ray (positive side)
  3519. if ( tmax < 0 ) return null;
  3520. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3521. },
  3522. intersectTriangle: function () {
  3523. // Compute the offset origin, edges, and normal.
  3524. var diff = new THREE.Vector3();
  3525. var edge1 = new THREE.Vector3();
  3526. var edge2 = new THREE.Vector3();
  3527. var normal = new THREE.Vector3();
  3528. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3529. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3530. edge1.subVectors( b, a );
  3531. edge2.subVectors( c, a );
  3532. normal.crossVectors( edge1, edge2 );
  3533. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3534. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3535. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3536. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3537. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3538. var DdN = this.direction.dot( normal );
  3539. var sign;
  3540. if ( DdN > 0 ) {
  3541. if ( backfaceCulling ) return null;
  3542. sign = 1;
  3543. } else if ( DdN < 0 ) {
  3544. sign = - 1;
  3545. DdN = - DdN;
  3546. } else {
  3547. return null;
  3548. }
  3549. diff.subVectors( this.origin, a );
  3550. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3551. // b1 < 0, no intersection
  3552. if ( DdQxE2 < 0 ) {
  3553. return null;
  3554. }
  3555. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3556. // b2 < 0, no intersection
  3557. if ( DdE1xQ < 0 ) {
  3558. return null;
  3559. }
  3560. // b1+b2 > 1, no intersection
  3561. if ( DdQxE2 + DdE1xQ > DdN ) {
  3562. return null;
  3563. }
  3564. // Line intersects triangle, check if ray does.
  3565. var QdN = - sign * diff.dot( normal );
  3566. // t < 0, no intersection
  3567. if ( QdN < 0 ) {
  3568. return null;
  3569. }
  3570. // Ray intersects triangle.
  3571. return this.at( QdN / DdN, optionalTarget );
  3572. };
  3573. }(),
  3574. applyMatrix4: function ( matrix4 ) {
  3575. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3576. this.origin.applyMatrix4( matrix4 );
  3577. this.direction.sub( this.origin );
  3578. this.direction.normalize();
  3579. return this;
  3580. },
  3581. equals: function ( ray ) {
  3582. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3583. },
  3584. clone: function () {
  3585. return new THREE.Ray().copy( this );
  3586. }
  3587. };
  3588. // File:src/math/Sphere.js
  3589. /**
  3590. * @author bhouston / http://exocortex.com
  3591. * @author mrdoob / http://mrdoob.com/
  3592. */
  3593. THREE.Sphere = function ( center, radius ) {
  3594. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3595. this.radius = ( radius !== undefined ) ? radius : 0;
  3596. };
  3597. THREE.Sphere.prototype = {
  3598. constructor: THREE.Sphere,
  3599. set: function ( center, radius ) {
  3600. this.center.copy( center );
  3601. this.radius = radius;
  3602. return this;
  3603. },
  3604. setFromPoints: function () {
  3605. var box = new THREE.Box3();
  3606. return function ( points, optionalCenter ) {
  3607. var center = this.center;
  3608. if ( optionalCenter !== undefined ) {
  3609. center.copy( optionalCenter );
  3610. } else {
  3611. box.setFromPoints( points ).center( center );
  3612. }
  3613. var maxRadiusSq = 0;
  3614. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3615. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3616. }
  3617. this.radius = Math.sqrt( maxRadiusSq );
  3618. return this;
  3619. };
  3620. }(),
  3621. copy: function ( sphere ) {
  3622. this.center.copy( sphere.center );
  3623. this.radius = sphere.radius;
  3624. return this;
  3625. },
  3626. empty: function () {
  3627. return ( this.radius <= 0 );
  3628. },
  3629. containsPoint: function ( point ) {
  3630. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3631. },
  3632. distanceToPoint: function ( point ) {
  3633. return ( point.distanceTo( this.center ) - this.radius );
  3634. },
  3635. intersectsSphere: function ( sphere ) {
  3636. var radiusSum = this.radius + sphere.radius;
  3637. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3638. },
  3639. clampPoint: function ( point, optionalTarget ) {
  3640. var deltaLengthSq = this.center.distanceToSquared( point );
  3641. var result = optionalTarget || new THREE.Vector3();
  3642. result.copy( point );
  3643. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3644. result.sub( this.center ).normalize();
  3645. result.multiplyScalar( this.radius ).add( this.center );
  3646. }
  3647. return result;
  3648. },
  3649. getBoundingBox: function ( optionalTarget ) {
  3650. var box = optionalTarget || new THREE.Box3();
  3651. box.set( this.center, this.center );
  3652. box.expandByScalar( this.radius );
  3653. return box;
  3654. },
  3655. applyMatrix4: function ( matrix ) {
  3656. this.center.applyMatrix4( matrix );
  3657. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3658. return this;
  3659. },
  3660. translate: function ( offset ) {
  3661. this.center.add( offset );
  3662. return this;
  3663. },
  3664. equals: function ( sphere ) {
  3665. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3666. },
  3667. clone: function () {
  3668. return new THREE.Sphere().copy( this );
  3669. }
  3670. };
  3671. // File:src/math/Frustum.js
  3672. /**
  3673. * @author mrdoob / http://mrdoob.com/
  3674. * @author alteredq / http://alteredqualia.com/
  3675. * @author bhouston / http://exocortex.com
  3676. */
  3677. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3678. this.planes = [
  3679. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3680. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3681. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3682. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3683. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3684. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3685. ];
  3686. };
  3687. THREE.Frustum.prototype = {
  3688. constructor: THREE.Frustum,
  3689. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3690. var planes = this.planes;
  3691. planes[ 0 ].copy( p0 );
  3692. planes[ 1 ].copy( p1 );
  3693. planes[ 2 ].copy( p2 );
  3694. planes[ 3 ].copy( p3 );
  3695. planes[ 4 ].copy( p4 );
  3696. planes[ 5 ].copy( p5 );
  3697. return this;
  3698. },
  3699. copy: function ( frustum ) {
  3700. var planes = this.planes;
  3701. for ( var i = 0; i < 6; i ++ ) {
  3702. planes[ i ].copy( frustum.planes[ i ] );
  3703. }
  3704. return this;
  3705. },
  3706. setFromMatrix: function ( m ) {
  3707. var planes = this.planes;
  3708. var me = m.elements;
  3709. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3710. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3711. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3712. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3713. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3714. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3715. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3716. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3717. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3718. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3719. return this;
  3720. },
  3721. intersectsObject: function () {
  3722. var sphere = new THREE.Sphere();
  3723. return function ( object ) {
  3724. var geometry = object.geometry;
  3725. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3726. sphere.copy( geometry.boundingSphere );
  3727. sphere.applyMatrix4( object.matrixWorld );
  3728. return this.intersectsSphere( sphere );
  3729. };
  3730. }(),
  3731. intersectsSphere: function ( sphere ) {
  3732. var planes = this.planes;
  3733. var center = sphere.center;
  3734. var negRadius = - sphere.radius;
  3735. for ( var i = 0; i < 6; i ++ ) {
  3736. var distance = planes[ i ].distanceToPoint( center );
  3737. if ( distance < negRadius ) {
  3738. return false;
  3739. }
  3740. }
  3741. return true;
  3742. },
  3743. intersectsBox: function () {
  3744. var p1 = new THREE.Vector3(),
  3745. p2 = new THREE.Vector3();
  3746. return function ( box ) {
  3747. var planes = this.planes;
  3748. for ( var i = 0; i < 6 ; i ++ ) {
  3749. var plane = planes[ i ];
  3750. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3751. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3752. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3753. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3754. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3755. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3756. var d1 = plane.distanceToPoint( p1 );
  3757. var d2 = plane.distanceToPoint( p2 );
  3758. // if both outside plane, no intersection
  3759. if ( d1 < 0 && d2 < 0 ) {
  3760. return false;
  3761. }
  3762. }
  3763. return true;
  3764. };
  3765. }(),
  3766. containsPoint: function ( point ) {
  3767. var planes = this.planes;
  3768. for ( var i = 0; i < 6; i ++ ) {
  3769. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3770. return false;
  3771. }
  3772. }
  3773. return true;
  3774. },
  3775. clone: function () {
  3776. return new THREE.Frustum().copy( this );
  3777. }
  3778. };
  3779. // File:src/math/Plane.js
  3780. /**
  3781. * @author bhouston / http://exocortex.com
  3782. */
  3783. THREE.Plane = function ( normal, constant ) {
  3784. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3785. this.constant = ( constant !== undefined ) ? constant : 0;
  3786. };
  3787. THREE.Plane.prototype = {
  3788. constructor: THREE.Plane,
  3789. set: function ( normal, constant ) {
  3790. this.normal.copy( normal );
  3791. this.constant = constant;
  3792. return this;
  3793. },
  3794. setComponents: function ( x, y, z, w ) {
  3795. this.normal.set( x, y, z );
  3796. this.constant = w;
  3797. return this;
  3798. },
  3799. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3800. this.normal.copy( normal );
  3801. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3802. return this;
  3803. },
  3804. setFromCoplanarPoints: function () {
  3805. var v1 = new THREE.Vector3();
  3806. var v2 = new THREE.Vector3();
  3807. return function ( a, b, c ) {
  3808. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3809. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3810. this.setFromNormalAndCoplanarPoint( normal, a );
  3811. return this;
  3812. };
  3813. }(),
  3814. copy: function ( plane ) {
  3815. this.normal.copy( plane.normal );
  3816. this.constant = plane.constant;
  3817. return this;
  3818. },
  3819. normalize: function () {
  3820. // Note: will lead to a divide by zero if the plane is invalid.
  3821. var inverseNormalLength = 1.0 / this.normal.length();
  3822. this.normal.multiplyScalar( inverseNormalLength );
  3823. this.constant *= inverseNormalLength;
  3824. return this;
  3825. },
  3826. negate: function () {
  3827. this.constant *= - 1;
  3828. this.normal.negate();
  3829. return this;
  3830. },
  3831. distanceToPoint: function ( point ) {
  3832. return this.normal.dot( point ) + this.constant;
  3833. },
  3834. distanceToSphere: function ( sphere ) {
  3835. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3836. },
  3837. projectPoint: function ( point, optionalTarget ) {
  3838. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3839. },
  3840. orthoPoint: function ( point, optionalTarget ) {
  3841. var perpendicularMagnitude = this.distanceToPoint( point );
  3842. var result = optionalTarget || new THREE.Vector3();
  3843. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3844. },
  3845. isIntersectionLine: function ( line ) {
  3846. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3847. var startSign = this.distanceToPoint( line.start );
  3848. var endSign = this.distanceToPoint( line.end );
  3849. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3850. },
  3851. intersectLine: function () {
  3852. var v1 = new THREE.Vector3();
  3853. return function ( line, optionalTarget ) {
  3854. var result = optionalTarget || new THREE.Vector3();
  3855. var direction = line.delta( v1 );
  3856. var denominator = this.normal.dot( direction );
  3857. if ( denominator === 0 ) {
  3858. // line is coplanar, return origin
  3859. if ( this.distanceToPoint( line.start ) === 0 ) {
  3860. return result.copy( line.start );
  3861. }
  3862. // Unsure if this is the correct method to handle this case.
  3863. return undefined;
  3864. }
  3865. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3866. if ( t < 0 || t > 1 ) {
  3867. return undefined;
  3868. }
  3869. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3870. };
  3871. }(),
  3872. coplanarPoint: function ( optionalTarget ) {
  3873. var result = optionalTarget || new THREE.Vector3();
  3874. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3875. },
  3876. applyMatrix4: function () {
  3877. var v1 = new THREE.Vector3();
  3878. var v2 = new THREE.Vector3();
  3879. var m1 = new THREE.Matrix3();
  3880. return function ( matrix, optionalNormalMatrix ) {
  3881. // compute new normal based on theory here:
  3882. // http://www.songho.ca/opengl/gl_normaltransform.html
  3883. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3884. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3885. var newCoplanarPoint = this.coplanarPoint( v2 );
  3886. newCoplanarPoint.applyMatrix4( matrix );
  3887. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3888. return this;
  3889. };
  3890. }(),
  3891. translate: function ( offset ) {
  3892. this.constant = this.constant - offset.dot( this.normal );
  3893. return this;
  3894. },
  3895. equals: function ( plane ) {
  3896. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  3897. },
  3898. clone: function () {
  3899. return new THREE.Plane().copy( this );
  3900. }
  3901. };
  3902. // File:src/math/Math.js
  3903. /**
  3904. * @author alteredq / http://alteredqualia.com/
  3905. * @author mrdoob / http://mrdoob.com/
  3906. */
  3907. THREE.Math = {
  3908. generateUUID: function () {
  3909. // http://www.broofa.com/Tools/Math.uuid.htm
  3910. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  3911. var uuid = new Array( 36 );
  3912. var rnd = 0, r;
  3913. return function () {
  3914. for ( var i = 0; i < 36; i ++ ) {
  3915. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  3916. uuid[ i ] = '-';
  3917. } else if ( i === 14 ) {
  3918. uuid[ i ] = '4';
  3919. } else {
  3920. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  3921. r = rnd & 0xf;
  3922. rnd = rnd >> 4;
  3923. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  3924. }
  3925. }
  3926. return uuid.join( '' );
  3927. };
  3928. }(),
  3929. // Clamp value to range <a, b>
  3930. clamp: function ( x, a, b ) {
  3931. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3932. },
  3933. // Clamp value to range <a, inf)
  3934. clampBottom: function ( x, a ) {
  3935. return x < a ? a : x;
  3936. },
  3937. // Linear mapping from range <a1, a2> to range <b1, b2>
  3938. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3939. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3940. },
  3941. // http://en.wikipedia.org/wiki/Smoothstep
  3942. smoothstep: function ( x, min, max ) {
  3943. if ( x <= min ) return 0;
  3944. if ( x >= max ) return 1;
  3945. x = ( x - min ) / ( max - min );
  3946. return x * x * ( 3 - 2 * x );
  3947. },
  3948. smootherstep: function ( x, min, max ) {
  3949. if ( x <= min ) return 0;
  3950. if ( x >= max ) return 1;
  3951. x = ( x - min ) / ( max - min );
  3952. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  3953. },
  3954. // Random float from <0, 1> with 16 bits of randomness
  3955. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3956. random16: function () {
  3957. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3958. },
  3959. // Random integer from <low, high> interval
  3960. randInt: function ( low, high ) {
  3961. return Math.floor( this.randFloat( low, high ) );
  3962. },
  3963. // Random float from <low, high> interval
  3964. randFloat: function ( low, high ) {
  3965. return low + Math.random() * ( high - low );
  3966. },
  3967. // Random float from <-range/2, range/2> interval
  3968. randFloatSpread: function ( range ) {
  3969. return range * ( 0.5 - Math.random() );
  3970. },
  3971. degToRad: function () {
  3972. var degreeToRadiansFactor = Math.PI / 180;
  3973. return function ( degrees ) {
  3974. return degrees * degreeToRadiansFactor;
  3975. };
  3976. }(),
  3977. radToDeg: function () {
  3978. var radianToDegreesFactor = 180 / Math.PI;
  3979. return function ( radians ) {
  3980. return radians * radianToDegreesFactor;
  3981. };
  3982. }(),
  3983. isPowerOfTwo: function ( value ) {
  3984. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3985. },
  3986. nextPowerOfTwo: function ( value ) {
  3987. value --;
  3988. value |= value >> 1;
  3989. value |= value >> 2;
  3990. value |= value >> 4;
  3991. value |= value >> 8;
  3992. value |= value >> 16;
  3993. value ++;
  3994. return value;
  3995. }
  3996. };
  3997. // File:src/math/Spline.js
  3998. /**
  3999. * Spline from Tween.js, slightly optimized (and trashed)
  4000. * http://sole.github.com/tween.js/examples/05_spline.html
  4001. *
  4002. * @author mrdoob / http://mrdoob.com/
  4003. * @author alteredq / http://alteredqualia.com/
  4004. */
  4005. THREE.Spline = function ( points ) {
  4006. this.points = points;
  4007. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4008. point, intPoint, weight, w2, w3,
  4009. pa, pb, pc, pd;
  4010. this.initFromArray = function ( a ) {
  4011. this.points = [];
  4012. for ( var i = 0; i < a.length; i ++ ) {
  4013. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4014. }
  4015. };
  4016. this.getPoint = function ( k ) {
  4017. point = ( this.points.length - 1 ) * k;
  4018. intPoint = Math.floor( point );
  4019. weight = point - intPoint;
  4020. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4021. c[ 1 ] = intPoint;
  4022. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4023. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4024. pa = this.points[ c[ 0 ] ];
  4025. pb = this.points[ c[ 1 ] ];
  4026. pc = this.points[ c[ 2 ] ];
  4027. pd = this.points[ c[ 3 ] ];
  4028. w2 = weight * weight;
  4029. w3 = weight * w2;
  4030. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4031. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4032. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4033. return v3;
  4034. };
  4035. this.getControlPointsArray = function () {
  4036. var i, p, l = this.points.length,
  4037. coords = [];
  4038. for ( i = 0; i < l; i ++ ) {
  4039. p = this.points[ i ];
  4040. coords[ i ] = [ p.x, p.y, p.z ];
  4041. }
  4042. return coords;
  4043. };
  4044. // approximate length by summing linear segments
  4045. this.getLength = function ( nSubDivisions ) {
  4046. var i, index, nSamples, position,
  4047. point = 0, intPoint = 0, oldIntPoint = 0,
  4048. oldPosition = new THREE.Vector3(),
  4049. tmpVec = new THREE.Vector3(),
  4050. chunkLengths = [],
  4051. totalLength = 0;
  4052. // first point has 0 length
  4053. chunkLengths[ 0 ] = 0;
  4054. if ( ! nSubDivisions ) nSubDivisions = 100;
  4055. nSamples = this.points.length * nSubDivisions;
  4056. oldPosition.copy( this.points[ 0 ] );
  4057. for ( i = 1; i < nSamples; i ++ ) {
  4058. index = i / nSamples;
  4059. position = this.getPoint( index );
  4060. tmpVec.copy( position );
  4061. totalLength += tmpVec.distanceTo( oldPosition );
  4062. oldPosition.copy( position );
  4063. point = ( this.points.length - 1 ) * index;
  4064. intPoint = Math.floor( point );
  4065. if ( intPoint !== oldIntPoint ) {
  4066. chunkLengths[ intPoint ] = totalLength;
  4067. oldIntPoint = intPoint;
  4068. }
  4069. }
  4070. // last point ends with total length
  4071. chunkLengths[ chunkLengths.length ] = totalLength;
  4072. return { chunks: chunkLengths, total: totalLength };
  4073. };
  4074. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4075. var i, j,
  4076. index, indexCurrent, indexNext,
  4077. realDistance,
  4078. sampling, position,
  4079. newpoints = [],
  4080. tmpVec = new THREE.Vector3(),
  4081. sl = this.getLength();
  4082. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4083. for ( i = 1; i < this.points.length; i ++ ) {
  4084. //tmpVec.copy( this.points[ i - 1 ] );
  4085. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4086. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4087. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4088. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4089. indexNext = i / ( this.points.length - 1 );
  4090. for ( j = 1; j < sampling - 1; j ++ ) {
  4091. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4092. position = this.getPoint( index );
  4093. newpoints.push( tmpVec.copy( position ).clone() );
  4094. }
  4095. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4096. }
  4097. this.points = newpoints;
  4098. };
  4099. // Catmull-Rom
  4100. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4101. var v0 = ( p2 - p0 ) * 0.5,
  4102. v1 = ( p3 - p1 ) * 0.5;
  4103. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4104. }
  4105. };
  4106. // File:src/math/Triangle.js
  4107. /**
  4108. * @author bhouston / http://exocortex.com
  4109. * @author mrdoob / http://mrdoob.com/
  4110. */
  4111. THREE.Triangle = function ( a, b, c ) {
  4112. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4113. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4114. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4115. };
  4116. THREE.Triangle.normal = function () {
  4117. var v0 = new THREE.Vector3();
  4118. return function ( a, b, c, optionalTarget ) {
  4119. var result = optionalTarget || new THREE.Vector3();
  4120. result.subVectors( c, b );
  4121. v0.subVectors( a, b );
  4122. result.cross( v0 );
  4123. var resultLengthSq = result.lengthSq();
  4124. if ( resultLengthSq > 0 ) {
  4125. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4126. }
  4127. return result.set( 0, 0, 0 );
  4128. };
  4129. }();
  4130. // static/instance method to calculate barycentric coordinates
  4131. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4132. THREE.Triangle.barycoordFromPoint = function () {
  4133. var v0 = new THREE.Vector3();
  4134. var v1 = new THREE.Vector3();
  4135. var v2 = new THREE.Vector3();
  4136. return function ( point, a, b, c, optionalTarget ) {
  4137. v0.subVectors( c, a );
  4138. v1.subVectors( b, a );
  4139. v2.subVectors( point, a );
  4140. var dot00 = v0.dot( v0 );
  4141. var dot01 = v0.dot( v1 );
  4142. var dot02 = v0.dot( v2 );
  4143. var dot11 = v1.dot( v1 );
  4144. var dot12 = v1.dot( v2 );
  4145. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4146. var result = optionalTarget || new THREE.Vector3();
  4147. // collinear or singular triangle
  4148. if ( denom === 0 ) {
  4149. // arbitrary location outside of triangle?
  4150. // not sure if this is the best idea, maybe should be returning undefined
  4151. return result.set( - 2, - 1, - 1 );
  4152. }
  4153. var invDenom = 1 / denom;
  4154. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4155. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4156. // barycentric coordinates must always sum to 1
  4157. return result.set( 1 - u - v, v, u );
  4158. };
  4159. }();
  4160. THREE.Triangle.containsPoint = function () {
  4161. var v1 = new THREE.Vector3();
  4162. return function ( point, a, b, c ) {
  4163. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4164. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4165. };
  4166. }();
  4167. THREE.Triangle.prototype = {
  4168. constructor: THREE.Triangle,
  4169. set: function ( a, b, c ) {
  4170. this.a.copy( a );
  4171. this.b.copy( b );
  4172. this.c.copy( c );
  4173. return this;
  4174. },
  4175. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4176. this.a.copy( points[ i0 ] );
  4177. this.b.copy( points[ i1 ] );
  4178. this.c.copy( points[ i2 ] );
  4179. return this;
  4180. },
  4181. copy: function ( triangle ) {
  4182. this.a.copy( triangle.a );
  4183. this.b.copy( triangle.b );
  4184. this.c.copy( triangle.c );
  4185. return this;
  4186. },
  4187. area: function () {
  4188. var v0 = new THREE.Vector3();
  4189. var v1 = new THREE.Vector3();
  4190. return function () {
  4191. v0.subVectors( this.c, this.b );
  4192. v1.subVectors( this.a, this.b );
  4193. return v0.cross( v1 ).length() * 0.5;
  4194. };
  4195. }(),
  4196. midpoint: function ( optionalTarget ) {
  4197. var result = optionalTarget || new THREE.Vector3();
  4198. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4199. },
  4200. normal: function ( optionalTarget ) {
  4201. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4202. },
  4203. plane: function ( optionalTarget ) {
  4204. var result = optionalTarget || new THREE.Plane();
  4205. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4206. },
  4207. barycoordFromPoint: function ( point, optionalTarget ) {
  4208. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4209. },
  4210. containsPoint: function ( point ) {
  4211. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4212. },
  4213. equals: function ( triangle ) {
  4214. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4215. },
  4216. clone: function () {
  4217. return new THREE.Triangle().copy( this );
  4218. }
  4219. };
  4220. // File:src/core/Clock.js
  4221. /**
  4222. * @author alteredq / http://alteredqualia.com/
  4223. */
  4224. THREE.Clock = function ( autoStart ) {
  4225. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4226. this.startTime = 0;
  4227. this.oldTime = 0;
  4228. this.elapsedTime = 0;
  4229. this.running = false;
  4230. };
  4231. THREE.Clock.prototype = {
  4232. constructor: THREE.Clock,
  4233. start: function () {
  4234. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4235. ? self.performance.now()
  4236. : Date.now();
  4237. this.oldTime = this.startTime;
  4238. this.running = true;
  4239. },
  4240. stop: function () {
  4241. this.getElapsedTime();
  4242. this.running = false;
  4243. },
  4244. getElapsedTime: function () {
  4245. this.getDelta();
  4246. return this.elapsedTime;
  4247. },
  4248. getDelta: function () {
  4249. var diff = 0;
  4250. if ( this.autoStart && ! this.running ) {
  4251. this.start();
  4252. }
  4253. if ( this.running ) {
  4254. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4255. ? self.performance.now()
  4256. : Date.now();
  4257. diff = 0.001 * ( newTime - this.oldTime );
  4258. this.oldTime = newTime;
  4259. this.elapsedTime += diff;
  4260. }
  4261. return diff;
  4262. }
  4263. };
  4264. // File:src/core/EventDispatcher.js
  4265. /**
  4266. * https://github.com/mrdoob/eventdispatcher.js/
  4267. */
  4268. THREE.EventDispatcher = function () {};
  4269. THREE.EventDispatcher.prototype = {
  4270. constructor: THREE.EventDispatcher,
  4271. apply: function ( object ) {
  4272. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4273. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4274. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4275. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4276. },
  4277. addEventListener: function ( type, listener ) {
  4278. if ( this._listeners === undefined ) this._listeners = {};
  4279. var listeners = this._listeners;
  4280. if ( listeners[ type ] === undefined ) {
  4281. listeners[ type ] = [];
  4282. }
  4283. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4284. listeners[ type ].push( listener );
  4285. }
  4286. },
  4287. hasEventListener: function ( type, listener ) {
  4288. if ( this._listeners === undefined ) return false;
  4289. var listeners = this._listeners;
  4290. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4291. return true;
  4292. }
  4293. return false;
  4294. },
  4295. removeEventListener: function ( type, listener ) {
  4296. if ( this._listeners === undefined ) return;
  4297. var listeners = this._listeners;
  4298. var listenerArray = listeners[ type ];
  4299. if ( listenerArray !== undefined ) {
  4300. var index = listenerArray.indexOf( listener );
  4301. if ( index !== - 1 ) {
  4302. listenerArray.splice( index, 1 );
  4303. }
  4304. }
  4305. },
  4306. dispatchEvent: function ( event ) {
  4307. if ( this._listeners === undefined ) return;
  4308. var listeners = this._listeners;
  4309. var listenerArray = listeners[ event.type ];
  4310. if ( listenerArray !== undefined ) {
  4311. event.target = this;
  4312. var array = [];
  4313. var length = listenerArray.length;
  4314. for ( var i = 0; i < length; i ++ ) {
  4315. array[ i ] = listenerArray[ i ];
  4316. }
  4317. for ( var i = 0; i < length; i ++ ) {
  4318. array[ i ].call( this, event );
  4319. }
  4320. }
  4321. }
  4322. };
  4323. // File:src/core/Raycaster.js
  4324. /**
  4325. * @author mrdoob / http://mrdoob.com/
  4326. * @author bhouston / http://exocortex.com/
  4327. * @author stephomi / http://stephaneginier.com/
  4328. */
  4329. ( function ( THREE ) {
  4330. THREE.Raycaster = function ( origin, direction, near, far ) {
  4331. this.ray = new THREE.Ray( origin, direction );
  4332. // direction is assumed to be normalized (for accurate distance calculations)
  4333. this.near = near || 0;
  4334. this.far = far || Infinity;
  4335. this.params = {
  4336. Sprite: {},
  4337. Mesh: {},
  4338. PointCloud: { threshold: 1 },
  4339. LOD: {},
  4340. Line: {}
  4341. };
  4342. };
  4343. var descSort = function ( a, b ) {
  4344. return a.distance - b.distance;
  4345. };
  4346. var intersectObject = function ( object, raycaster, intersects, recursive ) {
  4347. object.raycast( raycaster, intersects );
  4348. if ( recursive === true ) {
  4349. var children = object.children;
  4350. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4351. intersectObject( children[ i ], raycaster, intersects, true );
  4352. }
  4353. }
  4354. };
  4355. //
  4356. THREE.Raycaster.prototype = {
  4357. constructor: THREE.Raycaster,
  4358. linePrecision: 1,
  4359. set: function ( origin, direction ) {
  4360. // direction is assumed to be normalized (for accurate distance calculations)
  4361. this.ray.set( origin, direction );
  4362. },
  4363. setFromCamera: function ( coords, camera ) {
  4364. if ( camera instanceof THREE.PerspectiveCamera ) {
  4365. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4366. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4367. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4368. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4369. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4370. } else {
  4371. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  4372. }
  4373. },
  4374. intersectObject: function ( object, recursive ) {
  4375. var intersects = [];
  4376. intersectObject( object, this, intersects, recursive );
  4377. intersects.sort( descSort );
  4378. return intersects;
  4379. },
  4380. intersectObjects: function ( objects, recursive ) {
  4381. var intersects = [];
  4382. if ( Array.isArray( objects ) === false ) {
  4383. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  4384. return intersects;
  4385. }
  4386. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4387. intersectObject( objects[ i ], this, intersects, recursive );
  4388. }
  4389. intersects.sort( descSort );
  4390. return intersects;
  4391. }
  4392. };
  4393. }( THREE ) );
  4394. // File:src/core/Object3D.js
  4395. /**
  4396. * @author mrdoob / http://mrdoob.com/
  4397. * @author mikael emtinger / http://gomo.se/
  4398. * @author alteredq / http://alteredqualia.com/
  4399. * @author WestLangley / http://github.com/WestLangley
  4400. * @author elephantatwork / www.elephantatwork.ch
  4401. */
  4402. THREE.Object3D = function () {
  4403. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  4404. this.uuid = THREE.Math.generateUUID();
  4405. this.name = '';
  4406. this.type = 'Object3D';
  4407. this.parent = undefined;
  4408. this.children = [];
  4409. this.up = THREE.Object3D.DefaultUp.clone();
  4410. var position = new THREE.Vector3();
  4411. var rotation = new THREE.Euler();
  4412. var quaternion = new THREE.Quaternion();
  4413. var scale = new THREE.Vector3( 1, 1, 1 );
  4414. var onRotationChange = function () {
  4415. quaternion.setFromEuler( rotation, false );
  4416. };
  4417. var onQuaternionChange = function () {
  4418. rotation.setFromQuaternion( quaternion, undefined, false );
  4419. };
  4420. rotation.onChange( onRotationChange );
  4421. quaternion.onChange( onQuaternionChange );
  4422. Object.defineProperties( this, {
  4423. position: {
  4424. enumerable: true,
  4425. value: position
  4426. },
  4427. rotation: {
  4428. enumerable: true,
  4429. value: rotation
  4430. },
  4431. quaternion: {
  4432. enumerable: true,
  4433. value: quaternion
  4434. },
  4435. scale: {
  4436. enumerable: true,
  4437. value: scale
  4438. }
  4439. } );
  4440. this.rotationAutoUpdate = true;
  4441. this.matrix = new THREE.Matrix4();
  4442. this.matrixWorld = new THREE.Matrix4();
  4443. this.matrixAutoUpdate = true;
  4444. this.matrixWorldNeedsUpdate = false;
  4445. this.visible = true;
  4446. this.castShadow = false;
  4447. this.receiveShadow = false;
  4448. this.frustumCulled = true;
  4449. this.renderOrder = 0;
  4450. this.userData = {};
  4451. };
  4452. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  4453. THREE.Object3D.prototype = {
  4454. constructor: THREE.Object3D,
  4455. get eulerOrder () {
  4456. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4457. return this.rotation.order;
  4458. },
  4459. set eulerOrder ( value ) {
  4460. console.warn( 'THREE.Object3D: .eulerOrder has been moved to .rotation.order.' );
  4461. this.rotation.order = value;
  4462. },
  4463. get useQuaternion () {
  4464. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4465. },
  4466. set useQuaternion ( value ) {
  4467. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  4468. },
  4469. applyMatrix: function ( matrix ) {
  4470. this.matrix.multiplyMatrices( matrix, this.matrix );
  4471. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4472. },
  4473. setRotationFromAxisAngle: function ( axis, angle ) {
  4474. // assumes axis is normalized
  4475. this.quaternion.setFromAxisAngle( axis, angle );
  4476. },
  4477. setRotationFromEuler: function ( euler ) {
  4478. this.quaternion.setFromEuler( euler, true );
  4479. },
  4480. setRotationFromMatrix: function ( m ) {
  4481. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4482. this.quaternion.setFromRotationMatrix( m );
  4483. },
  4484. setRotationFromQuaternion: function ( q ) {
  4485. // assumes q is normalized
  4486. this.quaternion.copy( q );
  4487. },
  4488. rotateOnAxis: function () {
  4489. // rotate object on axis in object space
  4490. // axis is assumed to be normalized
  4491. var q1 = new THREE.Quaternion();
  4492. return function ( axis, angle ) {
  4493. q1.setFromAxisAngle( axis, angle );
  4494. this.quaternion.multiply( q1 );
  4495. return this;
  4496. }
  4497. }(),
  4498. rotateX: function () {
  4499. var v1 = new THREE.Vector3( 1, 0, 0 );
  4500. return function ( angle ) {
  4501. return this.rotateOnAxis( v1, angle );
  4502. };
  4503. }(),
  4504. rotateY: function () {
  4505. var v1 = new THREE.Vector3( 0, 1, 0 );
  4506. return function ( angle ) {
  4507. return this.rotateOnAxis( v1, angle );
  4508. };
  4509. }(),
  4510. rotateZ: function () {
  4511. var v1 = new THREE.Vector3( 0, 0, 1 );
  4512. return function ( angle ) {
  4513. return this.rotateOnAxis( v1, angle );
  4514. };
  4515. }(),
  4516. translateOnAxis: function () {
  4517. // translate object by distance along axis in object space
  4518. // axis is assumed to be normalized
  4519. var v1 = new THREE.Vector3();
  4520. return function ( axis, distance ) {
  4521. v1.copy( axis ).applyQuaternion( this.quaternion );
  4522. this.position.add( v1.multiplyScalar( distance ) );
  4523. return this;
  4524. }
  4525. }(),
  4526. translate: function ( distance, axis ) {
  4527. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  4528. return this.translateOnAxis( axis, distance );
  4529. },
  4530. translateX: function () {
  4531. var v1 = new THREE.Vector3( 1, 0, 0 );
  4532. return function ( distance ) {
  4533. return this.translateOnAxis( v1, distance );
  4534. };
  4535. }(),
  4536. translateY: function () {
  4537. var v1 = new THREE.Vector3( 0, 1, 0 );
  4538. return function ( distance ) {
  4539. return this.translateOnAxis( v1, distance );
  4540. };
  4541. }(),
  4542. translateZ: function () {
  4543. var v1 = new THREE.Vector3( 0, 0, 1 );
  4544. return function ( distance ) {
  4545. return this.translateOnAxis( v1, distance );
  4546. };
  4547. }(),
  4548. localToWorld: function ( vector ) {
  4549. return vector.applyMatrix4( this.matrixWorld );
  4550. },
  4551. worldToLocal: function () {
  4552. var m1 = new THREE.Matrix4();
  4553. return function ( vector ) {
  4554. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4555. };
  4556. }(),
  4557. lookAt: function () {
  4558. // This routine does not support objects with rotated and/or translated parent(s)
  4559. var m1 = new THREE.Matrix4();
  4560. return function ( vector ) {
  4561. m1.lookAt( vector, this.position, this.up );
  4562. this.quaternion.setFromRotationMatrix( m1 );
  4563. };
  4564. }(),
  4565. add: function ( object ) {
  4566. if ( arguments.length > 1 ) {
  4567. for ( var i = 0; i < arguments.length; i ++ ) {
  4568. this.add( arguments[ i ] );
  4569. }
  4570. return this;
  4571. }
  4572. if ( object === this ) {
  4573. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  4574. return this;
  4575. }
  4576. if ( object instanceof THREE.Object3D ) {
  4577. if ( object.parent !== undefined ) {
  4578. object.parent.remove( object );
  4579. }
  4580. object.parent = this;
  4581. object.dispatchEvent( { type: 'added' } );
  4582. this.children.push( object );
  4583. } else {
  4584. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  4585. }
  4586. return this;
  4587. },
  4588. remove: function ( object ) {
  4589. if ( arguments.length > 1 ) {
  4590. for ( var i = 0; i < arguments.length; i ++ ) {
  4591. this.remove( arguments[ i ] );
  4592. }
  4593. }
  4594. var index = this.children.indexOf( object );
  4595. if ( index !== - 1 ) {
  4596. object.parent = undefined;
  4597. object.dispatchEvent( { type: 'removed' } );
  4598. this.children.splice( index, 1 );
  4599. }
  4600. },
  4601. getChildByName: function ( name ) {
  4602. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  4603. return this.getObjectByName( name );
  4604. },
  4605. getObjectById: function ( id ) {
  4606. return this.getObjectByProperty( 'id', id );
  4607. },
  4608. getObjectByName: function ( name ) {
  4609. return this.getObjectByProperty( 'name', name );
  4610. },
  4611. getObjectByProperty: function ( name, value ) {
  4612. if ( this[ name ] === value ) return this;
  4613. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4614. var child = this.children[ i ];
  4615. var object = child.getObjectByProperty( name, value );
  4616. if ( object !== undefined ) {
  4617. return object;
  4618. }
  4619. }
  4620. return undefined;
  4621. },
  4622. getWorldPosition: function ( optionalTarget ) {
  4623. var result = optionalTarget || new THREE.Vector3();
  4624. this.updateMatrixWorld( true );
  4625. return result.setFromMatrixPosition( this.matrixWorld );
  4626. },
  4627. getWorldQuaternion: function () {
  4628. var position = new THREE.Vector3();
  4629. var scale = new THREE.Vector3();
  4630. return function ( optionalTarget ) {
  4631. var result = optionalTarget || new THREE.Quaternion();
  4632. this.updateMatrixWorld( true );
  4633. this.matrixWorld.decompose( position, result, scale );
  4634. return result;
  4635. }
  4636. }(),
  4637. getWorldRotation: function () {
  4638. var quaternion = new THREE.Quaternion();
  4639. return function ( optionalTarget ) {
  4640. var result = optionalTarget || new THREE.Euler();
  4641. this.getWorldQuaternion( quaternion );
  4642. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  4643. }
  4644. }(),
  4645. getWorldScale: function () {
  4646. var position = new THREE.Vector3();
  4647. var quaternion = new THREE.Quaternion();
  4648. return function ( optionalTarget ) {
  4649. var result = optionalTarget || new THREE.Vector3();
  4650. this.updateMatrixWorld( true );
  4651. this.matrixWorld.decompose( position, quaternion, result );
  4652. return result;
  4653. }
  4654. }(),
  4655. getWorldDirection: function () {
  4656. var quaternion = new THREE.Quaternion();
  4657. return function ( optionalTarget ) {
  4658. var result = optionalTarget || new THREE.Vector3();
  4659. this.getWorldQuaternion( quaternion );
  4660. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  4661. }
  4662. }(),
  4663. raycast: function () {},
  4664. traverse: function ( callback ) {
  4665. callback( this );
  4666. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4667. this.children[ i ].traverse( callback );
  4668. }
  4669. },
  4670. traverseVisible: function ( callback ) {
  4671. if ( this.visible === false ) return;
  4672. callback( this );
  4673. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4674. this.children[ i ].traverseVisible( callback );
  4675. }
  4676. },
  4677. traverseAncestors: function ( callback ) {
  4678. if ( this.parent ) {
  4679. callback( this.parent );
  4680. this.parent.traverseAncestors( callback );
  4681. }
  4682. },
  4683. updateMatrix: function () {
  4684. this.matrix.compose( this.position, this.quaternion, this.scale );
  4685. this.matrixWorldNeedsUpdate = true;
  4686. },
  4687. updateMatrixWorld: function ( force ) {
  4688. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4689. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4690. if ( this.parent === undefined ) {
  4691. this.matrixWorld.copy( this.matrix );
  4692. } else {
  4693. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4694. }
  4695. this.matrixWorldNeedsUpdate = false;
  4696. force = true;
  4697. }
  4698. // update children
  4699. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4700. this.children[ i ].updateMatrixWorld( force );
  4701. }
  4702. },
  4703. toJSON: function ( meta ) {
  4704. var isRootObject = ( meta === undefined );
  4705. var data = {};
  4706. // meta is a hash used to collect geometries, materials.
  4707. // not providing it implies that this is the root object
  4708. // being serialized.
  4709. if ( isRootObject ) {
  4710. // initialize meta obj
  4711. meta = {
  4712. geometries: {},
  4713. materials: {},
  4714. textures: {},
  4715. images: {}
  4716. };
  4717. data.metadata = {
  4718. version: 4.4,
  4719. type: 'Object',
  4720. generator: 'Object3D.toJSON'
  4721. };
  4722. }
  4723. // standard Object3D serialization
  4724. data.uuid = this.uuid;
  4725. data.type = this.type;
  4726. if ( this.name !== '' ) data.name = this.name;
  4727. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  4728. if ( this.visible !== true ) data.visible = this.visible;
  4729. data.matrix = this.matrix.toArray();
  4730. if ( this.children.length > 0 ) {
  4731. data.children = [];
  4732. for ( var i = 0; i < this.children.length; i ++ ) {
  4733. data.children.push( this.children[ i ].toJSON( meta ).object );
  4734. }
  4735. }
  4736. var output = {};
  4737. if ( isRootObject ) {
  4738. var geometries = extractFromCache( meta.geometries );
  4739. var materials = extractFromCache( meta.materials );
  4740. var textures = extractFromCache( meta.textures );
  4741. var images = extractFromCache( meta.images );
  4742. if ( geometries.length > 0 ) output.geometries = geometries;
  4743. if ( materials.length > 0 ) output.materials = materials;
  4744. if ( textures.length > 0 ) output.textures = textures;
  4745. if ( images.length > 0 ) output.images = images;
  4746. }
  4747. output.object = data;
  4748. return output;
  4749. // extract data from the cache hash
  4750. // remove metadata on each item
  4751. // and return as array
  4752. function extractFromCache ( cache ) {
  4753. var values = [];
  4754. for ( var key in cache ) {
  4755. var data = cache[ key ];
  4756. delete data.metadata;
  4757. values.push( data );
  4758. }
  4759. return values;
  4760. }
  4761. },
  4762. clone: function ( object, recursive ) {
  4763. if ( object === undefined ) object = new THREE.Object3D();
  4764. if ( recursive === undefined ) recursive = true;
  4765. object.name = this.name;
  4766. object.up.copy( this.up );
  4767. object.position.copy( this.position );
  4768. object.quaternion.copy( this.quaternion );
  4769. object.scale.copy( this.scale );
  4770. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4771. object.matrix.copy( this.matrix );
  4772. object.matrixWorld.copy( this.matrixWorld );
  4773. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4774. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4775. object.visible = this.visible;
  4776. object.castShadow = this.castShadow;
  4777. object.receiveShadow = this.receiveShadow;
  4778. object.frustumCulled = this.frustumCulled;
  4779. object.renderOrder = this.renderOrder;
  4780. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4781. if ( recursive === true ) {
  4782. for ( var i = 0; i < this.children.length; i ++ ) {
  4783. var child = this.children[ i ];
  4784. object.add( child.clone() );
  4785. }
  4786. }
  4787. return object;
  4788. }
  4789. };
  4790. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4791. THREE.Object3DIdCount = 0;
  4792. // File:src/core/Face3.js
  4793. /**
  4794. * @author mrdoob / http://mrdoob.com/
  4795. * @author alteredq / http://alteredqualia.com/
  4796. */
  4797. THREE.Face3 = function ( a, b, c, normal, color ) {
  4798. this.a = a;
  4799. this.b = b;
  4800. this.c = c;
  4801. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4802. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  4803. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4804. this.vertexColors = Array.isArray( color ) ? color : [];
  4805. this.vertexTangents = [];
  4806. };
  4807. THREE.Face3.prototype = {
  4808. constructor: THREE.Face3,
  4809. clone: function () {
  4810. var face = new THREE.Face3( this.a, this.b, this.c );
  4811. face.normal.copy( this.normal );
  4812. face.color.copy( this.color );
  4813. for ( var i = 0, il = this.vertexNormals.length; i < il; i ++ ) {
  4814. face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4815. }
  4816. for ( var i = 0, il = this.vertexColors.length; i < il; i ++ ) {
  4817. face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4818. }
  4819. for ( var i = 0, il = this.vertexTangents.length; i < il; i ++ ) {
  4820. face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4821. }
  4822. return face;
  4823. }
  4824. };
  4825. // File:src/core/Face4.js
  4826. /**
  4827. * @author mrdoob / http://mrdoob.com/
  4828. */
  4829. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4830. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  4831. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4832. };
  4833. // File:src/core/BufferAttribute.js
  4834. /**
  4835. * @author mrdoob / http://mrdoob.com/
  4836. */
  4837. THREE.BufferAttribute = function ( array, itemSize ) {
  4838. this.array = array;
  4839. this.itemSize = itemSize;
  4840. this.needsUpdate = false;
  4841. };
  4842. THREE.BufferAttribute.prototype = {
  4843. constructor: THREE.BufferAttribute,
  4844. get length () {
  4845. console.warn( 'THREE.BufferAttribute: .length has been renamed to .count.' );
  4846. return this.count;
  4847. },
  4848. get count() {
  4849. return this.array.length / this.itemSize;
  4850. },
  4851. copyAt: function ( index1, attribute, index2 ) {
  4852. index1 *= this.itemSize;
  4853. index2 *= attribute.itemSize;
  4854. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  4855. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  4856. }
  4857. return this;
  4858. },
  4859. copyArray: function ( array ) {
  4860. this.array.set( array );
  4861. return this;
  4862. },
  4863. copyColorsArray: function ( colors ) {
  4864. var array = this.array, offset = 0;
  4865. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  4866. var color = colors[ i ];
  4867. if ( color === undefined ) {
  4868. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  4869. color = new THREE.Color();
  4870. }
  4871. array[ offset ++ ] = color.r;
  4872. array[ offset ++ ] = color.g;
  4873. array[ offset ++ ] = color.b;
  4874. }
  4875. return this;
  4876. },
  4877. copyIndicesArray: function ( indices ) {
  4878. var array = this.array, offset = 0;
  4879. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  4880. var index = indices[ i ];
  4881. array[ offset ++ ] = index.a;
  4882. array[ offset ++ ] = index.b;
  4883. array[ offset ++ ] = index.c;
  4884. }
  4885. return this;
  4886. },
  4887. copyVector2sArray: function ( vectors ) {
  4888. var array = this.array, offset = 0;
  4889. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  4890. var vector = vectors[ i ];
  4891. if ( vector === undefined ) {
  4892. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  4893. vector = new THREE.Vector2();
  4894. }
  4895. array[ offset ++ ] = vector.x;
  4896. array[ offset ++ ] = vector.y;
  4897. }
  4898. return this;
  4899. },
  4900. copyVector3sArray: function ( vectors ) {
  4901. var array = this.array, offset = 0;
  4902. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  4903. var vector = vectors[ i ];
  4904. if ( vector === undefined ) {
  4905. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  4906. vector = new THREE.Vector3();
  4907. }
  4908. array[ offset ++ ] = vector.x;
  4909. array[ offset ++ ] = vector.y;
  4910. array[ offset ++ ] = vector.z;
  4911. }
  4912. return this;
  4913. },
  4914. copyVector4sArray: function ( vectors ) {
  4915. var array = this.array, offset = 0;
  4916. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  4917. var vector = vectors[ i ];
  4918. if ( vector === undefined ) {
  4919. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  4920. vector = new THREE.Vector4();
  4921. }
  4922. array[ offset ++ ] = vector.x;
  4923. array[ offset ++ ] = vector.y;
  4924. array[ offset ++ ] = vector.z;
  4925. array[ offset ++ ] = vector.w;
  4926. }
  4927. return this;
  4928. },
  4929. set: function ( value, offset ) {
  4930. if ( offset === undefined ) offset = 0;
  4931. this.array.set( value, offset );
  4932. return this;
  4933. },
  4934. getX: function ( index ) {
  4935. return this.array[ index * this.itemSize ];
  4936. },
  4937. setX: function ( index, x ) {
  4938. this.array[ index * this.itemSize ] = x;
  4939. return this;
  4940. },
  4941. getY: function ( index ) {
  4942. return this.array[ index * this.itemSize + 1 ];
  4943. },
  4944. setY: function ( index, y ) {
  4945. this.array[ index * this.itemSize + 1 ] = y;
  4946. return this;
  4947. },
  4948. getZ: function ( index ) {
  4949. return this.array[ index * this.itemSize + 2 ];
  4950. },
  4951. setZ: function ( index, z ) {
  4952. this.array[ index * this.itemSize + 2 ] = z;
  4953. return this;
  4954. },
  4955. getW: function ( index ) {
  4956. return this.array[ index * this.itemSize + 3 ];
  4957. },
  4958. setW: function ( index, w ) {
  4959. this.array[ index * this.itemSize + 3 ] = w;
  4960. return this;
  4961. },
  4962. setXY: function ( index, x, y ) {
  4963. index *= this.itemSize;
  4964. this.array[ index + 0 ] = x;
  4965. this.array[ index + 1 ] = y;
  4966. return this;
  4967. },
  4968. setXYZ: function ( index, x, y, z ) {
  4969. index *= this.itemSize;
  4970. this.array[ index + 0 ] = x;
  4971. this.array[ index + 1 ] = y;
  4972. this.array[ index + 2 ] = z;
  4973. return this;
  4974. },
  4975. setXYZW: function ( index, x, y, z, w ) {
  4976. index *= this.itemSize;
  4977. this.array[ index + 0 ] = x;
  4978. this.array[ index + 1 ] = y;
  4979. this.array[ index + 2 ] = z;
  4980. this.array[ index + 3 ] = w;
  4981. return this;
  4982. },
  4983. clone: function () {
  4984. return new THREE.BufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  4985. }
  4986. };
  4987. //
  4988. THREE.Int8Attribute = function ( array, itemSize ) {
  4989. return new THREE.BufferAttribute( new Int8Array( array ), itemSize );
  4990. };
  4991. THREE.Uint8Attribute = function ( array, itemSize ) {
  4992. return new THREE.BufferAttribute( new Uint8Array( array ), itemSize );
  4993. };
  4994. THREE.Uint8ClampedAttribute = function ( array, itemSize ) {
  4995. return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  4996. };
  4997. THREE.Int16Attribute = function ( array, itemSize ) {
  4998. return new THREE.BufferAttribute( new Int16Array( array ), itemSize );
  4999. };
  5000. THREE.Uint16Attribute = function ( array, itemSize ) {
  5001. return new THREE.BufferAttribute( new Uint16Array( array ), itemSize );
  5002. };
  5003. THREE.Int32Attribute = function ( array, itemSize ) {
  5004. return new THREE.BufferAttribute( new Int32Array( array ), itemSize );
  5005. };
  5006. THREE.Uint32Attribute = function ( array, itemSize ) {
  5007. return new THREE.BufferAttribute( new Uint32Array( array ), itemSize );
  5008. };
  5009. THREE.Float32Attribute = function ( array, itemSize ) {
  5010. return new THREE.BufferAttribute( new Float32Array( array ), itemSize );
  5011. };
  5012. THREE.Float64Attribute = function ( array, itemSize ) {
  5013. return new THREE.BufferAttribute( new Float64Array( array ), itemSize );
  5014. };
  5015. // File:src/core/DynamicBufferAttribute.js
  5016. /**
  5017. * @author benaadams / https://twitter.com/ben_a_adams
  5018. * @author mrdoob / http://mrdoob.com/
  5019. */
  5020. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  5021. THREE.BufferAttribute.call( this, array, itemSize );
  5022. this.updateRange = { offset: 0, count: -1 };
  5023. };
  5024. THREE.DynamicBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5025. THREE.DynamicBufferAttribute.prototype.constructor = THREE.DynamicBufferAttribute;
  5026. THREE.DynamicBufferAttribute.prototype.clone = function () {
  5027. return new THREE.DynamicBufferAttribute( new this.array.constructor( this.array ), this.itemSize );
  5028. };
  5029. // File:src/core/InstancedBufferAttribute.js
  5030. /**
  5031. * @author benaadams / https://twitter.com/ben_a_adams
  5032. */
  5033. THREE.InstancedBufferAttribute = function (array, itemSize, meshPerAttribute, dynamic) {
  5034. THREE.DynamicBufferAttribute.call( this, array, itemSize );
  5035. this.dynamic = dynamic || false;
  5036. this.meshPerAttribute = meshPerAttribute || 1;
  5037. };
  5038. THREE.InstancedBufferAttribute.prototype = Object.create( THREE.DynamicBufferAttribute.prototype );
  5039. THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute;
  5040. THREE.InstancedBufferAttribute.prototype.clone = function () {
  5041. return new THREE.InstancedBufferAttribute( new this.array.constructor( this.array ), this.itemSize, this.meshPerAttribute, this.dynamic );
  5042. };
  5043. // File:src/core/InterleavedBuffer.js
  5044. /**
  5045. * @author benaadams / https://twitter.com/ben_a_adams
  5046. */
  5047. THREE.InterleavedBuffer = function ( array, stride, dynamic ) {
  5048. this.array = array;
  5049. this.stride = stride;
  5050. this.needsUpdate = false;
  5051. this.dynamic = dynamic || false;
  5052. this.updateRange = { offset: 0, count: -1 };
  5053. };
  5054. THREE.InterleavedBuffer.prototype = {
  5055. constructor: THREE.InterleavedBuffer,
  5056. get length () {
  5057. return this.array.length;
  5058. },
  5059. copyAt: function ( index1, attribute, index2 ) {
  5060. index1 *= this.stride;
  5061. index2 *= attribute.stride;
  5062. for ( var i = 0, l = this.stride; i < l; i++ ) {
  5063. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5064. }
  5065. return this;
  5066. },
  5067. set: function ( value, offset ) {
  5068. if ( offset === undefined ) offset = 0;
  5069. this.array.set( value, offset );
  5070. return this;
  5071. },
  5072. clone: function () {
  5073. return new THREE.InterleavedBuffer( new this.array.constructor( this.array ), this.stride, this.dynamic );
  5074. }
  5075. };
  5076. // File:src/core/InstancedInterleavedBuffer.js
  5077. /**
  5078. * @author benaadams / https://twitter.com/ben_a_adams
  5079. */
  5080. THREE.InstancedInterleavedBuffer = function ( array, stride, dynamic, meshPerAttribute ) {
  5081. THREE.InterleavedBuffer.call( this, array, stride, dynamic );
  5082. this.meshPerAttribute = meshPerAttribute || 1;
  5083. };
  5084. THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype );
  5085. THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer;
  5086. THREE.InstancedInterleavedBuffer.prototype.clone = function () {
  5087. return new THREE.InstancedInterleavedBuffer( new this.array.constructor( this.array ), this.stride, this.dynamic, this.meshPerAttribute );
  5088. };
  5089. // File:src/core/InterleavedBufferAttribute.js
  5090. /**
  5091. * @author benaadams / https://twitter.com/ben_a_adams
  5092. */
  5093. THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) {
  5094. this.data = interleavedBuffer;
  5095. this.itemSize = itemSize;
  5096. this.offset = offset;
  5097. };
  5098. THREE.InterleavedBufferAttribute.prototype = {
  5099. constructor: THREE.InterleavedBufferAttribute,
  5100. get length() {
  5101. console.warn( 'THREE.InterleavedBufferAttribute: .length has been renamed to .count.' );
  5102. return this.count;
  5103. },
  5104. get count() {
  5105. return this.data.array.length / this.data.stride;
  5106. },
  5107. setX: function ( index, x ) {
  5108. this.data.array[ index * this.data.stride + this.offset ] = x;
  5109. return this;
  5110. },
  5111. setY: function ( index, y ) {
  5112. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  5113. return this;
  5114. },
  5115. setZ: function ( index, z ) {
  5116. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  5117. return this;
  5118. },
  5119. setW: function ( index, w ) {
  5120. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  5121. return this;
  5122. },
  5123. getX: function ( index ) {
  5124. return this.data.array[ index * this.data.stride + this.offset ];
  5125. },
  5126. getY: function ( index ) {
  5127. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  5128. },
  5129. getZ: function ( index ) {
  5130. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  5131. },
  5132. getW: function ( index ) {
  5133. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  5134. },
  5135. setXY: function ( index, x, y ) {
  5136. index = index * this.data.stride + this.offset;
  5137. this.data.array[ index + 0 ] = x;
  5138. this.data.array[ index + 1 ] = y;
  5139. return this;
  5140. },
  5141. setXYZ: function ( index, x, y, z ) {
  5142. index = index * this.data.stride + this.offset;
  5143. this.data.array[ index + 0 ] = x;
  5144. this.data.array[ index + 1 ] = y;
  5145. this.data.array[ index + 2 ] = z;
  5146. return this;
  5147. },
  5148. setXYZW: function ( index, x, y, z, w ) {
  5149. index = index * this.data.stride + this.offset;
  5150. this.data.array[ index + 0 ] = x;
  5151. this.data.array[ index + 1 ] = y;
  5152. this.data.array[ index + 2 ] = z;
  5153. this.data.array[ index + 3 ] = w;
  5154. return this;
  5155. }
  5156. };
  5157. // File:src/core/Geometry.js
  5158. /**
  5159. * @author mrdoob / http://mrdoob.com/
  5160. * @author kile / http://kile.stravaganza.org/
  5161. * @author alteredq / http://alteredqualia.com/
  5162. * @author mikael emtinger / http://gomo.se/
  5163. * @author zz85 / http://www.lab4games.net/zz85/blog
  5164. * @author bhouston / http://exocortex.com
  5165. */
  5166. THREE.Geometry = function () {
  5167. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5168. this.uuid = THREE.Math.generateUUID();
  5169. this.name = '';
  5170. this.type = 'Geometry';
  5171. this.vertices = [];
  5172. this.colors = [];
  5173. this.faces = [];
  5174. this.faceVertexUvs = [ [] ];
  5175. this.morphTargets = [];
  5176. this.morphColors = [];
  5177. this.morphNormals = [];
  5178. this.skinWeights = [];
  5179. this.skinIndices = [];
  5180. this.lineDistances = [];
  5181. this.boundingBox = null;
  5182. this.boundingSphere = null;
  5183. this.hasTangents = false;
  5184. // update flags
  5185. this.verticesNeedUpdate = false;
  5186. this.elementsNeedUpdate = false;
  5187. this.uvsNeedUpdate = false;
  5188. this.normalsNeedUpdate = false;
  5189. this.tangentsNeedUpdate = false;
  5190. this.colorsNeedUpdate = false;
  5191. this.lineDistancesNeedUpdate = false;
  5192. };
  5193. THREE.Geometry.prototype = {
  5194. constructor: THREE.Geometry,
  5195. applyMatrix: function ( matrix ) {
  5196. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5197. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5198. var vertex = this.vertices[ i ];
  5199. vertex.applyMatrix4( matrix );
  5200. }
  5201. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5202. var face = this.faces[ i ];
  5203. face.normal.applyMatrix3( normalMatrix ).normalize();
  5204. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5205. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5206. }
  5207. }
  5208. if ( this.boundingBox !== null ) {
  5209. this.computeBoundingBox();
  5210. }
  5211. if ( this.boundingSphere !== null ) {
  5212. this.computeBoundingSphere();
  5213. }
  5214. this.verticesNeedUpdate = true;
  5215. this.normalsNeedUpdate = true;
  5216. },
  5217. fromBufferGeometry: function ( geometry ) {
  5218. var scope = this;
  5219. var attributes = geometry.attributes;
  5220. var vertices = attributes.position.array;
  5221. var indices = attributes.index !== undefined ? attributes.index.array : undefined;
  5222. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5223. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5224. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5225. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  5226. var tangents = attributes.tangent !== undefined ? attributes.tangent.array : undefined;
  5227. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  5228. if ( tangents !== undefined ) this.hasTangents = true;
  5229. var tempNormals = [];
  5230. var tempUVs = [];
  5231. var tempUVs2 = [];
  5232. var tempTangents = [];
  5233. for ( var i = 0, j = 0, k = 0; i < vertices.length; i += 3, j += 2, k += 4 ) {
  5234. scope.vertices.push( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  5235. if ( normals !== undefined ) {
  5236. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5237. }
  5238. if ( colors !== undefined ) {
  5239. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5240. }
  5241. if ( uvs !== undefined ) {
  5242. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5243. }
  5244. if ( uvs2 !== undefined ) {
  5245. tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  5246. }
  5247. if ( tangents !== undefined ) {
  5248. tempTangents.push( new THREE.Vector4( tangents[ k ], tangents[ k + 1 ], tangents[ k + 2 ], tangents[ k + 3 ] ) );
  5249. }
  5250. }
  5251. var addFace = function ( a, b, c ) {
  5252. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5253. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5254. var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors );
  5255. scope.faces.push( face );
  5256. if ( uvs !== undefined ) {
  5257. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5258. }
  5259. if ( uvs2 !== undefined ) {
  5260. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  5261. }
  5262. if ( tangents !== undefined ) {
  5263. face.vertexTangents.push( tempTangents[ a ].clone(), tempTangents[ b ].clone(), tempTangents[ c ].clone() );
  5264. }
  5265. };
  5266. if ( indices !== undefined ) {
  5267. var drawcalls = geometry.drawcalls;
  5268. if ( drawcalls.length > 0 ) {
  5269. for ( var i = 0; i < drawcalls.length; i ++ ) {
  5270. var drawcall = drawcalls[ i ];
  5271. var start = drawcall.start;
  5272. var count = drawcall.count;
  5273. var index = drawcall.index;
  5274. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5275. addFace( index + indices[ j ], index + indices[ j + 1 ], index + indices[ j + 2 ] );
  5276. }
  5277. }
  5278. } else {
  5279. for ( var i = 0; i < indices.length; i += 3 ) {
  5280. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5281. }
  5282. }
  5283. } else {
  5284. for ( var i = 0; i < vertices.length / 3; i += 3 ) {
  5285. addFace( i, i + 1, i + 2 );
  5286. }
  5287. }
  5288. this.computeFaceNormals();
  5289. if ( geometry.boundingBox !== null ) {
  5290. this.boundingBox = geometry.boundingBox.clone();
  5291. }
  5292. if ( geometry.boundingSphere !== null ) {
  5293. this.boundingSphere = geometry.boundingSphere.clone();
  5294. }
  5295. return this;
  5296. },
  5297. center: function () {
  5298. this.computeBoundingBox();
  5299. var offset = this.boundingBox.center().negate();
  5300. this.applyMatrix( new THREE.Matrix4().setPosition( offset ) );
  5301. return offset;
  5302. },
  5303. normalize: function () {
  5304. this.computeBoundingSphere();
  5305. var center = this.boundingSphere.center;
  5306. var radius = this.boundingSphere.radius;
  5307. var s = radius === 0 ? 1 : 1.0 / radius;
  5308. var matrix = new THREE.Matrix4();
  5309. matrix.set(
  5310. s, 0, 0, -s * center.x,
  5311. 0, s, 0, -s * center.y,
  5312. 0, 0, s, -s * center.z,
  5313. 0, 0, 0, 1
  5314. );
  5315. this.applyMatrix( matrix );
  5316. return this;
  5317. },
  5318. computeFaceNormals: function () {
  5319. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5320. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5321. var face = this.faces[ f ];
  5322. var vA = this.vertices[ face.a ];
  5323. var vB = this.vertices[ face.b ];
  5324. var vC = this.vertices[ face.c ];
  5325. cb.subVectors( vC, vB );
  5326. ab.subVectors( vA, vB );
  5327. cb.cross( ab );
  5328. cb.normalize();
  5329. face.normal.copy( cb );
  5330. }
  5331. },
  5332. computeVertexNormals: function ( areaWeighted ) {
  5333. var v, vl, f, fl, face, vertices;
  5334. vertices = new Array( this.vertices.length );
  5335. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5336. vertices[ v ] = new THREE.Vector3();
  5337. }
  5338. if ( areaWeighted ) {
  5339. // vertex normals weighted by triangle areas
  5340. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5341. var vA, vB, vC;
  5342. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5343. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5344. face = this.faces[ f ];
  5345. vA = this.vertices[ face.a ];
  5346. vB = this.vertices[ face.b ];
  5347. vC = this.vertices[ face.c ];
  5348. cb.subVectors( vC, vB );
  5349. ab.subVectors( vA, vB );
  5350. cb.cross( ab );
  5351. vertices[ face.a ].add( cb );
  5352. vertices[ face.b ].add( cb );
  5353. vertices[ face.c ].add( cb );
  5354. }
  5355. } else {
  5356. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5357. face = this.faces[ f ];
  5358. vertices[ face.a ].add( face.normal );
  5359. vertices[ face.b ].add( face.normal );
  5360. vertices[ face.c ].add( face.normal );
  5361. }
  5362. }
  5363. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5364. vertices[ v ].normalize();
  5365. }
  5366. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5367. face = this.faces[ f ];
  5368. var vertexNormals = face.vertexNormals;
  5369. if ( vertexNormals.length === 3 ) {
  5370. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5371. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5372. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5373. } else {
  5374. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5375. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5376. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5377. }
  5378. }
  5379. },
  5380. computeMorphNormals: function () {
  5381. var i, il, f, fl, face;
  5382. // save original normals
  5383. // - create temp variables on first access
  5384. // otherwise just copy (for faster repeated calls)
  5385. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5386. face = this.faces[ f ];
  5387. if ( ! face.__originalFaceNormal ) {
  5388. face.__originalFaceNormal = face.normal.clone();
  5389. } else {
  5390. face.__originalFaceNormal.copy( face.normal );
  5391. }
  5392. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5393. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5394. if ( ! face.__originalVertexNormals[ i ] ) {
  5395. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5396. } else {
  5397. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5398. }
  5399. }
  5400. }
  5401. // use temp geometry to compute face and vertex normals for each morph
  5402. var tmpGeo = new THREE.Geometry();
  5403. tmpGeo.faces = this.faces;
  5404. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5405. // create on first access
  5406. if ( ! this.morphNormals[ i ] ) {
  5407. this.morphNormals[ i ] = {};
  5408. this.morphNormals[ i ].faceNormals = [];
  5409. this.morphNormals[ i ].vertexNormals = [];
  5410. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5411. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5412. var faceNormal, vertexNormals;
  5413. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5414. faceNormal = new THREE.Vector3();
  5415. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5416. dstNormalsFace.push( faceNormal );
  5417. dstNormalsVertex.push( vertexNormals );
  5418. }
  5419. }
  5420. var morphNormals = this.morphNormals[ i ];
  5421. // set vertices to morph target
  5422. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5423. // compute morph normals
  5424. tmpGeo.computeFaceNormals();
  5425. tmpGeo.computeVertexNormals();
  5426. // store morph normals
  5427. var faceNormal, vertexNormals;
  5428. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5429. face = this.faces[ f ];
  5430. faceNormal = morphNormals.faceNormals[ f ];
  5431. vertexNormals = morphNormals.vertexNormals[ f ];
  5432. faceNormal.copy( face.normal );
  5433. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5434. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5435. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5436. }
  5437. }
  5438. // restore original normals
  5439. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5440. face = this.faces[ f ];
  5441. face.normal = face.__originalFaceNormal;
  5442. face.vertexNormals = face.__originalVertexNormals;
  5443. }
  5444. },
  5445. computeTangents: function () {
  5446. // based on http://www.terathon.com/code/tangent.html
  5447. // tangents go to vertices
  5448. var f, fl, v, vl, i, vertexIndex,
  5449. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5450. x1, x2, y1, y2, z1, z2,
  5451. s1, s2, t1, t2, r, t, test,
  5452. tan1 = [], tan2 = [],
  5453. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5454. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5455. n = new THREE.Vector3(), w;
  5456. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5457. tan1[ v ] = new THREE.Vector3();
  5458. tan2[ v ] = new THREE.Vector3();
  5459. }
  5460. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5461. vA = context.vertices[ a ];
  5462. vB = context.vertices[ b ];
  5463. vC = context.vertices[ c ];
  5464. uvA = uv[ ua ];
  5465. uvB = uv[ ub ];
  5466. uvC = uv[ uc ];
  5467. x1 = vB.x - vA.x;
  5468. x2 = vC.x - vA.x;
  5469. y1 = vB.y - vA.y;
  5470. y2 = vC.y - vA.y;
  5471. z1 = vB.z - vA.z;
  5472. z2 = vC.z - vA.z;
  5473. s1 = uvB.x - uvA.x;
  5474. s2 = uvC.x - uvA.x;
  5475. t1 = uvB.y - uvA.y;
  5476. t2 = uvC.y - uvA.y;
  5477. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5478. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5479. ( t2 * y1 - t1 * y2 ) * r,
  5480. ( t2 * z1 - t1 * z2 ) * r );
  5481. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5482. ( s1 * y2 - s2 * y1 ) * r,
  5483. ( s1 * z2 - s2 * z1 ) * r );
  5484. tan1[ a ].add( sdir );
  5485. tan1[ b ].add( sdir );
  5486. tan1[ c ].add( sdir );
  5487. tan2[ a ].add( tdir );
  5488. tan2[ b ].add( tdir );
  5489. tan2[ c ].add( tdir );
  5490. }
  5491. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5492. face = this.faces[ f ];
  5493. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5494. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5495. }
  5496. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5497. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5498. face = this.faces[ f ];
  5499. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i ++ ) {
  5500. n.copy( face.vertexNormals[ i ] );
  5501. vertexIndex = face[ faceIndex[ i ] ];
  5502. t = tan1[ vertexIndex ];
  5503. // Gram-Schmidt orthogonalize
  5504. tmp.copy( t );
  5505. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5506. // Calculate handedness
  5507. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5508. test = tmp2.dot( tan2[ vertexIndex ] );
  5509. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  5510. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5511. }
  5512. }
  5513. this.hasTangents = true;
  5514. },
  5515. computeLineDistances: function () {
  5516. var d = 0;
  5517. var vertices = this.vertices;
  5518. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5519. if ( i > 0 ) {
  5520. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5521. }
  5522. this.lineDistances[ i ] = d;
  5523. }
  5524. },
  5525. computeBoundingBox: function () {
  5526. if ( this.boundingBox === null ) {
  5527. this.boundingBox = new THREE.Box3();
  5528. }
  5529. this.boundingBox.setFromPoints( this.vertices );
  5530. },
  5531. computeBoundingSphere: function () {
  5532. if ( this.boundingSphere === null ) {
  5533. this.boundingSphere = new THREE.Sphere();
  5534. }
  5535. this.boundingSphere.setFromPoints( this.vertices );
  5536. },
  5537. merge: function ( geometry, matrix ) {
  5538. if ( geometry instanceof THREE.Geometry === false ) {
  5539. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  5540. return;
  5541. }
  5542. var normalMatrix,
  5543. vertexOffset = this.vertices.length,
  5544. vertices1 = this.vertices,
  5545. vertices2 = geometry.vertices,
  5546. faces1 = this.faces,
  5547. faces2 = geometry.faces,
  5548. uvs1 = this.faceVertexUvs[ 0 ],
  5549. uvs2 = geometry.faceVertexUvs[ 0 ];
  5550. if ( matrix !== undefined ) {
  5551. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5552. }
  5553. // vertices
  5554. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  5555. var vertex = vertices2[ i ];
  5556. var vertexCopy = vertex.clone();
  5557. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  5558. vertices1.push( vertexCopy );
  5559. }
  5560. // faces
  5561. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  5562. var face = faces2[ i ], faceCopy, normal, color,
  5563. faceVertexNormals = face.vertexNormals,
  5564. faceVertexColors = face.vertexColors;
  5565. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  5566. faceCopy.normal.copy( face.normal );
  5567. if ( normalMatrix !== undefined ) {
  5568. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  5569. }
  5570. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  5571. normal = faceVertexNormals[ j ].clone();
  5572. if ( normalMatrix !== undefined ) {
  5573. normal.applyMatrix3( normalMatrix ).normalize();
  5574. }
  5575. faceCopy.vertexNormals.push( normal );
  5576. }
  5577. faceCopy.color.copy( face.color );
  5578. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  5579. color = faceVertexColors[ j ];
  5580. faceCopy.vertexColors.push( color.clone() );
  5581. }
  5582. faces1.push( faceCopy );
  5583. }
  5584. // uvs
  5585. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  5586. var uv = uvs2[ i ], uvCopy = [];
  5587. if ( uv === undefined ) {
  5588. continue;
  5589. }
  5590. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5591. uvCopy.push( uv[ j ].clone() );
  5592. }
  5593. uvs1.push( uvCopy );
  5594. }
  5595. },
  5596. mergeMesh: function ( mesh ) {
  5597. if ( mesh instanceof THREE.Mesh === false ) {
  5598. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  5599. return;
  5600. }
  5601. mesh.matrixAutoUpdate && mesh.updateMatrix();
  5602. this.merge( mesh.geometry, mesh.matrix );
  5603. },
  5604. /*
  5605. * Checks for duplicate vertices with hashmap.
  5606. * Duplicated vertices are removed
  5607. * and faces' vertices are updated.
  5608. */
  5609. mergeVertices: function () {
  5610. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  5611. var unique = [], changes = [];
  5612. var v, key;
  5613. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  5614. var precision = Math.pow( 10, precisionPoints );
  5615. var i, il, face;
  5616. var indices, j, jl;
  5617. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5618. v = this.vertices[ i ];
  5619. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5620. if ( verticesMap[ key ] === undefined ) {
  5621. verticesMap[ key ] = i;
  5622. unique.push( this.vertices[ i ] );
  5623. changes[ i ] = unique.length - 1;
  5624. } else {
  5625. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5626. changes[ i ] = changes[ verticesMap[ key ] ];
  5627. }
  5628. }
  5629. // if faces are completely degenerate after merging vertices, we
  5630. // have to remove them from the geometry.
  5631. var faceIndicesToRemove = [];
  5632. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  5633. face = this.faces[ i ];
  5634. face.a = changes[ face.a ];
  5635. face.b = changes[ face.b ];
  5636. face.c = changes[ face.c ];
  5637. indices = [ face.a, face.b, face.c ];
  5638. var dupIndex = - 1;
  5639. // if any duplicate vertices are found in a Face3
  5640. // we have to remove the face as nothing can be saved
  5641. for ( var n = 0; n < 3; n ++ ) {
  5642. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  5643. dupIndex = n;
  5644. faceIndicesToRemove.push( i );
  5645. break;
  5646. }
  5647. }
  5648. }
  5649. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5650. var idx = faceIndicesToRemove[ i ];
  5651. this.faces.splice( idx, 1 );
  5652. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5653. this.faceVertexUvs[ j ].splice( idx, 1 );
  5654. }
  5655. }
  5656. // Use unique set of vertices
  5657. var diff = this.vertices.length - unique.length;
  5658. this.vertices = unique;
  5659. return diff;
  5660. },
  5661. toJSON: function () {
  5662. var data = {
  5663. metadata: {
  5664. version: 4.4,
  5665. type: 'Geometry',
  5666. generator: 'Geometry.toJSON'
  5667. }
  5668. };
  5669. // standard Geometry serialization
  5670. data.uuid = this.uuid;
  5671. data.type = this.type;
  5672. if ( this.name !== '' ) data.name = this.name;
  5673. if ( this.parameters !== undefined ) {
  5674. var parameters = this.parameters;
  5675. for ( var key in parameters ) {
  5676. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  5677. }
  5678. return data;
  5679. }
  5680. var vertices = [];
  5681. for ( var i = 0; i < this.vertices.length; i ++ ) {
  5682. var vertex = this.vertices[ i ];
  5683. vertices.push( vertex.x, vertex.y, vertex.z );
  5684. }
  5685. var faces = [];
  5686. var normals = [];
  5687. var normalsHash = {};
  5688. var colors = [];
  5689. var colorsHash = {};
  5690. var uvs = [];
  5691. var uvsHash = {};
  5692. for ( var i = 0; i < this.faces.length; i ++ ) {
  5693. var face = this.faces[ i ];
  5694. var hasMaterial = false; // face.materialIndex !== undefined;
  5695. var hasFaceUv = false; // deprecated
  5696. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  5697. var hasFaceNormal = face.normal.length() > 0;
  5698. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  5699. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  5700. var hasFaceVertexColor = face.vertexColors.length > 0;
  5701. var faceType = 0;
  5702. faceType = setBit( faceType, 0, 0 );
  5703. faceType = setBit( faceType, 1, hasMaterial );
  5704. faceType = setBit( faceType, 2, hasFaceUv );
  5705. faceType = setBit( faceType, 3, hasFaceVertexUv );
  5706. faceType = setBit( faceType, 4, hasFaceNormal );
  5707. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  5708. faceType = setBit( faceType, 6, hasFaceColor );
  5709. faceType = setBit( faceType, 7, hasFaceVertexColor );
  5710. faces.push( faceType );
  5711. faces.push( face.a, face.b, face.c );
  5712. if ( hasFaceVertexUv ) {
  5713. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  5714. faces.push(
  5715. getUvIndex( faceVertexUvs[ 0 ] ),
  5716. getUvIndex( faceVertexUvs[ 1 ] ),
  5717. getUvIndex( faceVertexUvs[ 2 ] )
  5718. );
  5719. }
  5720. if ( hasFaceNormal ) {
  5721. faces.push( getNormalIndex( face.normal ) );
  5722. }
  5723. if ( hasFaceVertexNormal ) {
  5724. var vertexNormals = face.vertexNormals;
  5725. faces.push(
  5726. getNormalIndex( vertexNormals[ 0 ] ),
  5727. getNormalIndex( vertexNormals[ 1 ] ),
  5728. getNormalIndex( vertexNormals[ 2 ] )
  5729. );
  5730. }
  5731. if ( hasFaceColor ) {
  5732. faces.push( getColorIndex( face.color ) );
  5733. }
  5734. if ( hasFaceVertexColor ) {
  5735. var vertexColors = face.vertexColors;
  5736. faces.push(
  5737. getColorIndex( vertexColors[ 0 ] ),
  5738. getColorIndex( vertexColors[ 1 ] ),
  5739. getColorIndex( vertexColors[ 2 ] )
  5740. );
  5741. }
  5742. }
  5743. function setBit( value, position, enabled ) {
  5744. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position) );
  5745. }
  5746. function getNormalIndex( normal ) {
  5747. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  5748. if ( normalsHash[ hash ] !== undefined ) {
  5749. return normalsHash[ hash ];
  5750. }
  5751. normalsHash[ hash ] = normals.length / 3;
  5752. normals.push( normal.x, normal.y, normal.z );
  5753. return normalsHash[ hash ];
  5754. }
  5755. function getColorIndex( color ) {
  5756. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  5757. if ( colorsHash[ hash ] !== undefined ) {
  5758. return colorsHash[ hash ];
  5759. }
  5760. colorsHash[ hash ] = colors.length;
  5761. colors.push( color.getHex() );
  5762. return colorsHash[ hash ];
  5763. }
  5764. function getUvIndex( uv ) {
  5765. var hash = uv.x.toString() + uv.y.toString();
  5766. if ( uvsHash[ hash ] !== undefined ) {
  5767. return uvsHash[ hash ];
  5768. }
  5769. uvsHash[ hash ] = uvs.length / 2;
  5770. uvs.push( uv.x, uv.y );
  5771. return uvsHash[ hash ];
  5772. }
  5773. data.data = {};
  5774. data.data.vertices = vertices;
  5775. data.data.normals = normals;
  5776. if ( colors.length > 0 ) data.data.colors = colors;
  5777. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  5778. data.data.faces = faces;
  5779. return data;
  5780. },
  5781. clone: function () {
  5782. var geometry = new THREE.Geometry();
  5783. var vertices = this.vertices;
  5784. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5785. geometry.vertices.push( vertices[ i ].clone() );
  5786. }
  5787. var faces = this.faces;
  5788. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5789. geometry.faces.push( faces[ i ].clone() );
  5790. }
  5791. for ( var i = 0, il = this.faceVertexUvs.length; i < il; i ++ ) {
  5792. var faceVertexUvs = this.faceVertexUvs[ i ];
  5793. if ( geometry.faceVertexUvs[ i ] === undefined ) {
  5794. geometry.faceVertexUvs[ i ] = [];
  5795. }
  5796. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  5797. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  5798. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  5799. var uv = uvs[ k ];
  5800. uvsCopy.push( uv.clone() );
  5801. }
  5802. geometry.faceVertexUvs[ i ].push( uvsCopy );
  5803. }
  5804. }
  5805. return geometry;
  5806. },
  5807. dispose: function () {
  5808. this.dispatchEvent( { type: 'dispose' } );
  5809. },
  5810. // Backwards compatibility
  5811. set groupsNeedUpdate ( value ) {
  5812. if ( value === true ) this.dispose();
  5813. }
  5814. };
  5815. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5816. THREE.GeometryIdCount = 0;
  5817. // File:src/core/DirectGeometry.js
  5818. /**
  5819. * @author mrdoob / http://mrdoob.com/
  5820. */
  5821. THREE.DirectGeometry = function () {
  5822. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5823. this.uuid = THREE.Math.generateUUID();
  5824. this.name = '';
  5825. this.type = 'DirectGeometry';
  5826. this.indices = [];
  5827. this.vertices = [];
  5828. this.colors = [];
  5829. this.normals = [];
  5830. this.colors = [];
  5831. this.uvs = [];
  5832. this.uvs2 = [];
  5833. this.tangents = [];
  5834. this.morphTargets = [];
  5835. this.morphColors = [];
  5836. this.morphNormals = [];
  5837. this.skinWeights = [];
  5838. this.skinIndices = [];
  5839. // this.lineDistances = [];
  5840. this.boundingBox = null;
  5841. this.boundingSphere = null;
  5842. // update flags
  5843. this.verticesNeedUpdate = false;
  5844. this.normalsNeedUpdate = false;
  5845. this.colorsNeedUpdate = false;
  5846. this.uvsNeedUpdate = false;
  5847. this.tangentsNeedUpdate = false;
  5848. };
  5849. THREE.DirectGeometry.prototype = {
  5850. constructor: THREE.DirectGeometry,
  5851. computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox,
  5852. computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere,
  5853. computeFaceNormals: function () {
  5854. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  5855. return this;
  5856. },
  5857. computeVertexNormals: function () {
  5858. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  5859. return this;
  5860. },
  5861. computeTangents: function () {
  5862. console.warn( 'THREE.DirectGeometry: computeTangents() is not a method of this type of geometry.' );
  5863. return this;
  5864. },
  5865. fromGeometry: function ( geometry ) {
  5866. var faces = geometry.faces;
  5867. var vertices = geometry.vertices;
  5868. var faceVertexUvs = geometry.faceVertexUvs;
  5869. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  5870. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  5871. var hasTangents = geometry.hasTangents;
  5872. // morphs
  5873. var morphTargets = geometry.morphTargets;
  5874. var morphTargetsLength = morphTargets.length;
  5875. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  5876. this.morphTargets[ i ] = [];
  5877. }
  5878. var morphNormals = geometry.morphNormals;
  5879. var morphNormalsLength = morphNormals.length;
  5880. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  5881. this.morphNormals[ i ] = [];
  5882. }
  5883. var morphColors = geometry.morphColors;
  5884. var morphColorsLength = morphColors.length;
  5885. for ( var i = 0; i < morphColorsLength; i ++ ) {
  5886. this.morphColors[ i ] = [];
  5887. }
  5888. // skins
  5889. var skinIndices = geometry.skinIndices;
  5890. var skinWeights = geometry.skinWeights;
  5891. var hasSkinIndices = skinIndices.length === vertices.length;
  5892. var hasSkinWeights = skinWeights.length === vertices.length;
  5893. //
  5894. for ( var i = 0; i < faces.length; i ++ ) {
  5895. var face = faces[ i ];
  5896. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  5897. var vertexNormals = face.vertexNormals;
  5898. if ( vertexNormals.length === 3 ) {
  5899. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  5900. } else {
  5901. var normal = face.normal;
  5902. this.normals.push( normal, normal, normal );
  5903. }
  5904. var vertexColors = face.vertexColors;
  5905. if ( vertexColors.length === 3 ) {
  5906. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  5907. } else {
  5908. var color = face.color;
  5909. this.colors.push( color, color, color );
  5910. }
  5911. if ( hasFaceVertexUv === true ) {
  5912. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  5913. if ( vertexUvs !== undefined ) {
  5914. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  5915. } else {
  5916. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  5917. this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  5918. }
  5919. }
  5920. if ( hasFaceVertexUv2 === true ) {
  5921. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  5922. if ( vertexUvs !== undefined ) {
  5923. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  5924. } else {
  5925. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  5926. this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  5927. }
  5928. }
  5929. if ( hasTangents === true ) {
  5930. var vertexTangents = face.vertexTangents;
  5931. if ( vertexTangents.length === 3 ) {
  5932. this.tangents.push( vertexTangents[ 0 ], vertexTangents[ 1 ], vertexTangents[ 2 ] );
  5933. } else {
  5934. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined tangents ', i );
  5935. this.tangents.push( new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4() );
  5936. }
  5937. }
  5938. // morphs
  5939. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  5940. var morphTarget = morphTargets[ j ].vertices;
  5941. this.morphTargets[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  5942. }
  5943. /*
  5944. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  5945. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  5946. this.morphNormals[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  5947. }
  5948. for ( var j = 0; j < morphColorsLength; j ++ ) {
  5949. var morphColor = morphColors[ j ].colors;
  5950. this.morphColors[ j ].push( morphColor[ face.a ], morphColor[ face.b ], morphColor[ face.c ] );
  5951. }
  5952. */
  5953. // skins
  5954. if ( hasSkinIndices ) {
  5955. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  5956. }
  5957. if ( hasSkinWeights ) {
  5958. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  5959. }
  5960. }
  5961. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  5962. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  5963. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  5964. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  5965. this.tangentsNeedUpdate = geometry.tangentsNeedUpdate;
  5966. return this;
  5967. },
  5968. dispose: function () {
  5969. this.dispatchEvent( { type: 'dispose' } );
  5970. }
  5971. };
  5972. THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype );
  5973. // File:src/core/BufferGeometry.js
  5974. /**
  5975. * @author alteredq / http://alteredqualia.com/
  5976. * @author mrdoob / http://mrdoob.com/
  5977. */
  5978. THREE.BufferGeometry = function () {
  5979. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5980. this.uuid = THREE.Math.generateUUID();
  5981. this.name = '';
  5982. this.type = 'BufferGeometry';
  5983. this.attributes = {};
  5984. this.morphAttributes = [];
  5985. this.drawcalls = [];
  5986. this.offsets = this.drawcalls; // backwards compatibility
  5987. this.boundingBox = null;
  5988. this.boundingSphere = null;
  5989. };
  5990. THREE.BufferGeometry.prototype = {
  5991. constructor: THREE.BufferGeometry,
  5992. addAttribute: function ( name, attribute ) {
  5993. if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) {
  5994. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  5995. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5996. return;
  5997. }
  5998. this.attributes[ name ] = attribute;
  5999. },
  6000. getAttribute: function ( name ) {
  6001. return this.attributes[ name ];
  6002. },
  6003. addDrawCall: function ( start, count, indexOffset ) {
  6004. this.drawcalls.push( {
  6005. start: start,
  6006. count: count,
  6007. index: indexOffset !== undefined ? indexOffset : 0
  6008. } );
  6009. },
  6010. applyMatrix: function ( matrix ) {
  6011. var position = this.attributes.position;
  6012. if ( position !== undefined ) {
  6013. matrix.applyToVector3Array( position.array );
  6014. position.needsUpdate = true;
  6015. }
  6016. var normal = this.attributes.normal;
  6017. if ( normal !== undefined ) {
  6018. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6019. normalMatrix.applyToVector3Array( normal.array );
  6020. normal.needsUpdate = true;
  6021. }
  6022. if ( this.boundingBox !== null ) {
  6023. this.computeBoundingBox();
  6024. }
  6025. if ( this.boundingSphere !== null ) {
  6026. this.computeBoundingSphere();
  6027. }
  6028. },
  6029. copy: function ( geometry ) {
  6030. var attributes = geometry.attributes;
  6031. var offsets = geometry.offsets;
  6032. for ( var name in attributes ) {
  6033. var attribute = attributes[ name ];
  6034. this.addAttribute( name, attribute.clone() );
  6035. }
  6036. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  6037. var offset = offsets[ i ];
  6038. this.offsets.push( {
  6039. start: offset.start,
  6040. index: offset.index,
  6041. count: offset.count
  6042. } );
  6043. }
  6044. return this;
  6045. },
  6046. center: function () {
  6047. this.computeBoundingBox();
  6048. var offset = this.boundingBox.center().negate();
  6049. this.applyMatrix( new THREE.Matrix4().setPosition( offset ) );
  6050. return offset;
  6051. },
  6052. setFromObject: function ( object ) {
  6053. console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6054. var geometry = object.geometry;
  6055. var material = object.material;
  6056. if ( object instanceof THREE.PointCloud || object instanceof THREE.Line ) {
  6057. var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 );
  6058. var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 );
  6059. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6060. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6061. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6062. var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 );
  6063. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6064. }
  6065. if ( geometry.boundingSphere !== null ) {
  6066. this.boundingSphere = geometry.boundingSphere.clone();
  6067. }
  6068. if ( geometry.boundingBox !== null ) {
  6069. this.boundingBox = geometry.boundingBox.clone();
  6070. }
  6071. } else if ( object instanceof THREE.Mesh ) {
  6072. if ( geometry instanceof THREE.Geometry ) {
  6073. this.fromGeometry( geometry );
  6074. }
  6075. }
  6076. return this;
  6077. },
  6078. updateFromObject: function ( object ) {
  6079. var geometry = object.geometry;
  6080. if ( object instanceof THREE.Mesh ) {
  6081. var direct = geometry.__directGeometry;
  6082. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6083. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6084. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6085. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6086. direct.tangentsNeedUpdate = geometry.tangentsNeedUpdate;
  6087. geometry.verticesNeedUpdate = false;
  6088. geometry.normalsNeedUpdate = false;
  6089. geometry.colorsNeedUpdate = false;
  6090. geometry.uvsNeedUpdate = false;
  6091. geometry.tangentsNeedUpdate = false;
  6092. geometry = direct;
  6093. }
  6094. if ( geometry.verticesNeedUpdate === true ) {
  6095. var attribute = this.attributes.position;
  6096. if ( attribute !== undefined ) {
  6097. attribute.copyVector3sArray( geometry.vertices );
  6098. attribute.needsUpdate = true;
  6099. }
  6100. geometry.verticesNeedUpdate = false;
  6101. }
  6102. if ( geometry.normalsNeedUpdate === true ) {
  6103. var attribute = this.attributes.normal;
  6104. if ( attribute !== undefined ) {
  6105. attribute.copyVector3sArray( geometry.normals );
  6106. attribute.needsUpdate = true;
  6107. }
  6108. geometry.normalsNeedUpdate = false;
  6109. }
  6110. if ( geometry.colorsNeedUpdate === true ) {
  6111. var attribute = this.attributes.color;
  6112. if ( attribute !== undefined ) {
  6113. attribute.copyColorsArray( geometry.colors );
  6114. attribute.needsUpdate = true;
  6115. }
  6116. geometry.colorsNeedUpdate = false;
  6117. }
  6118. if ( geometry.tangentsNeedUpdate === true ) {
  6119. var attribute = this.attributes.tangent;
  6120. if ( attribute !== undefined ) {
  6121. attribute.copyVector4sArray( geometry.tangents );
  6122. attribute.needsUpdate = true;
  6123. }
  6124. geometry.tangentsNeedUpdate = false;
  6125. }
  6126. if ( geometry.lineDistancesNeedUpdate ) {
  6127. var attribute = this.attributes.lineDistance;
  6128. if ( attribute !== undefined ) {
  6129. attribute.copyArray( geometry.lineDistances );
  6130. attribute.needsUpdate = true;
  6131. }
  6132. geometry.lineDistancesNeedUpdate = false;
  6133. }
  6134. return this;
  6135. },
  6136. fromGeometry: function ( geometry ) {
  6137. geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry );
  6138. return this.fromDirectGeometry( geometry.__directGeometry );
  6139. },
  6140. fromDirectGeometry: function ( geometry ) {
  6141. if ( geometry.indices.length > 0 ) {
  6142. var indices = new Uint16Array( geometry.indices.length * 3 );
  6143. this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  6144. }
  6145. if ( geometry.vertices.length > 0 ) {
  6146. var positions = new Float32Array( geometry.vertices.length * 3 );
  6147. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6148. }
  6149. if ( geometry.normals.length > 0 ) {
  6150. var normals = new Float32Array( geometry.normals.length * 3 );
  6151. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6152. }
  6153. if ( geometry.colors.length > 0 ) {
  6154. var colors = new Float32Array( geometry.colors.length * 3 );
  6155. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6156. }
  6157. if ( geometry.uvs.length > 0 ) {
  6158. var uvs = new Float32Array( geometry.uvs.length * 2 );
  6159. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6160. }
  6161. if ( geometry.uvs2.length > 0 ) {
  6162. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6163. this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6164. }
  6165. if ( geometry.tangents.length > 0 ) {
  6166. var tangents = new Float32Array( geometry.tangents.length * 4 );
  6167. this.addAttribute( 'tangent', new THREE.BufferAttribute( tangents, 4 ).copyVector4sArray( geometry.tangents ) );
  6168. }
  6169. // morphs
  6170. if ( geometry.morphTargets.length > 0 ) {
  6171. var morphTargets = geometry.morphTargets;
  6172. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  6173. var morphTarget = morphTargets[ i ];
  6174. var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 );
  6175. this.morphAttributes.push( attribute.copyVector3sArray( morphTarget ) );
  6176. }
  6177. // TODO normals, colors
  6178. }
  6179. // skinning
  6180. if ( geometry.skinIndices.length > 0 ) {
  6181. var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 );
  6182. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6183. }
  6184. if ( geometry.skinWeights.length > 0 ) {
  6185. var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 );
  6186. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6187. }
  6188. //
  6189. if ( geometry.boundingSphere !== null ) {
  6190. this.boundingSphere = geometry.boundingSphere.clone();
  6191. }
  6192. if ( geometry.boundingBox !== null ) {
  6193. this.boundingBox = geometry.boundingBox.clone();
  6194. }
  6195. return this;
  6196. },
  6197. computeBoundingBox: function () {
  6198. var vector = new THREE.Vector3();
  6199. return function () {
  6200. if ( this.boundingBox === null ) {
  6201. this.boundingBox = new THREE.Box3();
  6202. }
  6203. var positions = this.attributes.position.array;
  6204. if ( positions ) {
  6205. var bb = this.boundingBox;
  6206. bb.makeEmpty();
  6207. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6208. vector.fromArray( positions, i );
  6209. bb.expandByPoint( vector );
  6210. }
  6211. }
  6212. if ( positions === undefined || positions.length === 0 ) {
  6213. this.boundingBox.min.set( 0, 0, 0 );
  6214. this.boundingBox.max.set( 0, 0, 0 );
  6215. }
  6216. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6217. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6218. }
  6219. };
  6220. }(),
  6221. computeBoundingSphere: function () {
  6222. var box = new THREE.Box3();
  6223. var vector = new THREE.Vector3();
  6224. return function () {
  6225. if ( this.boundingSphere === null ) {
  6226. this.boundingSphere = new THREE.Sphere();
  6227. }
  6228. var positions = this.attributes.position.array;
  6229. if ( positions ) {
  6230. box.makeEmpty();
  6231. var center = this.boundingSphere.center;
  6232. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6233. vector.fromArray( positions, i );
  6234. box.expandByPoint( vector );
  6235. }
  6236. box.center( center );
  6237. // hoping to find a boundingSphere with a radius smaller than the
  6238. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6239. var maxRadiusSq = 0;
  6240. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6241. vector.fromArray( positions, i );
  6242. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  6243. }
  6244. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6245. if ( isNaN( this.boundingSphere.radius ) ) {
  6246. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6247. }
  6248. }
  6249. };
  6250. }(),
  6251. computeFaceNormals: function () {
  6252. // backwards compatibility
  6253. },
  6254. computeVertexNormals: function () {
  6255. var attributes = this.attributes;
  6256. if ( attributes.position ) {
  6257. var positions = attributes.position.array;
  6258. if ( attributes.normal === undefined ) {
  6259. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  6260. } else {
  6261. // reset existing normals to zero
  6262. var normals = attributes.normal.array;
  6263. for ( var i = 0, il = normals.length; i < il; i ++ ) {
  6264. normals[ i ] = 0;
  6265. }
  6266. }
  6267. var normals = attributes.normal.array;
  6268. var vA, vB, vC,
  6269. pA = new THREE.Vector3(),
  6270. pB = new THREE.Vector3(),
  6271. pC = new THREE.Vector3(),
  6272. cb = new THREE.Vector3(),
  6273. ab = new THREE.Vector3();
  6274. // indexed elements
  6275. if ( attributes.index ) {
  6276. var indices = attributes.index.array;
  6277. var offsets = ( this.offsets.length > 0 ? this.offsets : [ { start: 0, count: indices.length, index: 0 } ] );
  6278. for ( var j = 0, jl = offsets.length; j < jl; ++ j ) {
  6279. var start = offsets[ j ].start;
  6280. var count = offsets[ j ].count;
  6281. var index = offsets[ j ].index;
  6282. for ( var i = start, il = start + count; i < il; i += 3 ) {
  6283. vA = ( index + indices[ i ] ) * 3;
  6284. vB = ( index + indices[ i + 1 ] ) * 3;
  6285. vC = ( index + indices[ i + 2 ] ) * 3;
  6286. pA.fromArray( positions, vA );
  6287. pB.fromArray( positions, vB );
  6288. pC.fromArray( positions, vC );
  6289. cb.subVectors( pC, pB );
  6290. ab.subVectors( pA, pB );
  6291. cb.cross( ab );
  6292. normals[ vA ] += cb.x;
  6293. normals[ vA + 1 ] += cb.y;
  6294. normals[ vA + 2 ] += cb.z;
  6295. normals[ vB ] += cb.x;
  6296. normals[ vB + 1 ] += cb.y;
  6297. normals[ vB + 2 ] += cb.z;
  6298. normals[ vC ] += cb.x;
  6299. normals[ vC + 1 ] += cb.y;
  6300. normals[ vC + 2 ] += cb.z;
  6301. }
  6302. }
  6303. } else {
  6304. // non-indexed elements (unconnected triangle soup)
  6305. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  6306. pA.fromArray( positions, i );
  6307. pB.fromArray( positions, i + 3 );
  6308. pC.fromArray( positions, i + 6 );
  6309. cb.subVectors( pC, pB );
  6310. ab.subVectors( pA, pB );
  6311. cb.cross( ab );
  6312. normals[ i ] = cb.x;
  6313. normals[ i + 1 ] = cb.y;
  6314. normals[ i + 2 ] = cb.z;
  6315. normals[ i + 3 ] = cb.x;
  6316. normals[ i + 4 ] = cb.y;
  6317. normals[ i + 5 ] = cb.z;
  6318. normals[ i + 6 ] = cb.x;
  6319. normals[ i + 7 ] = cb.y;
  6320. normals[ i + 8 ] = cb.z;
  6321. }
  6322. }
  6323. this.normalizeNormals();
  6324. attributes.normal.needsUpdate = true;
  6325. }
  6326. },
  6327. computeTangents: function () {
  6328. // based on http://www.terathon.com/code/tangent.html
  6329. // (per vertex tangents)
  6330. if ( this.attributes.index === undefined ||
  6331. this.attributes.position === undefined ||
  6332. this.attributes.normal === undefined ||
  6333. this.attributes.uv === undefined ) {
  6334. console.warn( 'THREE.BufferGeometry: Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()' );
  6335. return;
  6336. }
  6337. var indices = this.attributes.index.array;
  6338. var positions = this.attributes.position.array;
  6339. var normals = this.attributes.normal.array;
  6340. var uvs = this.attributes.uv.array;
  6341. var nVertices = positions.length / 3;
  6342. if ( this.attributes.tangent === undefined ) {
  6343. this.addAttribute( 'tangent', new THREE.BufferAttribute( new Float32Array( 4 * nVertices ), 4 ) );
  6344. }
  6345. var tangents = this.attributes.tangent.array;
  6346. var tan1 = [], tan2 = [];
  6347. for ( var k = 0; k < nVertices; k ++ ) {
  6348. tan1[ k ] = new THREE.Vector3();
  6349. tan2[ k ] = new THREE.Vector3();
  6350. }
  6351. var vA = new THREE.Vector3(),
  6352. vB = new THREE.Vector3(),
  6353. vC = new THREE.Vector3(),
  6354. uvA = new THREE.Vector2(),
  6355. uvB = new THREE.Vector2(),
  6356. uvC = new THREE.Vector2(),
  6357. x1, x2, y1, y2, z1, z2,
  6358. s1, s2, t1, t2, r;
  6359. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  6360. function handleTriangle( a, b, c ) {
  6361. vA.fromArray( positions, a * 3 );
  6362. vB.fromArray( positions, b * 3 );
  6363. vC.fromArray( positions, c * 3 );
  6364. uvA.fromArray( uvs, a * 2 );
  6365. uvB.fromArray( uvs, b * 2 );
  6366. uvC.fromArray( uvs, c * 2 );
  6367. x1 = vB.x - vA.x;
  6368. x2 = vC.x - vA.x;
  6369. y1 = vB.y - vA.y;
  6370. y2 = vC.y - vA.y;
  6371. z1 = vB.z - vA.z;
  6372. z2 = vC.z - vA.z;
  6373. s1 = uvB.x - uvA.x;
  6374. s2 = uvC.x - uvA.x;
  6375. t1 = uvB.y - uvA.y;
  6376. t2 = uvC.y - uvA.y;
  6377. r = 1.0 / ( s1 * t2 - s2 * t1 );
  6378. sdir.set(
  6379. ( t2 * x1 - t1 * x2 ) * r,
  6380. ( t2 * y1 - t1 * y2 ) * r,
  6381. ( t2 * z1 - t1 * z2 ) * r
  6382. );
  6383. tdir.set(
  6384. ( s1 * x2 - s2 * x1 ) * r,
  6385. ( s1 * y2 - s2 * y1 ) * r,
  6386. ( s1 * z2 - s2 * z1 ) * r
  6387. );
  6388. tan1[ a ].add( sdir );
  6389. tan1[ b ].add( sdir );
  6390. tan1[ c ].add( sdir );
  6391. tan2[ a ].add( tdir );
  6392. tan2[ b ].add( tdir );
  6393. tan2[ c ].add( tdir );
  6394. }
  6395. var i, il;
  6396. var j, jl;
  6397. var iA, iB, iC;
  6398. if ( this.drawcalls.length === 0 ) {
  6399. this.addDrawCall( 0, indices.length, 0 );
  6400. }
  6401. var drawcalls = this.drawcalls;
  6402. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  6403. var start = drawcalls[ j ].start;
  6404. var count = drawcalls[ j ].count;
  6405. var index = drawcalls[ j ].index;
  6406. for ( i = start, il = start + count; i < il; i += 3 ) {
  6407. iA = index + indices[ i ];
  6408. iB = index + indices[ i + 1 ];
  6409. iC = index + indices[ i + 2 ];
  6410. handleTriangle( iA, iB, iC );
  6411. }
  6412. }
  6413. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  6414. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  6415. var w, t, test;
  6416. function handleVertex( v ) {
  6417. n.fromArray( normals, v * 3 );
  6418. n2.copy( n );
  6419. t = tan1[ v ];
  6420. // Gram-Schmidt orthogonalize
  6421. tmp.copy( t );
  6422. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6423. // Calculate handedness
  6424. tmp2.crossVectors( n2, t );
  6425. test = tmp2.dot( tan2[ v ] );
  6426. w = ( test < 0.0 ) ? - 1.0 : 1.0;
  6427. tangents[ v * 4 ] = tmp.x;
  6428. tangents[ v * 4 + 1 ] = tmp.y;
  6429. tangents[ v * 4 + 2 ] = tmp.z;
  6430. tangents[ v * 4 + 3 ] = w;
  6431. }
  6432. for ( j = 0, jl = drawcalls.length; j < jl; ++ j ) {
  6433. var start = drawcalls[ j ].start;
  6434. var count = drawcalls[ j ].count;
  6435. var index = drawcalls[ j ].index;
  6436. for ( i = start, il = start + count; i < il; i += 3 ) {
  6437. iA = index + indices[ i ];
  6438. iB = index + indices[ i + 1 ];
  6439. iC = index + indices[ i + 2 ];
  6440. handleVertex( iA );
  6441. handleVertex( iB );
  6442. handleVertex( iC );
  6443. }
  6444. }
  6445. },
  6446. /*
  6447. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  6448. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  6449. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  6450. size - Defaults to 65535 or 4294967296 if extension OES_element_index_uint supported, but allows for larger or smaller chunks.
  6451. */
  6452. computeOffsets: function ( size ) {
  6453. if ( size === undefined ) size = THREE.BufferGeometry.MaxIndex;
  6454. var indices = this.attributes.index.array;
  6455. var vertices = this.attributes.position.array;
  6456. var facesCount = ( indices.length / 3 );
  6457. var UintArray = ( ( vertices.length / 3 ) > 65535 && THREE.BufferGeometry.MaxIndex > 65535 ) ? Uint32Array : Uint16Array;
  6458. /*
  6459. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  6460. console.log("Faces to process: "+(indices.length/3));
  6461. console.log("Reordering "+verticesCount+" vertices.");
  6462. */
  6463. var sortedIndices = new UintArray( indices.length );
  6464. var indexPtr = 0;
  6465. var vertexPtr = 0;
  6466. var offsets = [ { start:0, count:0, index:0 } ];
  6467. var offset = offsets[ 0 ];
  6468. var duplicatedVertices = 0;
  6469. var newVerticeMaps = 0;
  6470. var faceVertices = new Int32Array( 6 );
  6471. var vertexMap = new Int32Array( vertices.length );
  6472. var revVertexMap = new Int32Array( vertices.length );
  6473. for ( var j = 0; j < vertices.length; j ++ ) { vertexMap[ j ] = - 1; revVertexMap[ j ] = - 1; }
  6474. /*
  6475. Traverse every face and reorder vertices in the proper offsets of 65k.
  6476. We can have more than 'size' entries in the index buffer per offset, but only reference 'size' values.
  6477. */
  6478. for ( var findex = 0; findex < facesCount; findex ++ ) {
  6479. newVerticeMaps = 0;
  6480. for ( var vo = 0; vo < 3; vo ++ ) {
  6481. var vid = indices[ findex * 3 + vo ];
  6482. if ( vertexMap[ vid ] === - 1 ) {
  6483. //Unmapped vertex
  6484. faceVertices[ vo * 2 ] = vid;
  6485. faceVertices[ vo * 2 + 1 ] = - 1;
  6486. newVerticeMaps ++;
  6487. } else if ( vertexMap[ vid ] < offset.index ) {
  6488. //Reused vertices from previous block (duplicate)
  6489. faceVertices[ vo * 2 ] = vid;
  6490. faceVertices[ vo * 2 + 1 ] = - 1;
  6491. duplicatedVertices ++;
  6492. } else {
  6493. //Reused vertex in the current block
  6494. faceVertices[ vo * 2 ] = vid;
  6495. faceVertices[ vo * 2 + 1 ] = vertexMap[ vid ];
  6496. }
  6497. }
  6498. var faceMax = vertexPtr + newVerticeMaps;
  6499. if ( faceMax > ( offset.index + size ) ) {
  6500. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  6501. offsets.push( new_offset );
  6502. offset = new_offset;
  6503. //Re-evaluate reused vertices in light of new offset.
  6504. for ( var v = 0; v < 6; v += 2 ) {
  6505. var new_vid = faceVertices[ v + 1 ];
  6506. if ( new_vid > - 1 && new_vid < offset.index )
  6507. faceVertices[ v + 1 ] = - 1;
  6508. }
  6509. }
  6510. //Reindex the face.
  6511. for ( var v = 0; v < 6; v += 2 ) {
  6512. var vid = faceVertices[ v ];
  6513. var new_vid = faceVertices[ v + 1 ];
  6514. if ( new_vid === - 1 )
  6515. new_vid = vertexPtr ++;
  6516. vertexMap[ vid ] = new_vid;
  6517. revVertexMap[ new_vid ] = vid;
  6518. sortedIndices[ indexPtr ++ ] = new_vid - offset.index; //XXX overflows at 16bit
  6519. offset.count ++;
  6520. }
  6521. }
  6522. /* Move all attribute values to map to the new computed indices , also expand the vertex stack to match our new vertexPtr. */
  6523. this.reorderBuffers( sortedIndices, revVertexMap, vertexPtr );
  6524. this.offsets = offsets; // TODO: Deprecate
  6525. this.drawcalls = offsets;
  6526. /*
  6527. var orderTime = Date.now();
  6528. console.log("Reorder time: "+(orderTime-s)+"ms");
  6529. console.log("Duplicated "+duplicatedVertices+" vertices.");
  6530. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  6531. console.log("Draw offsets: "+offsets.length);
  6532. */
  6533. return offsets;
  6534. },
  6535. merge: function ( geometry, offset ) {
  6536. if ( geometry instanceof THREE.BufferGeometry === false ) {
  6537. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  6538. return;
  6539. }
  6540. if ( offset === undefined ) offset = 0;
  6541. var attributes = this.attributes;
  6542. for ( var key in attributes ) {
  6543. if ( geometry.attributes[ key ] === undefined ) continue;
  6544. var attribute1 = attributes[ key ];
  6545. var attributeArray1 = attribute1.array;
  6546. var attribute2 = geometry.attributes[ key ];
  6547. var attributeArray2 = attribute2.array;
  6548. var attributeSize = attribute2.itemSize;
  6549. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  6550. attributeArray1[ j ] = attributeArray2[ i ];
  6551. }
  6552. }
  6553. return this;
  6554. },
  6555. normalizeNormals: function () {
  6556. var normals = this.attributes.normal.array;
  6557. var x, y, z, n;
  6558. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  6559. x = normals[ i ];
  6560. y = normals[ i + 1 ];
  6561. z = normals[ i + 2 ];
  6562. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  6563. normals[ i ] *= n;
  6564. normals[ i + 1 ] *= n;
  6565. normals[ i + 2 ] *= n;
  6566. }
  6567. },
  6568. /*
  6569. reoderBuffers:
  6570. Reorder attributes based on a new indexBuffer and indexMap.
  6571. indexBuffer - Uint16Array of the new ordered indices.
  6572. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  6573. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertex stack).
  6574. */
  6575. reorderBuffers: function ( indexBuffer, indexMap, vertexCount ) {
  6576. /* Create a copy of all attributes for reordering. */
  6577. var sortedAttributes = {};
  6578. for ( var attr in this.attributes ) {
  6579. if ( attr === 'index' )
  6580. continue;
  6581. var sourceArray = this.attributes[ attr ].array;
  6582. sortedAttributes[ attr ] = new sourceArray.constructor( this.attributes[ attr ].itemSize * vertexCount );
  6583. }
  6584. /* Move attribute positions based on the new index map */
  6585. for ( var new_vid = 0; new_vid < vertexCount; new_vid ++ ) {
  6586. var vid = indexMap[ new_vid ];
  6587. for ( var attr in this.attributes ) {
  6588. if ( attr === 'index' )
  6589. continue;
  6590. var attrArray = this.attributes[ attr ].array;
  6591. var attrSize = this.attributes[ attr ].itemSize;
  6592. var sortedAttr = sortedAttributes[ attr ];
  6593. for ( var k = 0; k < attrSize; k ++ )
  6594. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  6595. }
  6596. }
  6597. /* Carry the new sorted buffers locally */
  6598. this.attributes[ 'index' ].array = indexBuffer;
  6599. for ( var attr in this.attributes ) {
  6600. if ( attr === 'index' )
  6601. continue;
  6602. this.attributes[ attr ].array = sortedAttributes[ attr ];
  6603. this.attributes[ attr ].numItems = this.attributes[ attr ].itemSize * vertexCount;
  6604. }
  6605. },
  6606. toJSON: function () {
  6607. var data = {
  6608. metadata: {
  6609. version: 4.4,
  6610. type: 'BufferGeometry',
  6611. generator: 'BufferGeometry.toJSON'
  6612. }
  6613. };
  6614. // standard BufferGeometry serialization
  6615. data.uuid = this.uuid;
  6616. data.type = this.type;
  6617. if ( this.name !== '' ) data.name = this.name;
  6618. if ( this.parameters !== undefined ) {
  6619. var parameters = this.parameters;
  6620. for ( var key in parameters ) {
  6621. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6622. }
  6623. return data;
  6624. }
  6625. data.data = { attributes: {} };
  6626. var attributes = this.attributes;
  6627. var offsets = this.offsets;
  6628. var boundingSphere = this.boundingSphere;
  6629. for ( var key in attributes ) {
  6630. var attribute = attributes[ key ];
  6631. var array = Array.prototype.slice.call( attribute.array );
  6632. data.data.attributes[ key ] = {
  6633. itemSize: attribute.itemSize,
  6634. type: attribute.array.constructor.name,
  6635. array: array
  6636. }
  6637. }
  6638. if ( offsets.length > 0 ) {
  6639. data.data.offsets = JSON.parse( JSON.stringify( offsets ) );
  6640. }
  6641. if ( boundingSphere !== null ) {
  6642. data.data.boundingSphere = {
  6643. center: boundingSphere.center.toArray(),
  6644. radius: boundingSphere.radius
  6645. }
  6646. }
  6647. return data;
  6648. },
  6649. clone: function () {
  6650. var geometry = new THREE.BufferGeometry();
  6651. for ( var attr in this.attributes ) {
  6652. var sourceAttr = this.attributes[ attr ];
  6653. geometry.addAttribute( attr, sourceAttr.clone() );
  6654. }
  6655. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  6656. var offset = this.offsets[ i ];
  6657. geometry.offsets.push( {
  6658. start: offset.start,
  6659. index: offset.index,
  6660. count: offset.count
  6661. } );
  6662. }
  6663. return geometry;
  6664. },
  6665. dispose: function () {
  6666. this.dispatchEvent( { type: 'dispose' } );
  6667. }
  6668. };
  6669. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  6670. THREE.BufferGeometry.MaxIndex = 65535;
  6671. // File:src/core/InstancedBufferGeometry.js
  6672. /**
  6673. * @author benaadams / https://twitter.com/ben_a_adams
  6674. */
  6675. THREE.InstancedBufferGeometry = function () {
  6676. THREE.BufferGeometry.call( this );
  6677. this.type = 'InstancedBufferGeometry';
  6678. this.maxInstancedCount = undefined;
  6679. };
  6680. THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  6681. THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry;
  6682. THREE.InstancedBufferGeometry.prototype.addDrawCall = function ( start, count, indexOffset, instances ) {
  6683. this.drawcalls.push( {
  6684. start: start,
  6685. count: count,
  6686. index: indexOffset !== undefined ? indexOffset : 0,
  6687. instances: instances
  6688. } );
  6689. },
  6690. THREE.InstancedBufferGeometry.prototype.clone = function () {
  6691. var geometry = new THREE.InstancedBufferGeometry();
  6692. for ( var attr in this.attributes ) {
  6693. var sourceAttr = this.attributes[attr];
  6694. geometry.addAttribute( attr, sourceAttr.clone() );
  6695. }
  6696. for ( var i = 0, il = this.offsets.length; i < il; i++ ) {
  6697. var offset = this.offsets[i];
  6698. geometry.offsets.push( {
  6699. start: offset.start,
  6700. index: offset.index,
  6701. count: offset.count,
  6702. instances: offset.instances
  6703. } );
  6704. }
  6705. return geometry;
  6706. };
  6707. THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype );
  6708. // File:src/cameras/Camera.js
  6709. /**
  6710. * @author mrdoob / http://mrdoob.com/
  6711. * @author mikael emtinger / http://gomo.se/
  6712. * @author WestLangley / http://github.com/WestLangley
  6713. */
  6714. THREE.Camera = function () {
  6715. THREE.Object3D.call( this );
  6716. this.type = 'Camera';
  6717. this.matrixWorldInverse = new THREE.Matrix4();
  6718. this.projectionMatrix = new THREE.Matrix4();
  6719. };
  6720. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6721. THREE.Camera.prototype.constructor = THREE.Camera;
  6722. THREE.Camera.prototype.getWorldDirection = function () {
  6723. var quaternion = new THREE.Quaternion();
  6724. return function ( optionalTarget ) {
  6725. var result = optionalTarget || new THREE.Vector3();
  6726. this.getWorldQuaternion( quaternion );
  6727. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  6728. };
  6729. }();
  6730. THREE.Camera.prototype.lookAt = function () {
  6731. // This routine does not support cameras with rotated and/or translated parent(s)
  6732. var m1 = new THREE.Matrix4();
  6733. return function ( vector ) {
  6734. m1.lookAt( this.position, vector, this.up );
  6735. this.quaternion.setFromRotationMatrix( m1 );
  6736. };
  6737. }();
  6738. THREE.Camera.prototype.clone = function ( camera ) {
  6739. if ( camera === undefined ) camera = new THREE.Camera();
  6740. THREE.Object3D.prototype.clone.call( this, camera );
  6741. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6742. camera.projectionMatrix.copy( this.projectionMatrix );
  6743. return camera;
  6744. };
  6745. // File:src/cameras/CubeCamera.js
  6746. /**
  6747. * Camera for rendering cube maps
  6748. * - renders scene into axis-aligned cube
  6749. *
  6750. * @author alteredq / http://alteredqualia.com/
  6751. */
  6752. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  6753. THREE.Object3D.call( this );
  6754. this.type = 'CubeCamera';
  6755. var fov = 90, aspect = 1;
  6756. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6757. cameraPX.up.set( 0, - 1, 0 );
  6758. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  6759. this.add( cameraPX );
  6760. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6761. cameraNX.up.set( 0, - 1, 0 );
  6762. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  6763. this.add( cameraNX );
  6764. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6765. cameraPY.up.set( 0, 0, 1 );
  6766. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  6767. this.add( cameraPY );
  6768. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6769. cameraNY.up.set( 0, 0, - 1 );
  6770. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  6771. this.add( cameraNY );
  6772. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6773. cameraPZ.up.set( 0, - 1, 0 );
  6774. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  6775. this.add( cameraPZ );
  6776. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  6777. cameraNZ.up.set( 0, - 1, 0 );
  6778. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  6779. this.add( cameraNZ );
  6780. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  6781. this.updateCubeMap = function ( renderer, scene ) {
  6782. if ( this.parent === undefined ) this.updateMatrixWorld();
  6783. var renderTarget = this.renderTarget;
  6784. var generateMipmaps = renderTarget.generateMipmaps;
  6785. renderTarget.generateMipmaps = false;
  6786. renderTarget.activeCubeFace = 0;
  6787. renderer.render( scene, cameraPX, renderTarget );
  6788. renderTarget.activeCubeFace = 1;
  6789. renderer.render( scene, cameraNX, renderTarget );
  6790. renderTarget.activeCubeFace = 2;
  6791. renderer.render( scene, cameraPY, renderTarget );
  6792. renderTarget.activeCubeFace = 3;
  6793. renderer.render( scene, cameraNY, renderTarget );
  6794. renderTarget.activeCubeFace = 4;
  6795. renderer.render( scene, cameraPZ, renderTarget );
  6796. renderTarget.generateMipmaps = generateMipmaps;
  6797. renderTarget.activeCubeFace = 5;
  6798. renderer.render( scene, cameraNZ, renderTarget );
  6799. renderer.setRenderTarget( null );
  6800. };
  6801. };
  6802. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  6803. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  6804. // File:src/cameras/OrthographicCamera.js
  6805. /**
  6806. * @author alteredq / http://alteredqualia.com/
  6807. */
  6808. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6809. THREE.Camera.call( this );
  6810. this.type = 'OrthographicCamera';
  6811. this.zoom = 1;
  6812. this.left = left;
  6813. this.right = right;
  6814. this.top = top;
  6815. this.bottom = bottom;
  6816. this.near = ( near !== undefined ) ? near : 0.1;
  6817. this.far = ( far !== undefined ) ? far : 2000;
  6818. this.updateProjectionMatrix();
  6819. };
  6820. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6821. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  6822. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6823. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  6824. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  6825. var cx = ( this.right + this.left ) / 2;
  6826. var cy = ( this.top + this.bottom ) / 2;
  6827. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  6828. };
  6829. THREE.OrthographicCamera.prototype.clone = function () {
  6830. var camera = new THREE.OrthographicCamera();
  6831. THREE.Camera.prototype.clone.call( this, camera );
  6832. camera.zoom = this.zoom;
  6833. camera.left = this.left;
  6834. camera.right = this.right;
  6835. camera.top = this.top;
  6836. camera.bottom = this.bottom;
  6837. camera.near = this.near;
  6838. camera.far = this.far;
  6839. return camera;
  6840. };
  6841. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  6842. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6843. data.object.zoom = this.zoom;
  6844. data.object.left = this.left;
  6845. data.object.right = this.right;
  6846. data.object.top = this.top;
  6847. data.object.bottom = this.bottom;
  6848. data.object.near = this.near;
  6849. data.object.far = this.far;
  6850. return data;
  6851. };
  6852. // File:src/cameras/PerspectiveCamera.js
  6853. /**
  6854. * @author mrdoob / http://mrdoob.com/
  6855. * @author greggman / http://games.greggman.com/
  6856. * @author zz85 / http://www.lab4games.net/zz85/blog
  6857. */
  6858. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6859. THREE.Camera.call( this );
  6860. this.type = 'PerspectiveCamera';
  6861. this.zoom = 1;
  6862. this.fov = fov !== undefined ? fov : 50;
  6863. this.aspect = aspect !== undefined ? aspect : 1;
  6864. this.near = near !== undefined ? near : 0.1;
  6865. this.far = far !== undefined ? far : 2000;
  6866. this.updateProjectionMatrix();
  6867. };
  6868. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6869. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  6870. /**
  6871. * Uses Focal Length (in mm) to estimate and set FOV
  6872. * 35mm (full-frame) camera is used if frame size is not specified;
  6873. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6874. */
  6875. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6876. if ( frameHeight === undefined ) frameHeight = 24;
  6877. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6878. this.updateProjectionMatrix();
  6879. };
  6880. /**
  6881. * Sets an offset in a larger frustum. This is useful for multi-window or
  6882. * multi-monitor/multi-machine setups.
  6883. *
  6884. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6885. * the monitors are in grid like this
  6886. *
  6887. * +---+---+---+
  6888. * | A | B | C |
  6889. * +---+---+---+
  6890. * | D | E | F |
  6891. * +---+---+---+
  6892. *
  6893. * then for each monitor you would call it like this
  6894. *
  6895. * var w = 1920;
  6896. * var h = 1080;
  6897. * var fullWidth = w * 3;
  6898. * var fullHeight = h * 2;
  6899. *
  6900. * --A--
  6901. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6902. * --B--
  6903. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6904. * --C--
  6905. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6906. * --D--
  6907. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6908. * --E--
  6909. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6910. * --F--
  6911. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6912. *
  6913. * Note there is no reason monitors have to be the same size or in a grid.
  6914. */
  6915. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6916. this.fullWidth = fullWidth;
  6917. this.fullHeight = fullHeight;
  6918. this.x = x;
  6919. this.y = y;
  6920. this.width = width;
  6921. this.height = height;
  6922. this.updateProjectionMatrix();
  6923. };
  6924. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6925. var fov = THREE.Math.radToDeg( 2 * Math.atan( Math.tan( THREE.Math.degToRad( this.fov ) * 0.5 ) / this.zoom ) );
  6926. if ( this.fullWidth ) {
  6927. var aspect = this.fullWidth / this.fullHeight;
  6928. var top = Math.tan( THREE.Math.degToRad( fov * 0.5 ) ) * this.near;
  6929. var bottom = - top;
  6930. var left = aspect * bottom;
  6931. var right = aspect * top;
  6932. var width = Math.abs( right - left );
  6933. var height = Math.abs( top - bottom );
  6934. this.projectionMatrix.makeFrustum(
  6935. left + this.x * width / this.fullWidth,
  6936. left + ( this.x + this.width ) * width / this.fullWidth,
  6937. top - ( this.y + this.height ) * height / this.fullHeight,
  6938. top - this.y * height / this.fullHeight,
  6939. this.near,
  6940. this.far
  6941. );
  6942. } else {
  6943. this.projectionMatrix.makePerspective( fov, this.aspect, this.near, this.far );
  6944. }
  6945. };
  6946. THREE.PerspectiveCamera.prototype.clone = function () {
  6947. var camera = new THREE.PerspectiveCamera();
  6948. THREE.Camera.prototype.clone.call( this, camera );
  6949. camera.zoom = this.zoom;
  6950. camera.fov = this.fov;
  6951. camera.aspect = this.aspect;
  6952. camera.near = this.near;
  6953. camera.far = this.far;
  6954. return camera;
  6955. };
  6956. THREE.PerspectiveCamera.prototype.toJSON = function ( meta ) {
  6957. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  6958. data.object.zoom = this.zoom;
  6959. data.object.fov = this.fov;
  6960. data.object.aspect = this.aspect;
  6961. data.object.near = this.near;
  6962. data.object.far = this.far;
  6963. return data;
  6964. };
  6965. // File:src/lights/Light.js
  6966. /**
  6967. * @author mrdoob / http://mrdoob.com/
  6968. * @author alteredq / http://alteredqualia.com/
  6969. */
  6970. THREE.Light = function ( color ) {
  6971. THREE.Object3D.call( this );
  6972. this.type = 'Light';
  6973. this.color = new THREE.Color( color );
  6974. };
  6975. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6976. THREE.Light.prototype.constructor = THREE.Light;
  6977. THREE.Light.prototype.clone = function ( light ) {
  6978. if ( light === undefined ) light = new THREE.Light();
  6979. THREE.Object3D.prototype.clone.call( this, light );
  6980. light.color.copy( this.color );
  6981. return light;
  6982. };
  6983. // File:src/lights/AmbientLight.js
  6984. /**
  6985. * @author mrdoob / http://mrdoob.com/
  6986. */
  6987. THREE.AmbientLight = function ( color ) {
  6988. THREE.Light.call( this, color );
  6989. this.type = 'AmbientLight';
  6990. };
  6991. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6992. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  6993. THREE.AmbientLight.prototype.clone = function () {
  6994. var light = new THREE.AmbientLight();
  6995. THREE.Light.prototype.clone.call( this, light );
  6996. return light;
  6997. };
  6998. THREE.AmbientLight.prototype.toJSON = function ( meta ) {
  6999. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7000. data.object.color = this.color.getHex();
  7001. return data;
  7002. };
  7003. // File:src/lights/AreaLight.js
  7004. /**
  7005. * @author MPanknin / http://www.redplant.de/
  7006. * @author alteredq / http://alteredqualia.com/
  7007. * @author prafullit
  7008. */
  7009. THREE.AreaLight = function ( color, intensity ) {
  7010. THREE.Light.call( this, color );
  7011. this.type = 'AreaLight';
  7012. this.normal = new THREE.Vector3( 0, - 1, 0 );
  7013. this.right = new THREE.Vector3( 1, 0, 0 );
  7014. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7015. this.width = 1.0;
  7016. this.height = 1.0;
  7017. this.constantAttenuation = 1.5;
  7018. this.linearAttenuation = 0.5;
  7019. this.quadraticAttenuation = 0.1;
  7020. };
  7021. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  7022. THREE.AreaLight.prototype.constructor = THREE.AreaLight;
  7023. THREE.AreaLight.prototype.clone = function () {
  7024. var light = new THREE.AreaLight();
  7025. THREE.Light.prototype.clone.call( this, light );
  7026. light.normal.copy(this.normal);
  7027. light.right.copy(this.right);
  7028. light.intensity = this.intensity;
  7029. light.width = this.width;
  7030. light.height = this.height;
  7031. light.constantAttenuation = this.constantAttenuation;
  7032. light.linearAttenuation = this.linearAttenuation;
  7033. light.quadraticAttenuation = this.quadraticAttenuation
  7034. return light;
  7035. };
  7036. THREE.AreaLight.prototype.toJSON = function ( meta ) {
  7037. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7038. data.object.color = this.color.getHex();
  7039. data.object.intensity = this.intensity;
  7040. return data;
  7041. };
  7042. // File:src/lights/DirectionalLight.js
  7043. /**
  7044. * @author mrdoob / http://mrdoob.com/
  7045. * @author alteredq / http://alteredqualia.com/
  7046. */
  7047. THREE.DirectionalLight = function ( color, intensity ) {
  7048. THREE.Light.call( this, color );
  7049. this.type = 'DirectionalLight';
  7050. this.position.set( 0, 1, 0 );
  7051. this.target = new THREE.Object3D();
  7052. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7053. this.castShadow = false;
  7054. this.onlyShadow = false;
  7055. //
  7056. this.shadowCameraNear = 50;
  7057. this.shadowCameraFar = 5000;
  7058. this.shadowCameraLeft = - 500;
  7059. this.shadowCameraRight = 500;
  7060. this.shadowCameraTop = 500;
  7061. this.shadowCameraBottom = - 500;
  7062. this.shadowCameraVisible = false;
  7063. this.shadowBias = 0;
  7064. this.shadowDarkness = 0.5;
  7065. this.shadowMapWidth = 512;
  7066. this.shadowMapHeight = 512;
  7067. //
  7068. this.shadowCascade = false;
  7069. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, - 1000 );
  7070. this.shadowCascadeCount = 2;
  7071. this.shadowCascadeBias = [ 0, 0, 0 ];
  7072. this.shadowCascadeWidth = [ 512, 512, 512 ];
  7073. this.shadowCascadeHeight = [ 512, 512, 512 ];
  7074. this.shadowCascadeNearZ = [ - 1.000, 0.990, 0.998 ];
  7075. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  7076. this.shadowCascadeArray = [];
  7077. //
  7078. this.shadowMap = null;
  7079. this.shadowMapSize = null;
  7080. this.shadowCamera = null;
  7081. this.shadowMatrix = null;
  7082. };
  7083. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  7084. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  7085. THREE.DirectionalLight.prototype.clone = function () {
  7086. var light = new THREE.DirectionalLight();
  7087. THREE.Light.prototype.clone.call( this, light );
  7088. light.target = this.target.clone();
  7089. light.intensity = this.intensity;
  7090. light.castShadow = this.castShadow;
  7091. light.onlyShadow = this.onlyShadow;
  7092. //
  7093. light.shadowCameraNear = this.shadowCameraNear;
  7094. light.shadowCameraFar = this.shadowCameraFar;
  7095. light.shadowCameraLeft = this.shadowCameraLeft;
  7096. light.shadowCameraRight = this.shadowCameraRight;
  7097. light.shadowCameraTop = this.shadowCameraTop;
  7098. light.shadowCameraBottom = this.shadowCameraBottom;
  7099. light.shadowCameraVisible = this.shadowCameraVisible;
  7100. light.shadowBias = this.shadowBias;
  7101. light.shadowDarkness = this.shadowDarkness;
  7102. light.shadowMapWidth = this.shadowMapWidth;
  7103. light.shadowMapHeight = this.shadowMapHeight;
  7104. //
  7105. light.shadowCascade = this.shadowCascade;
  7106. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  7107. light.shadowCascadeCount = this.shadowCascadeCount;
  7108. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  7109. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  7110. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  7111. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  7112. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  7113. return light;
  7114. };
  7115. THREE.DirectionalLight.prototype.toJSON = function ( meta ) {
  7116. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7117. data.object.color = this.color.getHex();
  7118. data.object.intensity = this.intensity;
  7119. return data;
  7120. };
  7121. // File:src/lights/HemisphereLight.js
  7122. /**
  7123. * @author alteredq / http://alteredqualia.com/
  7124. */
  7125. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  7126. THREE.Light.call( this, skyColor );
  7127. this.type = 'HemisphereLight';
  7128. this.position.set( 0, 100, 0 );
  7129. this.groundColor = new THREE.Color( groundColor );
  7130. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7131. };
  7132. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  7133. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  7134. THREE.HemisphereLight.prototype.clone = function () {
  7135. var light = new THREE.HemisphereLight();
  7136. THREE.Light.prototype.clone.call( this, light );
  7137. light.groundColor.copy( this.groundColor );
  7138. light.intensity = this.intensity;
  7139. return light;
  7140. };
  7141. THREE.HemisphereLight.prototype.toJSON = function ( meta ) {
  7142. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7143. data.object.color = this.color.getHex();
  7144. data.object.groundColor = this.groundColor.getHex();
  7145. return data;
  7146. };
  7147. // File:src/lights/PointLight.js
  7148. /**
  7149. * @author mrdoob / http://mrdoob.com/
  7150. */
  7151. THREE.PointLight = function ( color, intensity, distance, decay ) {
  7152. THREE.Light.call( this, color );
  7153. this.type = 'PointLight';
  7154. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7155. this.distance = ( distance !== undefined ) ? distance : 0;
  7156. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  7157. };
  7158. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  7159. THREE.PointLight.prototype.constructor = THREE.PointLight;
  7160. THREE.PointLight.prototype.clone = function () {
  7161. var light = new THREE.PointLight();
  7162. THREE.Light.prototype.clone.call( this, light );
  7163. light.intensity = this.intensity;
  7164. light.distance = this.distance;
  7165. light.decay = this.decay;
  7166. return light;
  7167. };
  7168. THREE.PointLight.prototype.toJSON = function ( meta ) {
  7169. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7170. data.object.color = this.color.getHex();
  7171. data.object.intensity = this.intensity;
  7172. data.object.distance = this.distance;
  7173. data.object.decay = this.decay;
  7174. return data;
  7175. };
  7176. // File:src/lights/SpotLight.js
  7177. /**
  7178. * @author alteredq / http://alteredqualia.com/
  7179. */
  7180. THREE.SpotLight = function ( color, intensity, distance, angle, exponent, decay ) {
  7181. THREE.Light.call( this, color );
  7182. this.type = 'SpotLight';
  7183. this.position.set( 0, 1, 0 );
  7184. this.target = new THREE.Object3D();
  7185. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  7186. this.distance = ( distance !== undefined ) ? distance : 0;
  7187. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  7188. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  7189. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  7190. this.castShadow = false;
  7191. this.onlyShadow = false;
  7192. //
  7193. this.shadowCameraNear = 50;
  7194. this.shadowCameraFar = 5000;
  7195. this.shadowCameraFov = 50;
  7196. this.shadowCameraVisible = false;
  7197. this.shadowBias = 0;
  7198. this.shadowDarkness = 0.5;
  7199. this.shadowMapWidth = 512;
  7200. this.shadowMapHeight = 512;
  7201. //
  7202. this.shadowMap = null;
  7203. this.shadowMapSize = null;
  7204. this.shadowCamera = null;
  7205. this.shadowMatrix = null;
  7206. };
  7207. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  7208. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  7209. THREE.SpotLight.prototype.clone = function () {
  7210. var light = new THREE.SpotLight();
  7211. THREE.Light.prototype.clone.call( this, light );
  7212. light.target = this.target.clone();
  7213. light.intensity = this.intensity;
  7214. light.distance = this.distance;
  7215. light.angle = this.angle;
  7216. light.exponent = this.exponent;
  7217. light.decay = this.decay;
  7218. light.castShadow = this.castShadow;
  7219. light.onlyShadow = this.onlyShadow;
  7220. //
  7221. light.shadowCameraNear = this.shadowCameraNear;
  7222. light.shadowCameraFar = this.shadowCameraFar;
  7223. light.shadowCameraFov = this.shadowCameraFov;
  7224. light.shadowCameraVisible = this.shadowCameraVisible;
  7225. light.shadowBias = this.shadowBias;
  7226. light.shadowDarkness = this.shadowDarkness;
  7227. light.shadowMapWidth = this.shadowMapWidth;
  7228. light.shadowMapHeight = this.shadowMapHeight;
  7229. return light;
  7230. };
  7231. THREE.SpotLight.prototype.toJSON = function ( meta ) {
  7232. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  7233. data.object.color = this.color.getHex();
  7234. data.object.intensity = this.intensity;
  7235. data.object.distance = this.distance;
  7236. data.object.angle = this.angle;
  7237. data.object.exponent = this.exponent;
  7238. data.object.decay = this.decay;
  7239. return data;
  7240. };
  7241. // File:src/loaders/Cache.js
  7242. /**
  7243. * @author mrdoob / http://mrdoob.com/
  7244. */
  7245. THREE.Cache = {
  7246. files: {},
  7247. add: function ( key, file ) {
  7248. // console.log( 'THREE.Cache', 'Adding key:', key );
  7249. this.files[ key ] = file;
  7250. },
  7251. get: function ( key ) {
  7252. // console.log( 'THREE.Cache', 'Checking key:', key );
  7253. return this.files[ key ];
  7254. },
  7255. remove: function ( key ) {
  7256. delete this.files[ key ];
  7257. },
  7258. clear: function () {
  7259. this.files = {}
  7260. }
  7261. };
  7262. // File:src/loaders/Loader.js
  7263. /**
  7264. * @author alteredq / http://alteredqualia.com/
  7265. */
  7266. THREE.Loader = function ( showStatus ) {
  7267. this.showStatus = showStatus;
  7268. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  7269. this.imageLoader = new THREE.ImageLoader();
  7270. this.onLoadStart = function () {};
  7271. this.onLoadProgress = function () {};
  7272. this.onLoadComplete = function () {};
  7273. };
  7274. THREE.Loader.prototype = {
  7275. constructor: THREE.Loader,
  7276. crossOrigin: undefined,
  7277. addStatusElement: function () {
  7278. var e = document.createElement( 'div' );
  7279. e.style.position = 'absolute';
  7280. e.style.right = '0px';
  7281. e.style.top = '0px';
  7282. e.style.fontSize = '0.8em';
  7283. e.style.textAlign = 'left';
  7284. e.style.background = 'rgba(0,0,0,0.25)';
  7285. e.style.color = '#fff';
  7286. e.style.width = '120px';
  7287. e.style.padding = '0.5em 0.5em 0.5em 0.5em';
  7288. e.style.zIndex = 1000;
  7289. e.innerHTML = 'Loading ...';
  7290. return e;
  7291. },
  7292. updateProgress: function ( progress ) {
  7293. var message = 'Loaded ';
  7294. if ( progress.total ) {
  7295. message += ( 100 * progress.loaded / progress.total ).toFixed( 0 ) + '%';
  7296. } else {
  7297. message += ( progress.loaded / 1024 ).toFixed( 2 ) + ' KB';
  7298. }
  7299. this.statusDomElement.innerHTML = message;
  7300. },
  7301. extractUrlBase: function ( url ) {
  7302. var parts = url.split( '/' );
  7303. if ( parts.length === 1 ) return './';
  7304. parts.pop();
  7305. return parts.join( '/' ) + '/';
  7306. },
  7307. initMaterials: function ( materials, texturePath ) {
  7308. var array = [];
  7309. for ( var i = 0; i < materials.length; ++ i ) {
  7310. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  7311. }
  7312. return array;
  7313. },
  7314. needsTangents: function ( materials ) {
  7315. for ( var i = 0, il = materials.length; i < il; i ++ ) {
  7316. var m = materials[ i ];
  7317. if ( m instanceof THREE.ShaderMaterial ) return true;
  7318. }
  7319. return false;
  7320. },
  7321. createMaterial: function ( m, texturePath ) {
  7322. var scope = this;
  7323. function nearest_pow2( n ) {
  7324. var l = Math.log( n ) / Math.LN2;
  7325. return Math.pow( 2, Math.round( l ) );
  7326. }
  7327. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  7328. var fullPath = texturePath + sourceFile;
  7329. var texture;
  7330. var loader = THREE.Loader.Handlers.get( fullPath );
  7331. if ( loader !== null ) {
  7332. texture = loader.load( fullPath );
  7333. } else {
  7334. texture = new THREE.Texture();
  7335. loader = scope.imageLoader;
  7336. loader.crossOrigin = scope.crossOrigin;
  7337. loader.load( fullPath, function ( image ) {
  7338. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  7339. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  7340. var width = nearest_pow2( image.width );
  7341. var height = nearest_pow2( image.height );
  7342. var canvas = document.createElement( 'canvas' );
  7343. canvas.width = width;
  7344. canvas.height = height;
  7345. var context = canvas.getContext( '2d' );
  7346. context.drawImage( image, 0, 0, width, height );
  7347. texture.image = canvas;
  7348. } else {
  7349. texture.image = image;
  7350. }
  7351. texture.needsUpdate = true;
  7352. } );
  7353. }
  7354. texture.sourceFile = sourceFile;
  7355. if ( repeat ) {
  7356. texture.repeat.set( repeat[ 0 ], repeat[ 1 ] );
  7357. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7358. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7359. }
  7360. if ( offset ) {
  7361. texture.offset.set( offset[ 0 ], offset[ 1 ] );
  7362. }
  7363. if ( wrap ) {
  7364. var wrapMap = {
  7365. 'repeat': THREE.RepeatWrapping,
  7366. 'mirror': THREE.MirroredRepeatWrapping
  7367. };
  7368. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ wrap[ 0 ] ];
  7369. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ wrap[ 1 ] ];
  7370. }
  7371. if ( anisotropy ) {
  7372. texture.anisotropy = anisotropy;
  7373. }
  7374. where[ name ] = texture;
  7375. }
  7376. function rgb2hex( rgb ) {
  7377. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  7378. }
  7379. // defaults
  7380. var mtype = 'MeshLambertMaterial';
  7381. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  7382. // parameters from model file
  7383. if ( m.shading ) {
  7384. var shading = m.shading.toLowerCase();
  7385. if ( shading === 'phong' ) mtype = 'MeshPhongMaterial';
  7386. else if ( shading === 'basic' ) mtype = 'MeshBasicMaterial';
  7387. }
  7388. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  7389. mpars.blending = THREE[ m.blending ];
  7390. }
  7391. if ( m.transparent !== undefined ) {
  7392. mpars.transparent = m.transparent;
  7393. }
  7394. if ( m.opacity !== undefined && m.opacity < 1.0 ) {
  7395. mpars.transparent = true;
  7396. }
  7397. if ( m.depthTest !== undefined ) {
  7398. mpars.depthTest = m.depthTest;
  7399. }
  7400. if ( m.depthWrite !== undefined ) {
  7401. mpars.depthWrite = m.depthWrite;
  7402. }
  7403. if ( m.visible !== undefined ) {
  7404. mpars.visible = m.visible;
  7405. }
  7406. if ( m.flipSided !== undefined ) {
  7407. mpars.side = THREE.BackSide;
  7408. }
  7409. if ( m.doubleSided !== undefined ) {
  7410. mpars.side = THREE.DoubleSide;
  7411. }
  7412. if ( m.wireframe !== undefined ) {
  7413. mpars.wireframe = m.wireframe;
  7414. }
  7415. if ( m.vertexColors !== undefined ) {
  7416. if ( m.vertexColors === 'face' ) {
  7417. mpars.vertexColors = THREE.FaceColors;
  7418. } else if ( m.vertexColors ) {
  7419. mpars.vertexColors = THREE.VertexColors;
  7420. }
  7421. }
  7422. // colors
  7423. if ( m.colorDiffuse ) {
  7424. mpars.color = rgb2hex( m.colorDiffuse );
  7425. } else if ( m.DbgColor ) {
  7426. mpars.color = m.DbgColor;
  7427. }
  7428. if ( m.colorSpecular ) {
  7429. mpars.specular = rgb2hex( m.colorSpecular );
  7430. }
  7431. if ( m.colorEmissive ) {
  7432. mpars.emissive = rgb2hex( m.colorEmissive );
  7433. }
  7434. // modifiers
  7435. if ( m.transparency !== undefined ) {
  7436. console.warn( 'THREE.Loader: transparency has been renamed to opacity' );
  7437. m.opacity = m.transparency;
  7438. }
  7439. if ( m.opacity !== undefined ) {
  7440. mpars.opacity = m.opacity;
  7441. }
  7442. if ( m.specularCoef ) {
  7443. mpars.shininess = m.specularCoef;
  7444. }
  7445. // textures
  7446. if ( m.mapDiffuse && texturePath ) {
  7447. create_texture( mpars, 'map', m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  7448. }
  7449. if ( m.mapLight && texturePath ) {
  7450. create_texture( mpars, 'lightMap', m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  7451. }
  7452. if ( m.mapAO && texturePath ) {
  7453. create_texture( mpars, 'aoMap', m.mapAO, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  7454. }
  7455. if ( m.mapBump && texturePath ) {
  7456. create_texture( mpars, 'bumpMap', m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  7457. }
  7458. if ( m.mapNormal && texturePath ) {
  7459. create_texture( mpars, 'normalMap', m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  7460. }
  7461. if ( m.mapSpecular && texturePath ) {
  7462. create_texture( mpars, 'specularMap', m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  7463. }
  7464. if ( m.mapAlpha && texturePath ) {
  7465. create_texture( mpars, 'alphaMap', m.mapAlpha, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  7466. }
  7467. //
  7468. if ( m.mapBumpScale ) {
  7469. mpars.bumpScale = m.mapBumpScale;
  7470. }
  7471. if ( m.mapNormalFactor ) {
  7472. mpars.normalScale = new THREE.Vector2( m.mapNormalFactor, m.mapNormalFactor );
  7473. }
  7474. var material = new THREE[ mtype ]( mpars );
  7475. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  7476. return material;
  7477. }
  7478. };
  7479. THREE.Loader.Handlers = {
  7480. handlers: [],
  7481. add: function ( regex, loader ) {
  7482. this.handlers.push( regex, loader );
  7483. },
  7484. get: function ( file ) {
  7485. for ( var i = 0, l = this.handlers.length; i < l; i += 2 ) {
  7486. var regex = this.handlers[ i ];
  7487. var loader = this.handlers[ i + 1 ];
  7488. if ( regex.test( file ) ) {
  7489. return loader;
  7490. }
  7491. }
  7492. return null;
  7493. }
  7494. };
  7495. // File:src/loaders/XHRLoader.js
  7496. /**
  7497. * @author mrdoob / http://mrdoob.com/
  7498. */
  7499. THREE.XHRLoader = function ( manager ) {
  7500. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7501. };
  7502. THREE.XHRLoader.prototype = {
  7503. constructor: THREE.XHRLoader,
  7504. load: function ( url, onLoad, onProgress, onError ) {
  7505. var scope = this;
  7506. var cached = THREE.Cache.get( url );
  7507. if ( cached !== undefined ) {
  7508. if ( onLoad ) onLoad( cached );
  7509. return cached;
  7510. }
  7511. var request = new XMLHttpRequest();
  7512. request.open( 'GET', url, true );
  7513. request.addEventListener( 'load', function ( event ) {
  7514. THREE.Cache.add( url, this.response );
  7515. if ( onLoad ) onLoad( this.response );
  7516. scope.manager.itemEnd( url );
  7517. }, false );
  7518. if ( onProgress !== undefined ) {
  7519. request.addEventListener( 'progress', function ( event ) {
  7520. onProgress( event );
  7521. }, false );
  7522. }
  7523. if ( onError !== undefined ) {
  7524. request.addEventListener( 'error', function ( event ) {
  7525. onError( event );
  7526. }, false );
  7527. }
  7528. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  7529. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  7530. request.send( null );
  7531. scope.manager.itemStart( url );
  7532. return request;
  7533. },
  7534. setResponseType: function ( value ) {
  7535. this.responseType = value;
  7536. },
  7537. setCrossOrigin: function ( value ) {
  7538. this.crossOrigin = value;
  7539. }
  7540. };
  7541. // File:src/loaders/ImageLoader.js
  7542. /**
  7543. * @author mrdoob / http://mrdoob.com/
  7544. */
  7545. THREE.ImageLoader = function ( manager ) {
  7546. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7547. };
  7548. THREE.ImageLoader.prototype = {
  7549. constructor: THREE.ImageLoader,
  7550. load: function ( url, onLoad, onProgress, onError ) {
  7551. var scope = this;
  7552. var cached = THREE.Cache.get( url );
  7553. if ( cached !== undefined ) {
  7554. if ( onLoad ) onLoad( cached );
  7555. return cached;
  7556. }
  7557. var image = document.createElement( 'img' );
  7558. image.addEventListener( 'load', function ( event ) {
  7559. THREE.Cache.add( url, this );
  7560. if ( onLoad ) onLoad( this );
  7561. scope.manager.itemEnd( url );
  7562. }, false );
  7563. if ( onProgress !== undefined ) {
  7564. image.addEventListener( 'progress', function ( event ) {
  7565. onProgress( event );
  7566. }, false );
  7567. }
  7568. if ( onError !== undefined ) {
  7569. image.addEventListener( 'error', function ( event ) {
  7570. onError( event );
  7571. }, false );
  7572. }
  7573. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7574. scope.manager.itemStart( url );
  7575. image.src = url;
  7576. return image;
  7577. },
  7578. setCrossOrigin: function ( value ) {
  7579. this.crossOrigin = value;
  7580. }
  7581. };
  7582. // File:src/loaders/JSONLoader.js
  7583. /**
  7584. * @author mrdoob / http://mrdoob.com/
  7585. * @author alteredq / http://alteredqualia.com/
  7586. */
  7587. THREE.JSONLoader = function ( showStatus ) {
  7588. THREE.Loader.call( this, showStatus );
  7589. this.withCredentials = false;
  7590. };
  7591. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7592. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  7593. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7594. // TODO: unify load API to for easier SceneLoader use
  7595. texturePath = texturePath && ( typeof texturePath === 'string' ) ? texturePath : this.extractUrlBase( url );
  7596. this.onLoadStart();
  7597. this.loadAjaxJSON( this, url, callback, texturePath );
  7598. };
  7599. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7600. var xhr = new XMLHttpRequest();
  7601. var length = 0;
  7602. xhr.onreadystatechange = function () {
  7603. if ( xhr.readyState === xhr.DONE ) {
  7604. if ( xhr.status === 200 || xhr.status === 0 ) {
  7605. if ( xhr.responseText ) {
  7606. var json = JSON.parse( xhr.responseText );
  7607. var metadata = json.metadata;
  7608. if ( metadata !== undefined ) {
  7609. if ( metadata.type === 'object' ) {
  7610. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  7611. return;
  7612. }
  7613. if ( metadata.type === 'scene' ) {
  7614. console.error( 'THREE.JSONLoader: ' + url + ' seems to be a Scene. Use THREE.SceneLoader instead.' );
  7615. return;
  7616. }
  7617. }
  7618. var result = context.parse( json, texturePath );
  7619. callback( result.geometry, result.materials );
  7620. } else {
  7621. console.error( 'THREE.JSONLoader: ' + url + ' seems to be unreachable or the file is empty.' );
  7622. }
  7623. // in context of more complex asset initialization
  7624. // do not block on single failed file
  7625. // maybe should go even one more level up
  7626. context.onLoadComplete();
  7627. } else {
  7628. console.error( 'THREE.JSONLoader: Couldn\'t load ' + url + ' (' + xhr.status + ')' );
  7629. }
  7630. } else if ( xhr.readyState === xhr.LOADING ) {
  7631. if ( callbackProgress ) {
  7632. if ( length === 0 ) {
  7633. length = xhr.getResponseHeader( 'Content-Length' );
  7634. }
  7635. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7636. }
  7637. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7638. if ( callbackProgress !== undefined ) {
  7639. length = xhr.getResponseHeader( 'Content-Length' );
  7640. }
  7641. }
  7642. };
  7643. xhr.open( 'GET', url, true );
  7644. xhr.withCredentials = this.withCredentials;
  7645. xhr.send( null );
  7646. };
  7647. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7648. var geometry = new THREE.Geometry(),
  7649. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7650. parseModel( scale );
  7651. parseSkin();
  7652. parseMorphing( scale );
  7653. geometry.computeFaceNormals();
  7654. geometry.computeBoundingSphere();
  7655. function parseModel( scale ) {
  7656. function isBitSet( value, position ) {
  7657. return value & ( 1 << position );
  7658. }
  7659. var i, j, fi,
  7660. offset, zLength,
  7661. colorIndex, normalIndex, uvIndex,
  7662. type,
  7663. isQuad,
  7664. hasMaterial,
  7665. hasFaceVertexUv,
  7666. hasFaceNormal, hasFaceVertexNormal,
  7667. hasFaceColor, hasFaceVertexColor,
  7668. vertex, face, faceA, faceB, hex, normal,
  7669. uvLayer, uv, u, v,
  7670. faces = json.faces,
  7671. vertices = json.vertices,
  7672. normals = json.normals,
  7673. colors = json.colors,
  7674. nUvLayers = 0;
  7675. if ( json.uvs !== undefined ) {
  7676. // disregard empty arrays
  7677. for ( i = 0; i < json.uvs.length; i ++ ) {
  7678. if ( json.uvs[ i ].length ) nUvLayers ++;
  7679. }
  7680. for ( i = 0; i < nUvLayers; i ++ ) {
  7681. geometry.faceVertexUvs[ i ] = [];
  7682. }
  7683. }
  7684. offset = 0;
  7685. zLength = vertices.length;
  7686. while ( offset < zLength ) {
  7687. vertex = new THREE.Vector3();
  7688. vertex.x = vertices[ offset ++ ] * scale;
  7689. vertex.y = vertices[ offset ++ ] * scale;
  7690. vertex.z = vertices[ offset ++ ] * scale;
  7691. geometry.vertices.push( vertex );
  7692. }
  7693. offset = 0;
  7694. zLength = faces.length;
  7695. while ( offset < zLength ) {
  7696. type = faces[ offset ++ ];
  7697. isQuad = isBitSet( type, 0 );
  7698. hasMaterial = isBitSet( type, 1 );
  7699. hasFaceVertexUv = isBitSet( type, 3 );
  7700. hasFaceNormal = isBitSet( type, 4 );
  7701. hasFaceVertexNormal = isBitSet( type, 5 );
  7702. hasFaceColor = isBitSet( type, 6 );
  7703. hasFaceVertexColor = isBitSet( type, 7 );
  7704. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7705. if ( isQuad ) {
  7706. faceA = new THREE.Face3();
  7707. faceA.a = faces[ offset ];
  7708. faceA.b = faces[ offset + 1 ];
  7709. faceA.c = faces[ offset + 3 ];
  7710. faceB = new THREE.Face3();
  7711. faceB.a = faces[ offset + 1 ];
  7712. faceB.b = faces[ offset + 2 ];
  7713. faceB.c = faces[ offset + 3 ];
  7714. offset += 4;
  7715. if ( hasMaterial ) {
  7716. offset ++;
  7717. }
  7718. // to get face <=> uv index correspondence
  7719. fi = geometry.faces.length;
  7720. if ( hasFaceVertexUv ) {
  7721. for ( i = 0; i < nUvLayers; i ++ ) {
  7722. uvLayer = json.uvs[ i ];
  7723. geometry.faceVertexUvs[ i ][ fi ] = [];
  7724. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  7725. for ( j = 0; j < 4; j ++ ) {
  7726. uvIndex = faces[ offset ++ ];
  7727. u = uvLayer[ uvIndex * 2 ];
  7728. v = uvLayer[ uvIndex * 2 + 1 ];
  7729. uv = new THREE.Vector2( u, v );
  7730. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7731. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7732. }
  7733. }
  7734. }
  7735. if ( hasFaceNormal ) {
  7736. normalIndex = faces[ offset ++ ] * 3;
  7737. faceA.normal.set(
  7738. normals[ normalIndex ++ ],
  7739. normals[ normalIndex ++ ],
  7740. normals[ normalIndex ]
  7741. );
  7742. faceB.normal.copy( faceA.normal );
  7743. }
  7744. if ( hasFaceVertexNormal ) {
  7745. for ( i = 0; i < 4; i ++ ) {
  7746. normalIndex = faces[ offset ++ ] * 3;
  7747. normal = new THREE.Vector3(
  7748. normals[ normalIndex ++ ],
  7749. normals[ normalIndex ++ ],
  7750. normals[ normalIndex ]
  7751. );
  7752. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7753. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7754. }
  7755. }
  7756. if ( hasFaceColor ) {
  7757. colorIndex = faces[ offset ++ ];
  7758. hex = colors[ colorIndex ];
  7759. faceA.color.setHex( hex );
  7760. faceB.color.setHex( hex );
  7761. }
  7762. if ( hasFaceVertexColor ) {
  7763. for ( i = 0; i < 4; i ++ ) {
  7764. colorIndex = faces[ offset ++ ];
  7765. hex = colors[ colorIndex ];
  7766. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7767. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7768. }
  7769. }
  7770. geometry.faces.push( faceA );
  7771. geometry.faces.push( faceB );
  7772. } else {
  7773. face = new THREE.Face3();
  7774. face.a = faces[ offset ++ ];
  7775. face.b = faces[ offset ++ ];
  7776. face.c = faces[ offset ++ ];
  7777. if ( hasMaterial ) {
  7778. offset ++;
  7779. }
  7780. // to get face <=> uv index correspondence
  7781. fi = geometry.faces.length;
  7782. if ( hasFaceVertexUv ) {
  7783. for ( i = 0; i < nUvLayers; i ++ ) {
  7784. uvLayer = json.uvs[ i ];
  7785. geometry.faceVertexUvs[ i ][ fi ] = [];
  7786. for ( j = 0; j < 3; j ++ ) {
  7787. uvIndex = faces[ offset ++ ];
  7788. u = uvLayer[ uvIndex * 2 ];
  7789. v = uvLayer[ uvIndex * 2 + 1 ];
  7790. uv = new THREE.Vector2( u, v );
  7791. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7792. }
  7793. }
  7794. }
  7795. if ( hasFaceNormal ) {
  7796. normalIndex = faces[ offset ++ ] * 3;
  7797. face.normal.set(
  7798. normals[ normalIndex ++ ],
  7799. normals[ normalIndex ++ ],
  7800. normals[ normalIndex ]
  7801. );
  7802. }
  7803. if ( hasFaceVertexNormal ) {
  7804. for ( i = 0; i < 3; i ++ ) {
  7805. normalIndex = faces[ offset ++ ] * 3;
  7806. normal = new THREE.Vector3(
  7807. normals[ normalIndex ++ ],
  7808. normals[ normalIndex ++ ],
  7809. normals[ normalIndex ]
  7810. );
  7811. face.vertexNormals.push( normal );
  7812. }
  7813. }
  7814. if ( hasFaceColor ) {
  7815. colorIndex = faces[ offset ++ ];
  7816. face.color.setHex( colors[ colorIndex ] );
  7817. }
  7818. if ( hasFaceVertexColor ) {
  7819. for ( i = 0; i < 3; i ++ ) {
  7820. colorIndex = faces[ offset ++ ];
  7821. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7822. }
  7823. }
  7824. geometry.faces.push( face );
  7825. }
  7826. }
  7827. }
  7828. function parseSkin() {
  7829. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7830. if ( json.skinWeights ) {
  7831. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7832. var x = json.skinWeights[ i ];
  7833. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7834. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7835. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7836. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7837. }
  7838. }
  7839. if ( json.skinIndices ) {
  7840. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7841. var a = json.skinIndices[ i ];
  7842. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7843. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7844. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7845. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7846. }
  7847. }
  7848. geometry.bones = json.bones;
  7849. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7850. console.warn( 'THREE.JSONLoader: When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7851. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7852. }
  7853. // could change this to json.animations[0] or remove completely
  7854. geometry.animation = json.animation;
  7855. geometry.animations = json.animations;
  7856. }
  7857. function parseMorphing( scale ) {
  7858. if ( json.morphTargets !== undefined ) {
  7859. var i, l, v, vl, dstVertices, srcVertices;
  7860. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7861. geometry.morphTargets[ i ] = {};
  7862. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7863. geometry.morphTargets[ i ].vertices = [];
  7864. dstVertices = geometry.morphTargets[ i ].vertices;
  7865. srcVertices = json.morphTargets [ i ].vertices;
  7866. for ( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7867. var vertex = new THREE.Vector3();
  7868. vertex.x = srcVertices[ v ] * scale;
  7869. vertex.y = srcVertices[ v + 1 ] * scale;
  7870. vertex.z = srcVertices[ v + 2 ] * scale;
  7871. dstVertices.push( vertex );
  7872. }
  7873. }
  7874. }
  7875. if ( json.morphColors !== undefined ) {
  7876. var i, l, c, cl, dstColors, srcColors, color;
  7877. for ( i = 0, l = json.morphColors.length; i < l; i ++ ) {
  7878. geometry.morphColors[ i ] = {};
  7879. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7880. geometry.morphColors[ i ].colors = [];
  7881. dstColors = geometry.morphColors[ i ].colors;
  7882. srcColors = json.morphColors [ i ].colors;
  7883. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7884. color = new THREE.Color( 0xffaa00 );
  7885. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7886. dstColors.push( color );
  7887. }
  7888. }
  7889. }
  7890. }
  7891. if ( json.materials === undefined || json.materials.length === 0 ) {
  7892. return { geometry: geometry };
  7893. } else {
  7894. var materials = this.initMaterials( json.materials, texturePath );
  7895. if ( this.needsTangents( materials ) ) {
  7896. geometry.computeTangents();
  7897. }
  7898. return { geometry: geometry, materials: materials };
  7899. }
  7900. };
  7901. // File:src/loaders/LoadingManager.js
  7902. /**
  7903. * @author mrdoob / http://mrdoob.com/
  7904. */
  7905. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7906. var scope = this;
  7907. var loaded = 0, total = 0;
  7908. this.onLoad = onLoad;
  7909. this.onProgress = onProgress;
  7910. this.onError = onError;
  7911. this.itemStart = function ( url ) {
  7912. total ++;
  7913. };
  7914. this.itemEnd = function ( url ) {
  7915. loaded ++;
  7916. if ( scope.onProgress !== undefined ) {
  7917. scope.onProgress( url, loaded, total );
  7918. }
  7919. if ( loaded === total && scope.onLoad !== undefined ) {
  7920. scope.onLoad();
  7921. }
  7922. };
  7923. };
  7924. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7925. // File:src/loaders/BufferGeometryLoader.js
  7926. /**
  7927. * @author mrdoob / http://mrdoob.com/
  7928. */
  7929. THREE.BufferGeometryLoader = function ( manager ) {
  7930. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7931. };
  7932. THREE.BufferGeometryLoader.prototype = {
  7933. constructor: THREE.BufferGeometryLoader,
  7934. load: function ( url, onLoad, onProgress, onError ) {
  7935. var scope = this;
  7936. var loader = new THREE.XHRLoader( scope.manager );
  7937. loader.setCrossOrigin( this.crossOrigin );
  7938. loader.load( url, function ( text ) {
  7939. onLoad( scope.parse( JSON.parse( text ) ) );
  7940. }, onProgress, onError );
  7941. },
  7942. setCrossOrigin: function ( value ) {
  7943. this.crossOrigin = value;
  7944. },
  7945. parse: function ( json ) {
  7946. var geometry = new THREE.BufferGeometry();
  7947. var attributes = json.data.attributes;
  7948. for ( var key in attributes ) {
  7949. var attribute = attributes[ key ];
  7950. var typedArray = new self[ attribute.type ]( attribute.array );
  7951. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize ) );
  7952. }
  7953. var offsets = json.data.offsets;
  7954. if ( offsets !== undefined ) {
  7955. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7956. }
  7957. var boundingSphere = json.data.boundingSphere;
  7958. if ( boundingSphere !== undefined ) {
  7959. var center = new THREE.Vector3();
  7960. if ( boundingSphere.center !== undefined ) {
  7961. center.fromArray( boundingSphere.center );
  7962. }
  7963. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  7964. }
  7965. return geometry;
  7966. }
  7967. };
  7968. // File:src/loaders/MaterialLoader.js
  7969. /**
  7970. * @author mrdoob / http://mrdoob.com/
  7971. */
  7972. THREE.MaterialLoader = function ( manager ) {
  7973. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7974. };
  7975. THREE.MaterialLoader.prototype = {
  7976. constructor: THREE.MaterialLoader,
  7977. load: function ( url, onLoad, onProgress, onError ) {
  7978. var scope = this;
  7979. var loader = new THREE.XHRLoader( scope.manager );
  7980. loader.setCrossOrigin( this.crossOrigin );
  7981. loader.load( url, function ( text ) {
  7982. onLoad( scope.parse( JSON.parse( text ) ) );
  7983. }, onProgress, onError );
  7984. },
  7985. setCrossOrigin: function ( value ) {
  7986. this.crossOrigin = value;
  7987. },
  7988. parse: function ( json ) {
  7989. var material = new THREE[ json.type ];
  7990. if ( json.color !== undefined ) material.color.setHex( json.color );
  7991. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7992. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7993. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7994. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  7995. if ( json.attributes !== undefined ) material.attributes = json.attributes;
  7996. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  7997. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  7998. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7999. if ( json.shading !== undefined ) material.shading = json.shading;
  8000. if ( json.blending !== undefined ) material.blending = json.blending;
  8001. if ( json.side !== undefined ) material.side = json.side;
  8002. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  8003. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  8004. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  8005. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  8006. // for PointCloudMaterial
  8007. if ( json.size !== undefined ) material.size = json.size;
  8008. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  8009. if ( json.materials !== undefined ) {
  8010. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  8011. material.materials.push( this.parse( json.materials[ i ] ) );
  8012. }
  8013. }
  8014. return material;
  8015. }
  8016. };
  8017. // File:src/loaders/ObjectLoader.js
  8018. /**
  8019. * @author mrdoob / http://mrdoob.com/
  8020. */
  8021. THREE.ObjectLoader = function ( manager ) {
  8022. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8023. this.texturePath = '';
  8024. };
  8025. THREE.ObjectLoader.prototype = {
  8026. constructor: THREE.ObjectLoader,
  8027. load: function ( url, onLoad, onProgress, onError ) {
  8028. if ( this.texturePath === '' ) {
  8029. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  8030. }
  8031. var scope = this;
  8032. var loader = new THREE.XHRLoader( scope.manager );
  8033. loader.setCrossOrigin( this.crossOrigin );
  8034. loader.load( url, function ( text ) {
  8035. scope.parse( JSON.parse( text ), onLoad );
  8036. }, onProgress, onError );
  8037. },
  8038. setTexturePath: function ( value ) {
  8039. this.texturePath = value;
  8040. },
  8041. setCrossOrigin: function ( value ) {
  8042. this.crossOrigin = value;
  8043. },
  8044. parse: function ( json, onLoad ) {
  8045. var geometries = this.parseGeometries( json.geometries );
  8046. var images = this.parseImages( json.images, function () {
  8047. if ( onLoad !== undefined ) onLoad( object );
  8048. } );
  8049. var textures = this.parseTextures( json.textures, images );
  8050. var materials = this.parseMaterials( json.materials, textures );
  8051. var object = this.parseObject( json.object, geometries, materials );
  8052. if ( json.images === undefined || json.images.length === 0 ) {
  8053. if ( onLoad !== undefined ) onLoad( object );
  8054. }
  8055. return object;
  8056. },
  8057. parseGeometries: function ( json ) {
  8058. var geometries = {};
  8059. if ( json !== undefined ) {
  8060. var geometryLoader = new THREE.JSONLoader();
  8061. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  8062. for ( var i = 0, l = json.length; i < l; i ++ ) {
  8063. var geometry;
  8064. var data = json[ i ];
  8065. switch ( data.type ) {
  8066. case 'PlaneGeometry':
  8067. case 'PlaneBufferGeometry':
  8068. geometry = new THREE[ data.type ](
  8069. data.width,
  8070. data.height,
  8071. data.widthSegments,
  8072. data.heightSegments
  8073. );
  8074. break;
  8075. case 'BoxGeometry':
  8076. case 'CubeGeometry': // backwards compatible
  8077. geometry = new THREE.BoxGeometry(
  8078. data.width,
  8079. data.height,
  8080. data.depth,
  8081. data.widthSegments,
  8082. data.heightSegments,
  8083. data.depthSegments
  8084. );
  8085. break;
  8086. case 'CircleGeometry':
  8087. geometry = new THREE.CircleGeometry(
  8088. data.radius,
  8089. data.segments
  8090. );
  8091. break;
  8092. case 'CylinderGeometry':
  8093. geometry = new THREE.CylinderGeometry(
  8094. data.radiusTop,
  8095. data.radiusBottom,
  8096. data.height,
  8097. data.radialSegments,
  8098. data.heightSegments,
  8099. data.openEnded
  8100. );
  8101. break;
  8102. case 'SphereGeometry':
  8103. geometry = new THREE.SphereGeometry(
  8104. data.radius,
  8105. data.widthSegments,
  8106. data.heightSegments,
  8107. data.phiStart,
  8108. data.phiLength,
  8109. data.thetaStart,
  8110. data.thetaLength
  8111. );
  8112. break;
  8113. case 'IcosahedronGeometry':
  8114. geometry = new THREE.IcosahedronGeometry(
  8115. data.radius,
  8116. data.detail
  8117. );
  8118. break;
  8119. case 'TorusGeometry':
  8120. geometry = new THREE.TorusGeometry(
  8121. data.radius,
  8122. data.tube,
  8123. data.radialSegments,
  8124. data.tubularSegments,
  8125. data.arc
  8126. );
  8127. break;
  8128. case 'TorusKnotGeometry':
  8129. geometry = new THREE.TorusKnotGeometry(
  8130. data.radius,
  8131. data.tube,
  8132. data.radialSegments,
  8133. data.tubularSegments,
  8134. data.p,
  8135. data.q,
  8136. data.heightScale
  8137. );
  8138. break;
  8139. case 'BufferGeometry':
  8140. geometry = bufferGeometryLoader.parse( data );
  8141. break;
  8142. case 'Geometry':
  8143. geometry = geometryLoader.parse( data.data ).geometry;
  8144. break;
  8145. case 'TextGeometry':
  8146. geometry = new THREE.TextGeometry(
  8147. data.text,
  8148. data.data
  8149. );
  8150. break;
  8151. }
  8152. geometry.uuid = data.uuid;
  8153. if ( data.name !== undefined ) geometry.name = data.name;
  8154. geometries[ data.uuid ] = geometry;
  8155. }
  8156. }
  8157. return geometries;
  8158. },
  8159. parseMaterials: function ( json, textures ) {
  8160. var materials = {};
  8161. if ( json !== undefined ) {
  8162. var getTexture = function ( name ) {
  8163. if ( textures[ name ] === undefined ) {
  8164. console.warn( 'THREE.ObjectLoader: Undefined texture', name );
  8165. }
  8166. return textures[ name ];
  8167. };
  8168. var loader = new THREE.MaterialLoader();
  8169. for ( var i = 0, l = json.length; i < l; i ++ ) {
  8170. var data = json[ i ];
  8171. var material = loader.parse( data );
  8172. material.uuid = data.uuid;
  8173. if ( data.depthTest !== undefined ) material.depthTest = data.depthTest;
  8174. if ( data.depthWrite !== undefined ) material.depthWrite = data.depthWrite;
  8175. if ( data.name !== undefined ) material.name = data.name;
  8176. if ( data.map !== undefined ) material.map = getTexture( data.map );
  8177. if ( data.alphaMap !== undefined ) {
  8178. material.alphaMap = getTexture( data.alphaMap );
  8179. material.transparent = true;
  8180. }
  8181. if ( data.bumpMap !== undefined ) material.bumpMap = getTexture( data.bumpMap );
  8182. if ( data.bumpScale !== undefined ) material.bumpScale = data.bumpScale;
  8183. if ( data.normalMap !== undefined ) material.normalMap = getTexture( data.normalMap );
  8184. if ( data.normalScale ) material.normalScale = new THREE.Vector2( data.normalScale, data.normalScale );
  8185. if ( data.specularMap !== undefined ) material.specularMap = getTexture( data.specularMap );
  8186. if ( data.envMap !== undefined ) {
  8187. material.envMap = getTexture( data.envMap );
  8188. material.combine = THREE.MultiplyOperation;
  8189. }
  8190. if ( data.reflectivity ) material.reflectivity = data.reflectivity;
  8191. if ( data.lightMap !== undefined ) material.lightMap = getTexture( data.lightMap );
  8192. if ( data.lightMapIntensity !== undefined ) material.lightMapIntensity = data.lightMapIntensity;
  8193. if ( data.aoMap !== undefined ) material.aoMap = getTexture( data.aoMap );
  8194. if ( data.aoMapIntensity !== undefined ) material.aoMapIntensity = data.aoMapIntensity;
  8195. materials[ data.uuid ] = material;
  8196. }
  8197. }
  8198. return materials;
  8199. },
  8200. parseImages: function ( json, onLoad ) {
  8201. var scope = this;
  8202. var images = {};
  8203. if ( json !== undefined && json.length > 0 ) {
  8204. var manager = new THREE.LoadingManager( onLoad );
  8205. var loader = new THREE.ImageLoader( manager );
  8206. loader.setCrossOrigin( this.crossOrigin );
  8207. var loadImage = function ( url ) {
  8208. scope.manager.itemStart( url );
  8209. return loader.load( url, function () {
  8210. scope.manager.itemEnd( url );
  8211. } );
  8212. };
  8213. for ( var i = 0, l = json.length; i < l; i ++ ) {
  8214. var image = json[ i ];
  8215. images[ image.uuid ] = loadImage( image.url );
  8216. }
  8217. }
  8218. return images;
  8219. },
  8220. parseTextures: function ( json, images ) {
  8221. function parseConstant( value ) {
  8222. if ( typeof( value ) === 'number' ) return value;
  8223. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  8224. return THREE[ value ];
  8225. }
  8226. var textures = {};
  8227. if ( json !== undefined ) {
  8228. for ( var i = 0, l = json.length; i < l; i ++ ) {
  8229. var data = json[ i ];
  8230. if ( data.image === undefined ) {
  8231. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  8232. }
  8233. if ( images[ data.image ] === undefined ) {
  8234. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  8235. }
  8236. var texture = new THREE.Texture( images[ data.image ] );
  8237. texture.needsUpdate = true;
  8238. texture.uuid = data.uuid;
  8239. if ( data.name !== undefined ) texture.name = data.name;
  8240. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  8241. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  8242. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  8243. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  8244. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  8245. if ( Array.isArray( data.wrap ) ) {
  8246. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  8247. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  8248. }
  8249. textures[ data.uuid ] = texture;
  8250. }
  8251. }
  8252. return textures;
  8253. },
  8254. parseObject: function () {
  8255. var matrix = new THREE.Matrix4();
  8256. return function ( data, geometries, materials ) {
  8257. var object;
  8258. var getGeometry = function ( name ) {
  8259. if ( geometries[ name ] === undefined ) {
  8260. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  8261. }
  8262. return geometries[ name ];
  8263. };
  8264. var getMaterial = function ( name ) {
  8265. if ( materials[ name ] === undefined ) {
  8266. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  8267. }
  8268. return materials[ name ];
  8269. };
  8270. switch ( data.type ) {
  8271. case 'Scene':
  8272. object = new THREE.Scene();
  8273. break;
  8274. case 'PerspectiveCamera':
  8275. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  8276. break;
  8277. case 'OrthographicCamera':
  8278. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  8279. break;
  8280. case 'AmbientLight':
  8281. object = new THREE.AmbientLight( data.color );
  8282. break;
  8283. case 'DirectionalLight':
  8284. object = new THREE.DirectionalLight( data.color, data.intensity );
  8285. break;
  8286. case 'PointLight':
  8287. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  8288. break;
  8289. case 'SpotLight':
  8290. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent, data.decay );
  8291. break;
  8292. case 'HemisphereLight':
  8293. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  8294. break;
  8295. case 'Mesh':
  8296. object = new THREE.Mesh( getGeometry( data.geometry ), getMaterial( data.material ) );
  8297. break;
  8298. case 'Line':
  8299. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  8300. break;
  8301. case 'PointCloud':
  8302. object = new THREE.PointCloud( getGeometry( data.geometry ), getMaterial( data.material ) );
  8303. break;
  8304. case 'Sprite':
  8305. object = new THREE.Sprite( getMaterial( data.material ) );
  8306. break;
  8307. case 'Group':
  8308. object = new THREE.Group();
  8309. break;
  8310. default:
  8311. object = new THREE.Object3D();
  8312. }
  8313. object.uuid = data.uuid;
  8314. if ( data.name !== undefined ) object.name = data.name;
  8315. if ( data.matrix !== undefined ) {
  8316. matrix.fromArray( data.matrix );
  8317. matrix.decompose( object.position, object.quaternion, object.scale );
  8318. } else {
  8319. if ( data.position !== undefined ) object.position.fromArray( data.position );
  8320. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  8321. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  8322. }
  8323. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  8324. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  8325. if ( data.visible !== undefined ) object.visible = data.visible;
  8326. if ( data.userData !== undefined ) object.userData = data.userData;
  8327. if ( data.children !== undefined ) {
  8328. for ( var child in data.children ) {
  8329. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  8330. }
  8331. }
  8332. return object;
  8333. }
  8334. }()
  8335. };
  8336. // File:src/loaders/TextureLoader.js
  8337. /**
  8338. * @author mrdoob / http://mrdoob.com/
  8339. */
  8340. THREE.TextureLoader = function ( manager ) {
  8341. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8342. };
  8343. THREE.TextureLoader.prototype = {
  8344. constructor: THREE.TextureLoader,
  8345. load: function ( url, onLoad, onProgress, onError ) {
  8346. var scope = this;
  8347. var loader = new THREE.ImageLoader( scope.manager );
  8348. loader.setCrossOrigin( this.crossOrigin );
  8349. loader.load( url, function ( image ) {
  8350. var texture = new THREE.Texture( image );
  8351. texture.needsUpdate = true;
  8352. if ( onLoad !== undefined ) {
  8353. onLoad( texture );
  8354. }
  8355. }, onProgress, onError );
  8356. },
  8357. setCrossOrigin: function ( value ) {
  8358. this.crossOrigin = value;
  8359. }
  8360. };
  8361. // File:src/loaders/BinaryTextureLoader.js
  8362. /**
  8363. * @author Nikos M. / https://github.com/foo123/
  8364. *
  8365. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  8366. */
  8367. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function () {
  8368. // override in sub classes
  8369. this._parser = null;
  8370. };
  8371. THREE.BinaryTextureLoader.prototype = {
  8372. constructor: THREE.BinaryTextureLoader,
  8373. load: function ( url, onLoad, onProgress, onError ) {
  8374. var scope = this;
  8375. var texture = new THREE.DataTexture( );
  8376. var loader = new THREE.XHRLoader();
  8377. loader.setResponseType( 'arraybuffer' );
  8378. loader.load( url, function ( buffer ) {
  8379. var texData = scope._parser( buffer );
  8380. if ( !texData ) return;
  8381. if ( undefined !== texData.image ) {
  8382. texture.image = texData.image;
  8383. } else if ( undefined !== texData.data ) {
  8384. texture.image.width = texData.width;
  8385. texture.image.height = texData.height;
  8386. texture.image.data = texData.data;
  8387. }
  8388. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  8389. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  8390. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  8391. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  8392. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  8393. if ( undefined !== texData.format ) {
  8394. texture.format = texData.format;
  8395. }
  8396. if ( undefined !== texData.type ) {
  8397. texture.type = texData.type;
  8398. }
  8399. if ( undefined !== texData.mipmaps ) {
  8400. texture.mipmaps = texData.mipmaps;
  8401. }
  8402. if ( 1 === texData.mipmapCount ) {
  8403. texture.minFilter = THREE.LinearFilter;
  8404. }
  8405. texture.needsUpdate = true;
  8406. if ( onLoad ) onLoad( texture, texData );
  8407. }, onProgress, onError );
  8408. return texture;
  8409. }
  8410. };
  8411. // File:src/loaders/CompressedTextureLoader.js
  8412. /**
  8413. * @author mrdoob / http://mrdoob.com/
  8414. *
  8415. * Abstract Base class to block based textures loader (dds, pvr, ...)
  8416. */
  8417. THREE.CompressedTextureLoader = function () {
  8418. // override in sub classes
  8419. this._parser = null;
  8420. };
  8421. THREE.CompressedTextureLoader.prototype = {
  8422. constructor: THREE.CompressedTextureLoader,
  8423. load: function ( url, onLoad, onError ) {
  8424. var scope = this;
  8425. var images = [];
  8426. var texture = new THREE.CompressedTexture();
  8427. texture.image = images;
  8428. var loader = new THREE.XHRLoader();
  8429. loader.setResponseType( 'arraybuffer' );
  8430. if ( Array.isArray( url ) ) {
  8431. var loaded = 0;
  8432. var loadTexture = function ( i ) {
  8433. loader.load( url[ i ], function ( buffer ) {
  8434. var texDatas = scope._parser( buffer, true );
  8435. images[ i ] = {
  8436. width: texDatas.width,
  8437. height: texDatas.height,
  8438. format: texDatas.format,
  8439. mipmaps: texDatas.mipmaps
  8440. };
  8441. loaded += 1;
  8442. if ( loaded === 6 ) {
  8443. if (texDatas.mipmapCount === 1)
  8444. texture.minFilter = THREE.LinearFilter;
  8445. texture.format = texDatas.format;
  8446. texture.needsUpdate = true;
  8447. if ( onLoad ) onLoad( texture );
  8448. }
  8449. } );
  8450. };
  8451. for ( var i = 0, il = url.length; i < il; ++ i ) {
  8452. loadTexture( i );
  8453. }
  8454. } else {
  8455. // compressed cubemap texture stored in a single DDS file
  8456. loader.load( url, function ( buffer ) {
  8457. var texDatas = scope._parser( buffer, true );
  8458. if ( texDatas.isCubemap ) {
  8459. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  8460. for ( var f = 0; f < faces; f ++ ) {
  8461. images[ f ] = { mipmaps : [] };
  8462. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  8463. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  8464. images[ f ].format = texDatas.format;
  8465. images[ f ].width = texDatas.width;
  8466. images[ f ].height = texDatas.height;
  8467. }
  8468. }
  8469. } else {
  8470. texture.image.width = texDatas.width;
  8471. texture.image.height = texDatas.height;
  8472. texture.mipmaps = texDatas.mipmaps;
  8473. }
  8474. if ( texDatas.mipmapCount === 1 ) {
  8475. texture.minFilter = THREE.LinearFilter;
  8476. }
  8477. texture.format = texDatas.format;
  8478. texture.needsUpdate = true;
  8479. if ( onLoad ) onLoad( texture );
  8480. } );
  8481. }
  8482. return texture;
  8483. }
  8484. };
  8485. // File:src/materials/Material.js
  8486. /**
  8487. * @author mrdoob / http://mrdoob.com/
  8488. * @author alteredq / http://alteredqualia.com/
  8489. */
  8490. THREE.Material = function () {
  8491. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  8492. this.uuid = THREE.Math.generateUUID();
  8493. this.name = '';
  8494. this.type = 'Material';
  8495. this.side = THREE.FrontSide;
  8496. this.opacity = 1;
  8497. this.transparent = false;
  8498. this.blending = THREE.NormalBlending;
  8499. this.blendSrc = THREE.SrcAlphaFactor;
  8500. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  8501. this.blendEquation = THREE.AddEquation;
  8502. this.blendSrcAlpha = null;
  8503. this.blendDstAlpha = null;
  8504. this.blendEquationAlpha = null;
  8505. this.depthFunc = THREE.LessEqualDepth;
  8506. this.depthTest = true;
  8507. this.depthWrite = true;
  8508. this.colorWrite = true;
  8509. this.polygonOffset = false;
  8510. this.polygonOffsetFactor = 0;
  8511. this.polygonOffsetUnits = 0;
  8512. this.alphaTest = 0;
  8513. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8514. this.visible = true;
  8515. this._needsUpdate = true;
  8516. };
  8517. THREE.Material.prototype = {
  8518. constructor: THREE.Material,
  8519. get needsUpdate () {
  8520. return this._needsUpdate;
  8521. },
  8522. set needsUpdate ( value ) {
  8523. if ( value === true ) this.update();
  8524. this._needsUpdate = value;
  8525. },
  8526. setValues: function ( values ) {
  8527. if ( values === undefined ) return;
  8528. for ( var key in values ) {
  8529. var newValue = values[ key ];
  8530. if ( newValue === undefined ) {
  8531. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  8532. continue;
  8533. }
  8534. if ( key in this ) {
  8535. var currentValue = this[ key ];
  8536. if ( currentValue instanceof THREE.Color ) {
  8537. currentValue.set( newValue );
  8538. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  8539. currentValue.copy( newValue );
  8540. } else if ( key === 'overdraw' ) {
  8541. // ensure overdraw is backwards-compatible with legacy boolean type
  8542. this[ key ] = Number( newValue );
  8543. } else {
  8544. this[ key ] = newValue;
  8545. }
  8546. }
  8547. }
  8548. },
  8549. toJSON: function ( meta ) {
  8550. var data = {
  8551. metadata: {
  8552. version: 4.4,
  8553. type: 'Material',
  8554. generator: 'Material.toJSON'
  8555. }
  8556. };
  8557. // standard Material serialization
  8558. data.uuid = this.uuid;
  8559. data.type = this.type;
  8560. if ( this.name !== '' ) data.name = this.name;
  8561. if ( this.color instanceof THREE.Color ) data.color = this.color.getHex();
  8562. if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex();
  8563. if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex();
  8564. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  8565. if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid;
  8566. if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  8567. if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  8568. if ( this.bumpMap instanceof THREE.Texture ) {
  8569. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  8570. data.bumpScale = this.bumpScale;
  8571. }
  8572. if ( this.normalMap instanceof THREE.Texture ) {
  8573. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  8574. data.normalScale = this.normalScale; // Removed for now, causes issue in editor ui.js
  8575. }
  8576. if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  8577. if ( this.envMap instanceof THREE.Texture ) {
  8578. data.envMap = this.envMap.toJSON( meta ).uuid;
  8579. data.reflectivity = this.reflectivity; // Scale behind envMap
  8580. }
  8581. if ( this.size !== undefined ) data.size = this.size;
  8582. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  8583. if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  8584. if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  8585. if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  8586. if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side;
  8587. if ( this.opacity < 1 ) data.opacity = this.opacity;
  8588. if ( this.transparent === true ) data.transparent = this.transparent;
  8589. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  8590. return data;
  8591. },
  8592. clone: function ( material ) {
  8593. if ( material === undefined ) material = new THREE.Material();
  8594. material.name = this.name;
  8595. material.side = this.side;
  8596. material.opacity = this.opacity;
  8597. material.transparent = this.transparent;
  8598. material.blending = this.blending;
  8599. material.blendSrc = this.blendSrc;
  8600. material.blendDst = this.blendDst;
  8601. material.blendEquation = this.blendEquation;
  8602. material.blendSrcAlpha = this.blendSrcAlpha;
  8603. material.blendDstAlpha = this.blendDstAlpha;
  8604. material.blendEquationAlpha = this.blendEquationAlpha;
  8605. material.depthFunc = this.depthFunc;
  8606. material.depthTest = this.depthTest;
  8607. material.depthWrite = this.depthWrite;
  8608. material.polygonOffset = this.polygonOffset;
  8609. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8610. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8611. material.alphaTest = this.alphaTest;
  8612. material.overdraw = this.overdraw;
  8613. material.visible = this.visible;
  8614. return material;
  8615. },
  8616. update: function () {
  8617. this.dispatchEvent( { type: 'update' } );
  8618. },
  8619. dispose: function () {
  8620. this.dispatchEvent( { type: 'dispose' } );
  8621. }
  8622. };
  8623. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8624. THREE.MaterialIdCount = 0;
  8625. // File:src/materials/LineBasicMaterial.js
  8626. /**
  8627. * @author mrdoob / http://mrdoob.com/
  8628. * @author alteredq / http://alteredqualia.com/
  8629. *
  8630. * parameters = {
  8631. * color: <hex>,
  8632. * opacity: <float>,
  8633. *
  8634. * blending: THREE.NormalBlending,
  8635. * depthTest: <bool>,
  8636. * depthWrite: <bool>,
  8637. *
  8638. * linewidth: <float>,
  8639. * linecap: "round",
  8640. * linejoin: "round",
  8641. *
  8642. * vertexColors: <bool>
  8643. *
  8644. * fog: <bool>
  8645. * }
  8646. */
  8647. THREE.LineBasicMaterial = function ( parameters ) {
  8648. THREE.Material.call( this );
  8649. this.type = 'LineBasicMaterial';
  8650. this.color = new THREE.Color( 0xffffff );
  8651. this.linewidth = 1;
  8652. this.linecap = 'round';
  8653. this.linejoin = 'round';
  8654. this.vertexColors = THREE.NoColors;
  8655. this.fog = true;
  8656. this.setValues( parameters );
  8657. };
  8658. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8659. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  8660. THREE.LineBasicMaterial.prototype.clone = function () {
  8661. var material = new THREE.LineBasicMaterial();
  8662. THREE.Material.prototype.clone.call( this, material );
  8663. material.color.copy( this.color );
  8664. material.linewidth = this.linewidth;
  8665. material.linecap = this.linecap;
  8666. material.linejoin = this.linejoin;
  8667. material.vertexColors = this.vertexColors;
  8668. material.fog = this.fog;
  8669. return material;
  8670. };
  8671. // File:src/materials/LineDashedMaterial.js
  8672. /**
  8673. * @author alteredq / http://alteredqualia.com/
  8674. *
  8675. * parameters = {
  8676. * color: <hex>,
  8677. * opacity: <float>,
  8678. *
  8679. * blending: THREE.NormalBlending,
  8680. * depthTest: <bool>,
  8681. * depthWrite: <bool>,
  8682. *
  8683. * linewidth: <float>,
  8684. *
  8685. * scale: <float>,
  8686. * dashSize: <float>,
  8687. * gapSize: <float>,
  8688. *
  8689. * vertexColors: <bool>
  8690. *
  8691. * fog: <bool>
  8692. * }
  8693. */
  8694. THREE.LineDashedMaterial = function ( parameters ) {
  8695. THREE.Material.call( this );
  8696. this.type = 'LineDashedMaterial';
  8697. this.color = new THREE.Color( 0xffffff );
  8698. this.linewidth = 1;
  8699. this.scale = 1;
  8700. this.dashSize = 3;
  8701. this.gapSize = 1;
  8702. this.vertexColors = false;
  8703. this.fog = true;
  8704. this.setValues( parameters );
  8705. };
  8706. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8707. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  8708. THREE.LineDashedMaterial.prototype.clone = function () {
  8709. var material = new THREE.LineDashedMaterial();
  8710. THREE.Material.prototype.clone.call( this, material );
  8711. material.color.copy( this.color );
  8712. material.linewidth = this.linewidth;
  8713. material.scale = this.scale;
  8714. material.dashSize = this.dashSize;
  8715. material.gapSize = this.gapSize;
  8716. material.vertexColors = this.vertexColors;
  8717. material.fog = this.fog;
  8718. return material;
  8719. };
  8720. // File:src/materials/MeshBasicMaterial.js
  8721. /**
  8722. * @author mrdoob / http://mrdoob.com/
  8723. * @author alteredq / http://alteredqualia.com/
  8724. *
  8725. * parameters = {
  8726. * color: <hex>,
  8727. * opacity: <float>,
  8728. * map: new THREE.Texture( <Image> ),
  8729. *
  8730. * aoMap: new THREE.Texture( <Image> ),
  8731. * aoMapIntensity: <float>
  8732. *
  8733. * specularMap: new THREE.Texture( <Image> ),
  8734. *
  8735. * alphaMap: new THREE.Texture( <Image> ),
  8736. *
  8737. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8738. * combine: THREE.Multiply,
  8739. * reflectivity: <float>,
  8740. * refractionRatio: <float>,
  8741. *
  8742. * shading: THREE.SmoothShading,
  8743. * blending: THREE.NormalBlending,
  8744. * depthTest: <bool>,
  8745. * depthWrite: <bool>,
  8746. *
  8747. * wireframe: <boolean>,
  8748. * wireframeLinewidth: <float>,
  8749. *
  8750. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8751. *
  8752. * skinning: <bool>,
  8753. * morphTargets: <bool>,
  8754. *
  8755. * fog: <bool>
  8756. * }
  8757. */
  8758. THREE.MeshBasicMaterial = function ( parameters ) {
  8759. THREE.Material.call( this );
  8760. this.type = 'MeshBasicMaterial';
  8761. this.color = new THREE.Color( 0xffffff ); // emissive
  8762. this.map = null;
  8763. this.aoMap = null;
  8764. this.aoMapIntensity = 1.0;
  8765. this.specularMap = null;
  8766. this.alphaMap = null;
  8767. this.envMap = null;
  8768. this.combine = THREE.MultiplyOperation;
  8769. this.reflectivity = 1;
  8770. this.refractionRatio = 0.98;
  8771. this.fog = true;
  8772. this.shading = THREE.SmoothShading;
  8773. this.wireframe = false;
  8774. this.wireframeLinewidth = 1;
  8775. this.wireframeLinecap = 'round';
  8776. this.wireframeLinejoin = 'round';
  8777. this.vertexColors = THREE.NoColors;
  8778. this.skinning = false;
  8779. this.morphTargets = false;
  8780. this.setValues( parameters );
  8781. };
  8782. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8783. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  8784. THREE.MeshBasicMaterial.prototype.clone = function () {
  8785. var material = new THREE.MeshBasicMaterial();
  8786. THREE.Material.prototype.clone.call( this, material );
  8787. material.color.copy( this.color );
  8788. material.map = this.map;
  8789. material.aoMap = this.aoMap;
  8790. material.aoMapIntensity = this.aoMapIntensity;
  8791. material.specularMap = this.specularMap;
  8792. material.alphaMap = this.alphaMap;
  8793. material.envMap = this.envMap;
  8794. material.combine = this.combine;
  8795. material.reflectivity = this.reflectivity;
  8796. material.refractionRatio = this.refractionRatio;
  8797. material.fog = this.fog;
  8798. material.shading = this.shading;
  8799. material.wireframe = this.wireframe;
  8800. material.wireframeLinewidth = this.wireframeLinewidth;
  8801. material.wireframeLinecap = this.wireframeLinecap;
  8802. material.wireframeLinejoin = this.wireframeLinejoin;
  8803. material.vertexColors = this.vertexColors;
  8804. material.skinning = this.skinning;
  8805. material.morphTargets = this.morphTargets;
  8806. return material;
  8807. };
  8808. // File:src/materials/MeshLambertMaterial.js
  8809. /**
  8810. * @author mrdoob / http://mrdoob.com/
  8811. * @author alteredq / http://alteredqualia.com/
  8812. *
  8813. * parameters = {
  8814. * color: <hex>,
  8815. * emissive: <hex>,
  8816. * opacity: <float>,
  8817. *
  8818. * map: new THREE.Texture( <Image> ),
  8819. *
  8820. * specularMap: new THREE.Texture( <Image> ),
  8821. *
  8822. * alphaMap: new THREE.Texture( <Image> ),
  8823. *
  8824. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8825. * combine: THREE.Multiply,
  8826. * reflectivity: <float>,
  8827. * refractionRatio: <float>,
  8828. *
  8829. * shading: THREE.SmoothShading,
  8830. * blending: THREE.NormalBlending,
  8831. * depthTest: <bool>,
  8832. * depthWrite: <bool>,
  8833. *
  8834. * wireframe: <boolean>,
  8835. * wireframeLinewidth: <float>,
  8836. *
  8837. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8838. *
  8839. * skinning: <bool>,
  8840. * morphTargets: <bool>,
  8841. * morphNormals: <bool>,
  8842. *
  8843. * fog: <bool>
  8844. * }
  8845. */
  8846. THREE.MeshLambertMaterial = function ( parameters ) {
  8847. THREE.Material.call( this );
  8848. this.type = 'MeshLambertMaterial';
  8849. this.color = new THREE.Color( 0xffffff ); // diffuse
  8850. this.emissive = new THREE.Color( 0x000000 );
  8851. this.map = null;
  8852. this.specularMap = null;
  8853. this.alphaMap = null;
  8854. this.envMap = null;
  8855. this.combine = THREE.MultiplyOperation;
  8856. this.reflectivity = 1;
  8857. this.refractionRatio = 0.98;
  8858. this.fog = true;
  8859. this.shading = THREE.SmoothShading;
  8860. this.wireframe = false;
  8861. this.wireframeLinewidth = 1;
  8862. this.wireframeLinecap = 'round';
  8863. this.wireframeLinejoin = 'round';
  8864. this.vertexColors = THREE.NoColors;
  8865. this.skinning = false;
  8866. this.morphTargets = false;
  8867. this.morphNormals = false;
  8868. this.setValues( parameters );
  8869. };
  8870. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8871. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  8872. THREE.MeshLambertMaterial.prototype.clone = function () {
  8873. var material = new THREE.MeshLambertMaterial();
  8874. THREE.Material.prototype.clone.call( this, material );
  8875. material.color.copy( this.color );
  8876. material.emissive.copy( this.emissive );
  8877. material.map = this.map;
  8878. material.specularMap = this.specularMap;
  8879. material.alphaMap = this.alphaMap;
  8880. material.envMap = this.envMap;
  8881. material.combine = this.combine;
  8882. material.reflectivity = this.reflectivity;
  8883. material.refractionRatio = this.refractionRatio;
  8884. material.fog = this.fog;
  8885. material.shading = this.shading;
  8886. material.wireframe = this.wireframe;
  8887. material.wireframeLinewidth = this.wireframeLinewidth;
  8888. material.wireframeLinecap = this.wireframeLinecap;
  8889. material.wireframeLinejoin = this.wireframeLinejoin;
  8890. material.vertexColors = this.vertexColors;
  8891. material.skinning = this.skinning;
  8892. material.morphTargets = this.morphTargets;
  8893. material.morphNormals = this.morphNormals;
  8894. return material;
  8895. };
  8896. // File:src/materials/MeshPhongMaterial.js
  8897. /**
  8898. * @author mrdoob / http://mrdoob.com/
  8899. * @author alteredq / http://alteredqualia.com/
  8900. *
  8901. * parameters = {
  8902. * color: <hex>,
  8903. * emissive: <hex>,
  8904. * specular: <hex>,
  8905. * shininess: <float>,
  8906. * opacity: <float>,
  8907. *
  8908. * map: new THREE.Texture( <Image> ),
  8909. *
  8910. * lightMap: new THREE.Texture( <Image> ),
  8911. * lightMapIntensity: <float>
  8912. *
  8913. * aoMap: new THREE.Texture( <Image> ),
  8914. * aoMapIntensity: <float>
  8915. *
  8916. * emissiveMap: new THREE.Texture( <Image> ),
  8917. *
  8918. * bumpMap: new THREE.Texture( <Image> ),
  8919. * bumpScale: <float>,
  8920. *
  8921. * normalMap: new THREE.Texture( <Image> ),
  8922. * normalScale: <Vector2>,
  8923. *
  8924. * specularMap: new THREE.Texture( <Image> ),
  8925. *
  8926. * alphaMap: new THREE.Texture( <Image> ),
  8927. *
  8928. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8929. * combine: THREE.Multiply,
  8930. * reflectivity: <float>,
  8931. * refractionRatio: <float>,
  8932. *
  8933. * shading: THREE.SmoothShading,
  8934. * blending: THREE.NormalBlending,
  8935. * depthTest: <bool>,
  8936. * depthWrite: <bool>,
  8937. *
  8938. * wireframe: <boolean>,
  8939. * wireframeLinewidth: <float>,
  8940. *
  8941. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8942. *
  8943. * skinning: <bool>,
  8944. * morphTargets: <bool>,
  8945. * morphNormals: <bool>,
  8946. *
  8947. * fog: <bool>
  8948. * }
  8949. */
  8950. THREE.MeshPhongMaterial = function ( parameters ) {
  8951. THREE.Material.call( this );
  8952. this.type = 'MeshPhongMaterial';
  8953. this.color = new THREE.Color( 0xffffff ); // diffuse
  8954. this.emissive = new THREE.Color( 0x000000 );
  8955. this.specular = new THREE.Color( 0x111111 );
  8956. this.shininess = 30;
  8957. this.metal = false;
  8958. this.map = null;
  8959. this.lightMap = null;
  8960. this.lightMapIntensity = 1.0;
  8961. this.aoMap = null;
  8962. this.aoMapIntensity = 1.0;
  8963. this.emissiveMap = null;
  8964. this.bumpMap = null;
  8965. this.bumpScale = 1;
  8966. this.normalMap = null;
  8967. this.normalScale = new THREE.Vector2( 1, 1 );
  8968. this.specularMap = null;
  8969. this.alphaMap = null;
  8970. this.envMap = null;
  8971. this.combine = THREE.MultiplyOperation;
  8972. this.reflectivity = 1;
  8973. this.refractionRatio = 0.98;
  8974. this.fog = true;
  8975. this.shading = THREE.SmoothShading;
  8976. this.wireframe = false;
  8977. this.wireframeLinewidth = 1;
  8978. this.wireframeLinecap = 'round';
  8979. this.wireframeLinejoin = 'round';
  8980. this.vertexColors = THREE.NoColors;
  8981. this.skinning = false;
  8982. this.morphTargets = false;
  8983. this.morphNormals = false;
  8984. this.setValues( parameters );
  8985. };
  8986. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8987. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  8988. THREE.MeshPhongMaterial.prototype.clone = function () {
  8989. var material = new THREE.MeshPhongMaterial();
  8990. THREE.Material.prototype.clone.call( this, material );
  8991. material.color.copy( this.color );
  8992. material.emissive.copy( this.emissive );
  8993. material.specular.copy( this.specular );
  8994. material.shininess = this.shininess;
  8995. material.metal = this.metal;
  8996. material.map = this.map;
  8997. material.lightMap = this.lightMap;
  8998. material.lightMapIntensity = this.lightMapIntensity;
  8999. material.aoMap = this.aoMap;
  9000. material.aoMapIntensity = this.aoMapIntensity;
  9001. material.emissiveMap = this.emissiveMap;
  9002. material.bumpMap = this.bumpMap;
  9003. material.bumpScale = this.bumpScale;
  9004. material.normalMap = this.normalMap;
  9005. material.normalScale.copy( this.normalScale );
  9006. material.specularMap = this.specularMap;
  9007. material.alphaMap = this.alphaMap;
  9008. material.envMap = this.envMap;
  9009. material.combine = this.combine;
  9010. material.reflectivity = this.reflectivity;
  9011. material.refractionRatio = this.refractionRatio;
  9012. material.fog = this.fog;
  9013. material.shading = this.shading;
  9014. material.wireframe = this.wireframe;
  9015. material.wireframeLinewidth = this.wireframeLinewidth;
  9016. material.wireframeLinecap = this.wireframeLinecap;
  9017. material.wireframeLinejoin = this.wireframeLinejoin;
  9018. material.vertexColors = this.vertexColors;
  9019. material.skinning = this.skinning;
  9020. material.morphTargets = this.morphTargets;
  9021. material.morphNormals = this.morphNormals;
  9022. return material;
  9023. };
  9024. // File:src/materials/MeshDepthMaterial.js
  9025. /**
  9026. * @author mrdoob / http://mrdoob.com/
  9027. * @author alteredq / http://alteredqualia.com/
  9028. *
  9029. * parameters = {
  9030. * opacity: <float>,
  9031. *
  9032. * blending: THREE.NormalBlending,
  9033. * depthTest: <bool>,
  9034. * depthWrite: <bool>,
  9035. *
  9036. * wireframe: <boolean>,
  9037. * wireframeLinewidth: <float>
  9038. * }
  9039. */
  9040. THREE.MeshDepthMaterial = function ( parameters ) {
  9041. THREE.Material.call( this );
  9042. this.type = 'MeshDepthMaterial';
  9043. this.morphTargets = false;
  9044. this.wireframe = false;
  9045. this.wireframeLinewidth = 1;
  9046. this.setValues( parameters );
  9047. };
  9048. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  9049. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  9050. THREE.MeshDepthMaterial.prototype.clone = function () {
  9051. var material = new THREE.MeshDepthMaterial();
  9052. THREE.Material.prototype.clone.call( this, material );
  9053. material.wireframe = this.wireframe;
  9054. material.wireframeLinewidth = this.wireframeLinewidth;
  9055. return material;
  9056. };
  9057. // File:src/materials/MeshNormalMaterial.js
  9058. /**
  9059. * @author mrdoob / http://mrdoob.com/
  9060. *
  9061. * parameters = {
  9062. * opacity: <float>,
  9063. *
  9064. * shading: THREE.FlatShading,
  9065. * blending: THREE.NormalBlending,
  9066. * depthTest: <bool>,
  9067. * depthWrite: <bool>,
  9068. *
  9069. * wireframe: <boolean>,
  9070. * wireframeLinewidth: <float>
  9071. * }
  9072. */
  9073. THREE.MeshNormalMaterial = function ( parameters ) {
  9074. THREE.Material.call( this, parameters );
  9075. this.type = 'MeshNormalMaterial';
  9076. this.wireframe = false;
  9077. this.wireframeLinewidth = 1;
  9078. this.morphTargets = false;
  9079. this.setValues( parameters );
  9080. };
  9081. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  9082. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  9083. THREE.MeshNormalMaterial.prototype.clone = function () {
  9084. var material = new THREE.MeshNormalMaterial();
  9085. THREE.Material.prototype.clone.call( this, material );
  9086. material.wireframe = this.wireframe;
  9087. material.wireframeLinewidth = this.wireframeLinewidth;
  9088. return material;
  9089. };
  9090. // File:src/materials/MeshFaceMaterial.js
  9091. /**
  9092. * @author mrdoob / http://mrdoob.com/
  9093. */
  9094. THREE.MeshFaceMaterial = function ( materials ) {
  9095. this.uuid = THREE.Math.generateUUID();
  9096. this.type = 'MeshFaceMaterial';
  9097. this.materials = materials instanceof Array ? materials : [];
  9098. };
  9099. THREE.MeshFaceMaterial.prototype = {
  9100. constructor: THREE.MeshFaceMaterial,
  9101. toJSON: function () {
  9102. var output = {
  9103. metadata: {
  9104. version: 4.2,
  9105. type: 'material',
  9106. generator: 'MaterialExporter'
  9107. },
  9108. uuid: this.uuid,
  9109. type: this.type,
  9110. materials: []
  9111. };
  9112. for ( var i = 0, l = this.materials.length; i < l; i ++ ) {
  9113. output.materials.push( this.materials[ i ].toJSON() );
  9114. }
  9115. return output;
  9116. },
  9117. clone: function () {
  9118. var material = new THREE.MeshFaceMaterial();
  9119. for ( var i = 0; i < this.materials.length; i ++ ) {
  9120. material.materials.push( this.materials[ i ].clone() );
  9121. }
  9122. return material;
  9123. }
  9124. };
  9125. // File:src/materials/PointCloudMaterial.js
  9126. /**
  9127. * @author mrdoob / http://mrdoob.com/
  9128. * @author alteredq / http://alteredqualia.com/
  9129. *
  9130. * parameters = {
  9131. * color: <hex>,
  9132. * opacity: <float>,
  9133. * map: new THREE.Texture( <Image> ),
  9134. *
  9135. * size: <float>,
  9136. * sizeAttenuation: <bool>,
  9137. *
  9138. * blending: THREE.NormalBlending,
  9139. * depthTest: <bool>,
  9140. * depthWrite: <bool>,
  9141. *
  9142. * vertexColors: <bool>,
  9143. *
  9144. * fog: <bool>
  9145. * }
  9146. */
  9147. THREE.PointCloudMaterial = function ( parameters ) {
  9148. THREE.Material.call( this );
  9149. this.type = 'PointCloudMaterial';
  9150. this.color = new THREE.Color( 0xffffff );
  9151. this.map = null;
  9152. this.size = 1;
  9153. this.sizeAttenuation = true;
  9154. this.vertexColors = THREE.NoColors;
  9155. this.fog = true;
  9156. this.setValues( parameters );
  9157. };
  9158. THREE.PointCloudMaterial.prototype = Object.create( THREE.Material.prototype );
  9159. THREE.PointCloudMaterial.prototype.constructor = THREE.PointCloudMaterial;
  9160. THREE.PointCloudMaterial.prototype.clone = function () {
  9161. var material = new THREE.PointCloudMaterial();
  9162. THREE.Material.prototype.clone.call( this, material );
  9163. material.color.copy( this.color );
  9164. material.map = this.map;
  9165. material.size = this.size;
  9166. material.sizeAttenuation = this.sizeAttenuation;
  9167. material.vertexColors = this.vertexColors;
  9168. material.fog = this.fog;
  9169. return material;
  9170. };
  9171. // backwards compatibility
  9172. THREE.ParticleBasicMaterial = function ( parameters ) {
  9173. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointCloudMaterial.' );
  9174. return new THREE.PointCloudMaterial( parameters );
  9175. };
  9176. THREE.ParticleSystemMaterial = function ( parameters ) {
  9177. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointCloudMaterial.' );
  9178. return new THREE.PointCloudMaterial( parameters );
  9179. };
  9180. // File:src/materials/ShaderMaterial.js
  9181. /**
  9182. * @author alteredq / http://alteredqualia.com/
  9183. *
  9184. * parameters = {
  9185. * defines: { "label" : "value" },
  9186. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  9187. *
  9188. * fragmentShader: <string>,
  9189. * vertexShader: <string>,
  9190. *
  9191. * shading: THREE.SmoothShading,
  9192. * blending: THREE.NormalBlending,
  9193. * depthTest: <bool>,
  9194. * depthWrite: <bool>,
  9195. *
  9196. * wireframe: <boolean>,
  9197. * wireframeLinewidth: <float>,
  9198. *
  9199. * lights: <bool>,
  9200. *
  9201. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  9202. *
  9203. * skinning: <bool>,
  9204. * morphTargets: <bool>,
  9205. * morphNormals: <bool>,
  9206. *
  9207. * fog: <bool>
  9208. * }
  9209. */
  9210. THREE.ShaderMaterial = function ( parameters ) {
  9211. THREE.Material.call( this );
  9212. this.type = 'ShaderMaterial';
  9213. this.defines = {};
  9214. this.uniforms = {};
  9215. this.attributes = [];
  9216. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  9217. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  9218. this.shading = THREE.SmoothShading;
  9219. this.linewidth = 1;
  9220. this.wireframe = false;
  9221. this.wireframeLinewidth = 1;
  9222. this.fog = false; // set to use scene fog
  9223. this.lights = false; // set to use scene lights
  9224. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  9225. this.skinning = false; // set to use skinning attribute streams
  9226. this.morphTargets = false; // set to use morph targets
  9227. this.morphNormals = false; // set to use morph normals
  9228. this.derivatives = false; // set to use derivatives
  9229. // When rendered geometry doesn't include these attributes but the material does,
  9230. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9231. this.defaultAttributeValues = {
  9232. 'color': [ 1, 1, 1 ],
  9233. 'uv': [ 0, 0 ],
  9234. 'uv2': [ 0, 0 ]
  9235. };
  9236. this.index0AttributeName = undefined;
  9237. if ( parameters !== undefined ) {
  9238. if ( parameters.attributes !== undefined && Array.isArray( parameters.attributes ) === false ) {
  9239. console.warn( 'THREE.ShaderMaterial: attributes should now be an array of attribute names.' );
  9240. parameters.attributes = Object.keys( parameters.attributes );
  9241. }
  9242. this.setValues( parameters );
  9243. }
  9244. };
  9245. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  9246. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  9247. THREE.ShaderMaterial.prototype.clone = function ( material ) {
  9248. if ( material === undefined ) material = new THREE.ShaderMaterial();
  9249. THREE.Material.prototype.clone.call( this, material );
  9250. material.fragmentShader = this.fragmentShader;
  9251. material.vertexShader = this.vertexShader;
  9252. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  9253. material.attributes = this.attributes;
  9254. material.defines = this.defines;
  9255. material.shading = this.shading;
  9256. material.wireframe = this.wireframe;
  9257. material.wireframeLinewidth = this.wireframeLinewidth;
  9258. material.fog = this.fog;
  9259. material.lights = this.lights;
  9260. material.vertexColors = this.vertexColors;
  9261. material.skinning = this.skinning;
  9262. material.morphTargets = this.morphTargets;
  9263. material.morphNormals = this.morphNormals;
  9264. return material;
  9265. };
  9266. THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
  9267. var data = THREE.Material.prototype.toJSON.call( this, meta );
  9268. data.uniforms = this.uniforms;
  9269. data.attributes = this.attributes;
  9270. data.vertexShader = this.vertexShader;
  9271. data.fragmentShader = this.fragmentShader;
  9272. return data;
  9273. };
  9274. // File:src/materials/RawShaderMaterial.js
  9275. /**
  9276. * @author mrdoob / http://mrdoob.com/
  9277. */
  9278. THREE.RawShaderMaterial = function ( parameters ) {
  9279. THREE.ShaderMaterial.call( this, parameters );
  9280. this.type = 'RawShaderMaterial';
  9281. };
  9282. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  9283. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  9284. THREE.RawShaderMaterial.prototype.clone = function () {
  9285. var material = new THREE.RawShaderMaterial();
  9286. THREE.ShaderMaterial.prototype.clone.call( this, material );
  9287. return material;
  9288. };
  9289. // File:src/materials/SpriteMaterial.js
  9290. /**
  9291. * @author alteredq / http://alteredqualia.com/
  9292. *
  9293. * parameters = {
  9294. * color: <hex>,
  9295. * opacity: <float>,
  9296. * map: new THREE.Texture( <Image> ),
  9297. *
  9298. * blending: THREE.NormalBlending,
  9299. * depthTest: <bool>,
  9300. * depthWrite: <bool>,
  9301. *
  9302. * uvOffset: new THREE.Vector2(),
  9303. * uvScale: new THREE.Vector2(),
  9304. *
  9305. * fog: <bool>
  9306. * }
  9307. */
  9308. THREE.SpriteMaterial = function ( parameters ) {
  9309. THREE.Material.call( this );
  9310. this.type = 'SpriteMaterial';
  9311. this.color = new THREE.Color( 0xffffff );
  9312. this.map = null;
  9313. this.rotation = 0;
  9314. this.fog = false;
  9315. // set parameters
  9316. this.setValues( parameters );
  9317. };
  9318. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  9319. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  9320. THREE.SpriteMaterial.prototype.clone = function () {
  9321. var material = new THREE.SpriteMaterial();
  9322. THREE.Material.prototype.clone.call( this, material );
  9323. material.color.copy( this.color );
  9324. material.map = this.map;
  9325. material.rotation = this.rotation;
  9326. material.fog = this.fog;
  9327. return material;
  9328. };
  9329. // File:src/textures/Texture.js
  9330. /**
  9331. * @author mrdoob / http://mrdoob.com/
  9332. * @author alteredq / http://alteredqualia.com/
  9333. * @author szimek / https://github.com/szimek/
  9334. */
  9335. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9336. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  9337. this.uuid = THREE.Math.generateUUID();
  9338. this.name = '';
  9339. this.sourceFile = '';
  9340. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  9341. this.mipmaps = [];
  9342. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  9343. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  9344. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  9345. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  9346. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  9347. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  9348. this.format = format !== undefined ? format : THREE.RGBAFormat;
  9349. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  9350. this.offset = new THREE.Vector2( 0, 0 );
  9351. this.repeat = new THREE.Vector2( 1, 1 );
  9352. this.generateMipmaps = true;
  9353. this.premultiplyAlpha = false;
  9354. this.flipY = true;
  9355. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  9356. this._needsUpdate = false;
  9357. this.onUpdate = null;
  9358. };
  9359. THREE.Texture.DEFAULT_IMAGE = undefined;
  9360. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  9361. THREE.Texture.prototype = {
  9362. constructor: THREE.Texture,
  9363. get needsUpdate () {
  9364. return this._needsUpdate;
  9365. },
  9366. set needsUpdate ( value ) {
  9367. if ( value === true ) this.update();
  9368. this._needsUpdate = value;
  9369. },
  9370. clone: function ( texture ) {
  9371. if ( texture === undefined ) texture = new THREE.Texture();
  9372. texture.image = this.image;
  9373. texture.mipmaps = this.mipmaps.slice( 0 );
  9374. texture.mapping = this.mapping;
  9375. texture.wrapS = this.wrapS;
  9376. texture.wrapT = this.wrapT;
  9377. texture.magFilter = this.magFilter;
  9378. texture.minFilter = this.minFilter;
  9379. texture.anisotropy = this.anisotropy;
  9380. texture.format = this.format;
  9381. texture.type = this.type;
  9382. texture.offset.copy( this.offset );
  9383. texture.repeat.copy( this.repeat );
  9384. texture.generateMipmaps = this.generateMipmaps;
  9385. texture.premultiplyAlpha = this.premultiplyAlpha;
  9386. texture.flipY = this.flipY;
  9387. texture.unpackAlignment = this.unpackAlignment;
  9388. return texture;
  9389. },
  9390. toJSON: function ( meta ) {
  9391. if ( meta.textures[ this.uuid ] !== undefined ) {
  9392. return meta.textures[ this.uuid ];
  9393. }
  9394. function getDataURL( image ) {
  9395. var canvas;
  9396. if ( image.toDataURL !== undefined ) {
  9397. canvas = image;
  9398. } else {
  9399. canvas = document.createElement( 'canvas' );
  9400. canvas.width = image.width;
  9401. canvas.height = image.height;
  9402. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  9403. }
  9404. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  9405. return canvas.toDataURL( 'image/jpeg', 0.6 );
  9406. } else {
  9407. return canvas.toDataURL( 'image/png' );
  9408. }
  9409. }
  9410. var output = {
  9411. metadata: {
  9412. version: 4.4,
  9413. type: 'Texture',
  9414. generator: 'Texture.toJSON'
  9415. },
  9416. uuid: this.uuid,
  9417. name: this.name,
  9418. mapping: this.mapping,
  9419. repeat: [ this.repeat.x, this.repeat.y ],
  9420. offset: [ this.offset.x, this.offset.y ],
  9421. wrap: [ this.wrapS, this.wrapT ],
  9422. minFilter: this.minFilter,
  9423. magFilter: this.magFilter,
  9424. anisotropy: this.anisotropy
  9425. };
  9426. if ( this.image !== undefined ) {
  9427. // TODO: Move to THREE.Image
  9428. var image = this.image;
  9429. if ( image.uuid === undefined ) {
  9430. image.uuid = THREE.Math.generateUUID(); // UGH
  9431. }
  9432. if ( meta.images[ image.uuid ] === undefined ) {
  9433. meta.images[ image.uuid ] = {
  9434. uuid: image.uuid,
  9435. url: getDataURL( image )
  9436. };
  9437. }
  9438. output.image = image.uuid;
  9439. }
  9440. meta.textures[ this.uuid ] = output;
  9441. return output;
  9442. },
  9443. update: function () {
  9444. this.dispatchEvent( { type: 'update' } );
  9445. },
  9446. dispose: function () {
  9447. this.dispatchEvent( { type: 'dispose' } );
  9448. }
  9449. };
  9450. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  9451. THREE.TextureIdCount = 0;
  9452. // File:src/textures/CubeTexture.js
  9453. /**
  9454. * @author mrdoob / http://mrdoob.com/
  9455. */
  9456. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9457. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  9458. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9459. this.images = images;
  9460. };
  9461. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  9462. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  9463. THREE.CubeTexture.clone = function ( texture ) {
  9464. if ( texture === undefined ) texture = new THREE.CubeTexture();
  9465. THREE.Texture.prototype.clone.call( this, texture );
  9466. texture.images = this.images;
  9467. return texture;
  9468. };
  9469. // File:src/textures/CompressedTexture.js
  9470. /**
  9471. * @author alteredq / http://alteredqualia.com/
  9472. */
  9473. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9474. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9475. this.image = { width: width, height: height };
  9476. this.mipmaps = mipmaps;
  9477. // no flipping for cube textures
  9478. // (also flipping doesn't work for compressed textures )
  9479. this.flipY = false;
  9480. // can't generate mipmaps for compressed textures
  9481. // mips must be embedded in DDS files
  9482. this.generateMipmaps = false;
  9483. };
  9484. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  9485. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  9486. THREE.CompressedTexture.prototype.clone = function () {
  9487. var texture = new THREE.CompressedTexture();
  9488. THREE.Texture.prototype.clone.call( this, texture );
  9489. return texture;
  9490. };
  9491. // File:src/textures/DataTexture.js
  9492. /**
  9493. * @author alteredq / http://alteredqualia.com/
  9494. */
  9495. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9496. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9497. this.image = { data: data, width: width, height: height };
  9498. };
  9499. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  9500. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  9501. THREE.DataTexture.prototype.clone = function () {
  9502. var texture = new THREE.DataTexture();
  9503. THREE.Texture.prototype.clone.call( this, texture );
  9504. return texture;
  9505. };
  9506. // File:src/textures/VideoTexture.js
  9507. /**
  9508. * @author mrdoob / http://mrdoob.com/
  9509. */
  9510. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9511. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9512. this.generateMipmaps = false;
  9513. var scope = this;
  9514. var update = function () {
  9515. requestAnimationFrame( update );
  9516. if ( video.readyState === video.HAVE_ENOUGH_DATA ) {
  9517. scope.needsUpdate = true;
  9518. }
  9519. };
  9520. update();
  9521. };
  9522. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  9523. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  9524. // File:src/objects/Group.js
  9525. /**
  9526. * @author mrdoob / http://mrdoob.com/
  9527. */
  9528. THREE.Group = function () {
  9529. THREE.Object3D.call( this );
  9530. this.type = 'Group';
  9531. };
  9532. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  9533. THREE.Group.prototype.constructor = THREE.Group;
  9534. THREE.Group.prototype.clone = function ( object ) {
  9535. if ( object === undefined ) object = new THREE.Group();
  9536. THREE.Object3D.prototype.clone.call( this, object );
  9537. return object;
  9538. };
  9539. // File:src/objects/PointCloud.js
  9540. /**
  9541. * @author alteredq / http://alteredqualia.com/
  9542. */
  9543. THREE.PointCloud = function ( geometry, material ) {
  9544. THREE.Object3D.call( this );
  9545. this.type = 'PointCloud';
  9546. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9547. this.material = material !== undefined ? material : new THREE.PointCloudMaterial( { color: Math.random() * 0xffffff } );
  9548. };
  9549. THREE.PointCloud.prototype = Object.create( THREE.Object3D.prototype );
  9550. THREE.PointCloud.prototype.constructor = THREE.PointCloud;
  9551. THREE.PointCloud.prototype.raycast = ( function () {
  9552. var inverseMatrix = new THREE.Matrix4();
  9553. var ray = new THREE.Ray();
  9554. return function ( raycaster, intersects ) {
  9555. var object = this;
  9556. var geometry = object.geometry;
  9557. var threshold = raycaster.params.PointCloud.threshold;
  9558. inverseMatrix.getInverse( this.matrixWorld );
  9559. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9560. if ( geometry.boundingBox !== null ) {
  9561. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  9562. return;
  9563. }
  9564. }
  9565. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  9566. var position = new THREE.Vector3();
  9567. var testPoint = function ( point, index ) {
  9568. var rayPointDistance = ray.distanceToPoint( point );
  9569. if ( rayPointDistance < localThreshold ) {
  9570. var intersectPoint = ray.closestPointToPoint( point );
  9571. intersectPoint.applyMatrix4( object.matrixWorld );
  9572. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  9573. if ( distance < raycaster.near || distance > raycaster.far ) return;
  9574. intersects.push( {
  9575. distance: distance,
  9576. distanceToRay: rayPointDistance,
  9577. point: intersectPoint.clone(),
  9578. index: index,
  9579. face: null,
  9580. object: object
  9581. } );
  9582. }
  9583. };
  9584. if ( geometry instanceof THREE.BufferGeometry ) {
  9585. var attributes = geometry.attributes;
  9586. var positions = attributes.position.array;
  9587. if ( attributes.index !== undefined ) {
  9588. var indices = attributes.index.array;
  9589. var offsets = geometry.offsets;
  9590. if ( offsets.length === 0 ) {
  9591. offsets.push( {
  9592. start: 0,
  9593. count: indices.length,
  9594. index: 0
  9595. } );
  9596. }
  9597. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  9598. var offset = offsets[ oi ];
  9599. var start = offset.start;
  9600. var count = offset.count;
  9601. var index = offset.index;
  9602. for ( var i = start, il = start + count; i < il; i ++ ) {
  9603. var a = index + indices[ i ];
  9604. position.fromArray( positions, a * 3 );
  9605. testPoint( position, a );
  9606. }
  9607. }
  9608. } else {
  9609. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  9610. position.fromArray( positions, i * 3 );
  9611. testPoint( position, i );
  9612. }
  9613. }
  9614. } else {
  9615. var vertices = geometry.vertices;
  9616. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  9617. testPoint( vertices[ i ], i );
  9618. }
  9619. }
  9620. };
  9621. }() );
  9622. THREE.PointCloud.prototype.clone = function ( object ) {
  9623. if ( object === undefined ) object = new THREE.PointCloud( this.geometry, this.material );
  9624. THREE.Object3D.prototype.clone.call( this, object );
  9625. return object;
  9626. };
  9627. THREE.PointCloud.prototype.toJSON = function ( meta ) {
  9628. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9629. // only serialize if not in meta geometries cache
  9630. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9631. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9632. }
  9633. // only serialize if not in meta materials cache
  9634. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9635. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9636. }
  9637. data.object.geometry = this.geometry.uuid;
  9638. data.object.material = this.material.uuid;
  9639. return data;
  9640. };
  9641. // Backwards compatibility
  9642. THREE.ParticleSystem = function ( geometry, material ) {
  9643. console.warn( 'THREE.ParticleSystem has been renamed to THREE.PointCloud.' );
  9644. return new THREE.PointCloud( geometry, material );
  9645. };
  9646. // File:src/objects/Line.js
  9647. /**
  9648. * @author mrdoob / http://mrdoob.com/
  9649. */
  9650. THREE.Line = function ( geometry, material, mode ) {
  9651. if ( mode === 1 ) {
  9652. console.error( 'THREE.Line: THREE.LinePieces mode has been removed. Use THREE.LineSegments instead.' );
  9653. }
  9654. THREE.Object3D.call( this );
  9655. this.type = 'Line';
  9656. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9657. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9658. };
  9659. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9660. THREE.Line.prototype.constructor = THREE.Line;
  9661. THREE.Line.prototype.raycast = ( function () {
  9662. var inverseMatrix = new THREE.Matrix4();
  9663. var ray = new THREE.Ray();
  9664. var sphere = new THREE.Sphere();
  9665. return function ( raycaster, intersects ) {
  9666. var precision = raycaster.linePrecision;
  9667. var precisionSq = precision * precision;
  9668. var geometry = this.geometry;
  9669. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9670. // Checking boundingSphere distance to ray
  9671. sphere.copy( geometry.boundingSphere );
  9672. sphere.applyMatrix4( this.matrixWorld );
  9673. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9674. return;
  9675. }
  9676. inverseMatrix.getInverse( this.matrixWorld );
  9677. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9678. var vStart = new THREE.Vector3();
  9679. var vEnd = new THREE.Vector3();
  9680. var interSegment = new THREE.Vector3();
  9681. var interRay = new THREE.Vector3();
  9682. var step = this instanceof THREE.LineSegments ? 2 : 1;
  9683. if ( geometry instanceof THREE.BufferGeometry ) {
  9684. var attributes = geometry.attributes;
  9685. if ( attributes.index !== undefined ) {
  9686. var indices = attributes.index.array;
  9687. var positions = attributes.position.array;
  9688. var offsets = geometry.offsets;
  9689. if ( offsets.length === 0 ) {
  9690. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9691. }
  9692. for ( var oi = 0; oi < offsets.length; oi ++) {
  9693. var start = offsets[ oi ].start;
  9694. var count = offsets[ oi ].count;
  9695. var index = offsets[ oi ].index;
  9696. for ( var i = start; i < start + count - 1; i += step ) {
  9697. var a = index + indices[ i ];
  9698. var b = index + indices[ i + 1 ];
  9699. vStart.fromArray( positions, a * 3 );
  9700. vEnd.fromArray( positions, b * 3 );
  9701. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9702. if ( distSq > precisionSq ) continue;
  9703. var distance = ray.origin.distanceTo( interRay );
  9704. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9705. intersects.push( {
  9706. distance: distance,
  9707. // What do we want? intersection point on the ray or on the segment??
  9708. // point: raycaster.ray.at( distance ),
  9709. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9710. index: i,
  9711. offsetIndex: oi,
  9712. face: null,
  9713. faceIndex: null,
  9714. object: this
  9715. } );
  9716. }
  9717. }
  9718. } else {
  9719. var positions = attributes.position.array;
  9720. for ( var i = 0; i < positions.length / 3 - 1; i += step ) {
  9721. vStart.fromArray( positions, 3 * i );
  9722. vEnd.fromArray( positions, 3 * i + 3 );
  9723. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  9724. if ( distSq > precisionSq ) continue;
  9725. var distance = ray.origin.distanceTo( interRay );
  9726. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9727. intersects.push( {
  9728. distance: distance,
  9729. // What do we want? intersection point on the ray or on the segment??
  9730. // point: raycaster.ray.at( distance ),
  9731. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9732. index: i,
  9733. face: null,
  9734. faceIndex: null,
  9735. object: this
  9736. } );
  9737. }
  9738. }
  9739. } else if ( geometry instanceof THREE.Geometry ) {
  9740. var vertices = geometry.vertices;
  9741. var nbVertices = vertices.length;
  9742. for ( var i = 0; i < nbVertices - 1; i += step ) {
  9743. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  9744. if ( distSq > precisionSq ) continue;
  9745. var distance = ray.origin.distanceTo( interRay );
  9746. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9747. intersects.push( {
  9748. distance: distance,
  9749. // What do we want? intersection point on the ray or on the segment??
  9750. // point: raycaster.ray.at( distance ),
  9751. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  9752. index: i,
  9753. face: null,
  9754. faceIndex: null,
  9755. object: this
  9756. } );
  9757. }
  9758. }
  9759. };
  9760. }() );
  9761. THREE.Line.prototype.clone = function ( object ) {
  9762. if ( object === undefined ) object = new THREE[ this.type ]( this.geometry, this.material );
  9763. THREE.Object3D.prototype.clone.call( this, object );
  9764. return object;
  9765. };
  9766. THREE.Line.prototype.toJSON = function ( meta ) {
  9767. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9768. // only serialize if not in meta geometries cache
  9769. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9770. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON();
  9771. }
  9772. // only serialize if not in meta materials cache
  9773. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9774. meta.materials[ this.material.uuid ] = this.material.toJSON();
  9775. }
  9776. data.object.geometry = this.geometry.uuid;
  9777. data.object.material = this.material.uuid;
  9778. return data;
  9779. };
  9780. // DEPRECATED
  9781. THREE.LineStrip = 0;
  9782. THREE.LinePieces = 1;
  9783. // File:src/objects/LineSegments.js
  9784. /**
  9785. * @author mrdoob / http://mrdoob.com/
  9786. */
  9787. THREE.LineSegments = function ( geometry, material ) {
  9788. THREE.Line.call( this, geometry, material );
  9789. this.type = 'LineSegments';
  9790. };
  9791. THREE.LineSegments.prototype = Object.create( THREE.Line.prototype );
  9792. THREE.LineSegments.prototype.constructor = THREE.LineSegments;
  9793. THREE.LineSegments.prototype.clone = function ( object ) {
  9794. if ( object === undefined ) object = new THREE.LineSegments( this.geometry, this.material );
  9795. THREE.Line.prototype.clone.call( this, object );
  9796. return object;
  9797. };
  9798. // File:src/objects/Mesh.js
  9799. /**
  9800. * @author mrdoob / http://mrdoob.com/
  9801. * @author alteredq / http://alteredqualia.com/
  9802. * @author mikael emtinger / http://gomo.se/
  9803. * @author jonobr1 / http://jonobr1.com/
  9804. */
  9805. THREE.Mesh = function ( geometry, material ) {
  9806. THREE.Object3D.call( this );
  9807. this.type = 'Mesh';
  9808. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9809. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9810. this.updateMorphTargets();
  9811. };
  9812. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9813. THREE.Mesh.prototype.constructor = THREE.Mesh;
  9814. THREE.Mesh.prototype.updateMorphTargets = function () {
  9815. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9816. this.morphTargetBase = - 1;
  9817. this.morphTargetForcedOrder = [];
  9818. this.morphTargetInfluences = [];
  9819. this.morphTargetDictionary = {};
  9820. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9821. this.morphTargetInfluences.push( 0 );
  9822. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9823. }
  9824. }
  9825. };
  9826. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9827. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9828. return this.morphTargetDictionary[ name ];
  9829. }
  9830. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  9831. return 0;
  9832. };
  9833. THREE.Mesh.prototype.raycast = ( function () {
  9834. var inverseMatrix = new THREE.Matrix4();
  9835. var ray = new THREE.Ray();
  9836. var sphere = new THREE.Sphere();
  9837. var vA = new THREE.Vector3();
  9838. var vB = new THREE.Vector3();
  9839. var vC = new THREE.Vector3();
  9840. return function ( raycaster, intersects ) {
  9841. var geometry = this.geometry;
  9842. var material = this.material;
  9843. if ( material === undefined ) return;
  9844. // Checking boundingSphere distance to ray
  9845. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9846. sphere.copy( geometry.boundingSphere );
  9847. sphere.applyMatrix4( this.matrixWorld );
  9848. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  9849. return;
  9850. }
  9851. // Check boundingBox before continuing
  9852. inverseMatrix.getInverse( this.matrixWorld );
  9853. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  9854. if ( geometry.boundingBox !== null ) {
  9855. if ( ray.isIntersectionBox( geometry.boundingBox ) === false ) {
  9856. return;
  9857. }
  9858. }
  9859. var a, b, c;
  9860. if ( geometry instanceof THREE.BufferGeometry ) {
  9861. var attributes = geometry.attributes;
  9862. if ( attributes.index !== undefined ) {
  9863. var indices = attributes.index.array;
  9864. var positions = attributes.position.array;
  9865. var offsets = geometry.offsets;
  9866. if ( offsets.length === 0 ) {
  9867. offsets = [ { start: 0, count: indices.length, index: 0 } ];
  9868. }
  9869. for ( var oi = 0, ol = offsets.length; oi < ol; ++ oi ) {
  9870. var start = offsets[ oi ].start;
  9871. var count = offsets[ oi ].count;
  9872. var index = offsets[ oi ].index;
  9873. for ( var i = start, il = start + count; i < il; i += 3 ) {
  9874. a = index + indices[ i ];
  9875. b = index + indices[ i + 1 ];
  9876. c = index + indices[ i + 2 ];
  9877. vA.fromArray( positions, a * 3 );
  9878. vB.fromArray( positions, b * 3 );
  9879. vC.fromArray( positions, c * 3 );
  9880. if ( material.side === THREE.BackSide ) {
  9881. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9882. } else {
  9883. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9884. }
  9885. if ( intersectionPoint === null ) continue;
  9886. intersectionPoint.applyMatrix4( this.matrixWorld );
  9887. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9888. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9889. intersects.push( {
  9890. distance: distance,
  9891. point: intersectionPoint,
  9892. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9893. faceIndex: Math.floor( i / 3 ), // triangle number in indices buffer semantics
  9894. object: this
  9895. } );
  9896. }
  9897. }
  9898. } else {
  9899. var positions = attributes.position.array;
  9900. for ( var i = 0, j = 0, il = positions.length; i < il; i += 3, j += 9 ) {
  9901. a = i;
  9902. b = i + 1;
  9903. c = i + 2;
  9904. vA.fromArray( positions, j );
  9905. vB.fromArray( positions, j + 3 );
  9906. vC.fromArray( positions, j + 6 );
  9907. if ( material.side === THREE.BackSide ) {
  9908. var intersectionPoint = ray.intersectTriangle( vC, vB, vA, true );
  9909. } else {
  9910. var intersectionPoint = ray.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  9911. }
  9912. if ( intersectionPoint === null ) continue;
  9913. intersectionPoint.applyMatrix4( this.matrixWorld );
  9914. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9915. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9916. intersects.push( {
  9917. distance: distance,
  9918. point: intersectionPoint,
  9919. face: new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) ),
  9920. index: Math.floor(i/3), // triangle number in positions buffer semantics
  9921. object: this
  9922. } );
  9923. }
  9924. }
  9925. } else if ( geometry instanceof THREE.Geometry ) {
  9926. var isFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  9927. var materials = isFaceMaterial === true ? material.materials : null;
  9928. var vertices = geometry.vertices;
  9929. var faces = geometry.faces;
  9930. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  9931. var face = faces[ f ];
  9932. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  9933. if ( faceMaterial === undefined ) continue;
  9934. a = vertices[ face.a ];
  9935. b = vertices[ face.b ];
  9936. c = vertices[ face.c ];
  9937. if ( faceMaterial.morphTargets === true ) {
  9938. var morphTargets = geometry.morphTargets;
  9939. var morphInfluences = this.morphTargetInfluences;
  9940. vA.set( 0, 0, 0 );
  9941. vB.set( 0, 0, 0 );
  9942. vC.set( 0, 0, 0 );
  9943. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  9944. var influence = morphInfluences[ t ];
  9945. if ( influence === 0 ) continue;
  9946. var targets = morphTargets[ t ].vertices;
  9947. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  9948. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  9949. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  9950. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  9951. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  9952. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  9953. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  9954. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  9955. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  9956. }
  9957. vA.add( a );
  9958. vB.add( b );
  9959. vC.add( c );
  9960. a = vA;
  9961. b = vB;
  9962. c = vC;
  9963. }
  9964. if ( faceMaterial.side === THREE.BackSide ) {
  9965. var intersectionPoint = ray.intersectTriangle( c, b, a, true );
  9966. } else {
  9967. var intersectionPoint = ray.intersectTriangle( a, b, c, faceMaterial.side !== THREE.DoubleSide );
  9968. }
  9969. if ( intersectionPoint === null ) continue;
  9970. intersectionPoint.applyMatrix4( this.matrixWorld );
  9971. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  9972. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  9973. intersects.push( {
  9974. distance: distance,
  9975. point: intersectionPoint,
  9976. face: face,
  9977. faceIndex: f,
  9978. object: this
  9979. } );
  9980. }
  9981. }
  9982. };
  9983. }() );
  9984. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  9985. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9986. THREE.Object3D.prototype.clone.call( this, object, recursive );
  9987. return object;
  9988. };
  9989. THREE.Mesh.prototype.toJSON = function ( meta ) {
  9990. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9991. // only serialize if not in meta geometries cache
  9992. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  9993. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  9994. }
  9995. // only serialize if not in meta materials cache
  9996. if ( meta.materials[ this.material.uuid ] === undefined ) {
  9997. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  9998. }
  9999. data.object.geometry = this.geometry.uuid;
  10000. data.object.material = this.material.uuid;
  10001. return data;
  10002. };
  10003. // File:src/objects/Bone.js
  10004. /**
  10005. * @author mikael emtinger / http://gomo.se/
  10006. * @author alteredq / http://alteredqualia.com/
  10007. * @author ikerr / http://verold.com
  10008. */
  10009. THREE.Bone = function ( skin ) {
  10010. THREE.Object3D.call( this );
  10011. this.type = 'Bone';
  10012. this.skin = skin;
  10013. };
  10014. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  10015. THREE.Bone.prototype.constructor = THREE.Bone;
  10016. THREE.Bone.prototype.clone = function ( object ) {
  10017. if ( object === undefined ) object = new THREE.Bone( this.skin );
  10018. THREE.Object3D.prototype.clone.call( this, object );
  10019. object.skin = this.skin;
  10020. return object;
  10021. };
  10022. // File:src/objects/Skeleton.js
  10023. /**
  10024. * @author mikael emtinger / http://gomo.se/
  10025. * @author alteredq / http://alteredqualia.com/
  10026. * @author michael guerrero / http://realitymeltdown.com
  10027. * @author ikerr / http://verold.com
  10028. */
  10029. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  10030. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  10031. this.identityMatrix = new THREE.Matrix4();
  10032. // copy the bone array
  10033. bones = bones || [];
  10034. this.bones = bones.slice( 0 );
  10035. // create a bone texture or an array of floats
  10036. if ( this.useVertexTexture ) {
  10037. // layout (1 matrix = 4 pixels)
  10038. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  10039. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  10040. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  10041. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  10042. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  10043. var size = THREE.Math.nextPowerOfTwo( Math.sqrt( this.bones.length * 4 ) ); // 4 pixels needed for 1 matrix
  10044. this.boneTextureWidth = size;
  10045. this.boneTextureHeight = size;
  10046. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  10047. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  10048. this.boneTexture.minFilter = THREE.NearestFilter;
  10049. this.boneTexture.magFilter = THREE.NearestFilter;
  10050. this.boneTexture.generateMipmaps = false;
  10051. this.boneTexture.flipY = false;
  10052. } else {
  10053. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  10054. }
  10055. // use the supplied bone inverses or calculate the inverses
  10056. if ( boneInverses === undefined ) {
  10057. this.calculateInverses();
  10058. } else {
  10059. if ( this.bones.length === boneInverses.length ) {
  10060. this.boneInverses = boneInverses.slice( 0 );
  10061. } else {
  10062. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  10063. this.boneInverses = [];
  10064. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  10065. this.boneInverses.push( new THREE.Matrix4() );
  10066. }
  10067. }
  10068. }
  10069. };
  10070. THREE.Skeleton.prototype.calculateInverses = function () {
  10071. this.boneInverses = [];
  10072. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  10073. var inverse = new THREE.Matrix4();
  10074. if ( this.bones[ b ] ) {
  10075. inverse.getInverse( this.bones[ b ].matrixWorld );
  10076. }
  10077. this.boneInverses.push( inverse );
  10078. }
  10079. };
  10080. THREE.Skeleton.prototype.pose = function () {
  10081. var bone;
  10082. // recover the bind-time world matrices
  10083. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  10084. bone = this.bones[ b ];
  10085. if ( bone ) {
  10086. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  10087. }
  10088. }
  10089. // compute the local matrices, positions, rotations and scales
  10090. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  10091. bone = this.bones[ b ];
  10092. if ( bone ) {
  10093. if ( bone.parent ) {
  10094. bone.matrix.getInverse( bone.parent.matrixWorld );
  10095. bone.matrix.multiply( bone.matrixWorld );
  10096. } else {
  10097. bone.matrix.copy( bone.matrixWorld );
  10098. }
  10099. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  10100. }
  10101. }
  10102. };
  10103. THREE.Skeleton.prototype.update = ( function () {
  10104. var offsetMatrix = new THREE.Matrix4();
  10105. return function () {
  10106. // flatten bone matrices to array
  10107. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  10108. // compute the offset between the current and the original transform
  10109. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  10110. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  10111. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  10112. }
  10113. if ( this.useVertexTexture ) {
  10114. this.boneTexture.needsUpdate = true;
  10115. }
  10116. };
  10117. } )();
  10118. THREE.Skeleton.prototype.clone = function () {
  10119. return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  10120. };
  10121. // File:src/objects/SkinnedMesh.js
  10122. /**
  10123. * @author mikael emtinger / http://gomo.se/
  10124. * @author alteredq / http://alteredqualia.com/
  10125. * @author ikerr / http://verold.com
  10126. */
  10127. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  10128. THREE.Mesh.call( this, geometry, material );
  10129. this.type = 'SkinnedMesh';
  10130. this.bindMode = "attached";
  10131. this.bindMatrix = new THREE.Matrix4();
  10132. this.bindMatrixInverse = new THREE.Matrix4();
  10133. // init bones
  10134. // TODO: remove bone creation as there is no reason (other than
  10135. // convenience) for THREE.SkinnedMesh to do this.
  10136. var bones = [];
  10137. if ( this.geometry && this.geometry.bones !== undefined ) {
  10138. var bone, gbone, p, q, s;
  10139. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  10140. gbone = this.geometry.bones[ b ];
  10141. p = gbone.pos;
  10142. q = gbone.rotq;
  10143. s = gbone.scl;
  10144. bone = new THREE.Bone( this );
  10145. bones.push( bone );
  10146. bone.name = gbone.name;
  10147. bone.position.set( p[ 0 ], p[ 1 ], p[ 2 ] );
  10148. bone.quaternion.set( q[ 0 ], q[ 1 ], q[ 2 ], q[ 3 ] );
  10149. if ( s !== undefined ) {
  10150. bone.scale.set( s[ 0 ], s[ 1 ], s[ 2 ] );
  10151. } else {
  10152. bone.scale.set( 1, 1, 1 );
  10153. }
  10154. }
  10155. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  10156. gbone = this.geometry.bones[ b ];
  10157. if ( gbone.parent !== - 1 ) {
  10158. bones[ gbone.parent ].add( bones[ b ] );
  10159. } else {
  10160. this.add( bones[ b ] );
  10161. }
  10162. }
  10163. }
  10164. this.normalizeSkinWeights();
  10165. this.updateMatrixWorld( true );
  10166. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ) );
  10167. };
  10168. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  10169. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  10170. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  10171. this.skeleton = skeleton;
  10172. if ( bindMatrix === undefined ) {
  10173. this.updateMatrixWorld( true );
  10174. bindMatrix = this.matrixWorld;
  10175. }
  10176. this.bindMatrix.copy( bindMatrix );
  10177. this.bindMatrixInverse.getInverse( bindMatrix );
  10178. };
  10179. THREE.SkinnedMesh.prototype.pose = function () {
  10180. this.skeleton.pose();
  10181. };
  10182. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  10183. if ( this.geometry instanceof THREE.Geometry ) {
  10184. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  10185. var sw = this.geometry.skinWeights[ i ];
  10186. var scale = 1.0 / sw.lengthManhattan();
  10187. if ( scale !== Infinity ) {
  10188. sw.multiplyScalar( scale );
  10189. } else {
  10190. sw.set( 1 ); // this will be normalized by the shader anyway
  10191. }
  10192. }
  10193. } else {
  10194. // skinning weights assumed to be normalized for THREE.BufferGeometry
  10195. }
  10196. };
  10197. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  10198. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  10199. if ( this.bindMode === "attached" ) {
  10200. this.bindMatrixInverse.getInverse( this.matrixWorld );
  10201. } else if ( this.bindMode === "detached" ) {
  10202. this.bindMatrixInverse.getInverse( this.bindMatrix );
  10203. } else {
  10204. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  10205. }
  10206. };
  10207. THREE.SkinnedMesh.prototype.clone = function( object ) {
  10208. if ( object === undefined ) {
  10209. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  10210. }
  10211. THREE.Mesh.prototype.clone.call( this, object );
  10212. return object;
  10213. };
  10214. // File:src/objects/MorphAnimMesh.js
  10215. /**
  10216. * @author alteredq / http://alteredqualia.com/
  10217. */
  10218. THREE.MorphAnimMesh = function ( geometry, material ) {
  10219. THREE.Mesh.call( this, geometry, material );
  10220. this.type = 'MorphAnimMesh';
  10221. // API
  10222. this.duration = 1000; // milliseconds
  10223. this.mirroredLoop = false;
  10224. this.time = 0;
  10225. // internals
  10226. this.lastKeyframe = 0;
  10227. this.currentKeyframe = 0;
  10228. this.direction = 1;
  10229. this.directionBackwards = false;
  10230. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  10231. };
  10232. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  10233. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  10234. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  10235. this.startKeyframe = start;
  10236. this.endKeyframe = end;
  10237. this.length = this.endKeyframe - this.startKeyframe + 1;
  10238. };
  10239. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  10240. this.direction = 1;
  10241. this.directionBackwards = false;
  10242. };
  10243. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  10244. this.direction = - 1;
  10245. this.directionBackwards = true;
  10246. };
  10247. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  10248. var geometry = this.geometry;
  10249. if ( ! geometry.animations ) geometry.animations = {};
  10250. var firstAnimation, animations = geometry.animations;
  10251. var pattern = /([a-z]+)_?(\d+)/;
  10252. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  10253. var morph = geometry.morphTargets[ i ];
  10254. var parts = morph.name.match( pattern );
  10255. if ( parts && parts.length > 1 ) {
  10256. var label = parts[ 1 ];
  10257. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: - Infinity };
  10258. var animation = animations[ label ];
  10259. if ( i < animation.start ) animation.start = i;
  10260. if ( i > animation.end ) animation.end = i;
  10261. if ( ! firstAnimation ) firstAnimation = label;
  10262. }
  10263. }
  10264. geometry.firstAnimation = firstAnimation;
  10265. };
  10266. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  10267. if ( ! this.geometry.animations ) this.geometry.animations = {};
  10268. this.geometry.animations[ label ] = { start: start, end: end };
  10269. };
  10270. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  10271. var animation = this.geometry.animations[ label ];
  10272. if ( animation ) {
  10273. this.setFrameRange( animation.start, animation.end );
  10274. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  10275. this.time = 0;
  10276. } else {
  10277. console.warn( 'THREE.MorphAnimMesh: animation[' + label + '] undefined in .playAnimation()' );
  10278. }
  10279. };
  10280. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  10281. var frameTime = this.duration / this.length;
  10282. this.time += this.direction * delta;
  10283. if ( this.mirroredLoop ) {
  10284. if ( this.time > this.duration || this.time < 0 ) {
  10285. this.direction *= - 1;
  10286. if ( this.time > this.duration ) {
  10287. this.time = this.duration;
  10288. this.directionBackwards = true;
  10289. }
  10290. if ( this.time < 0 ) {
  10291. this.time = 0;
  10292. this.directionBackwards = false;
  10293. }
  10294. }
  10295. } else {
  10296. this.time = this.time % this.duration;
  10297. if ( this.time < 0 ) this.time += this.duration;
  10298. }
  10299. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  10300. if ( keyframe !== this.currentKeyframe ) {
  10301. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  10302. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  10303. this.morphTargetInfluences[ keyframe ] = 0;
  10304. this.lastKeyframe = this.currentKeyframe;
  10305. this.currentKeyframe = keyframe;
  10306. }
  10307. var mix = ( this.time % frameTime ) / frameTime;
  10308. if ( this.directionBackwards ) {
  10309. mix = 1 - mix;
  10310. }
  10311. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  10312. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  10313. };
  10314. THREE.MorphAnimMesh.prototype.interpolateTargets = function ( a, b, t ) {
  10315. var influences = this.morphTargetInfluences;
  10316. for ( var i = 0, l = influences.length; i < l; i ++ ) {
  10317. influences[ i ] = 0;
  10318. }
  10319. if ( a > -1 ) influences[ a ] = 1 - t;
  10320. if ( b > -1 ) influences[ b ] = t;
  10321. };
  10322. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  10323. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  10324. object.duration = this.duration;
  10325. object.mirroredLoop = this.mirroredLoop;
  10326. object.time = this.time;
  10327. object.lastKeyframe = this.lastKeyframe;
  10328. object.currentKeyframe = this.currentKeyframe;
  10329. object.direction = this.direction;
  10330. object.directionBackwards = this.directionBackwards;
  10331. THREE.Mesh.prototype.clone.call( this, object );
  10332. return object;
  10333. };
  10334. // File:src/objects/LOD.js
  10335. /**
  10336. * @author mikael emtinger / http://gomo.se/
  10337. * @author alteredq / http://alteredqualia.com/
  10338. * @author mrdoob / http://mrdoob.com/
  10339. */
  10340. THREE.LOD = function () {
  10341. THREE.Object3D.call( this );
  10342. Object.defineProperties( this, {
  10343. levels: {
  10344. enumerable: true,
  10345. value: []
  10346. },
  10347. objects: {
  10348. get: function () {
  10349. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  10350. return this.levels;
  10351. }
  10352. }
  10353. } );
  10354. };
  10355. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  10356. THREE.LOD.prototype.constructor = THREE.LOD;
  10357. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  10358. if ( distance === undefined ) distance = 0;
  10359. distance = Math.abs( distance );
  10360. var levels = this.levels;
  10361. for ( var l = 0; l < levels.length; l ++ ) {
  10362. if ( distance < levels[ l ].distance ) {
  10363. break;
  10364. }
  10365. }
  10366. levels.splice( l, 0, { distance: distance, object: object } );
  10367. this.add( object );
  10368. };
  10369. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  10370. var levels = this.levels;
  10371. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  10372. if ( distance < levels[ i ].distance ) {
  10373. break;
  10374. }
  10375. }
  10376. return levels[ i - 1 ].object;
  10377. };
  10378. THREE.LOD.prototype.raycast = ( function () {
  10379. var matrixPosition = new THREE.Vector3();
  10380. return function ( raycaster, intersects ) {
  10381. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  10382. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  10383. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  10384. };
  10385. }() );
  10386. THREE.LOD.prototype.update = function () {
  10387. var v1 = new THREE.Vector3();
  10388. var v2 = new THREE.Vector3();
  10389. return function ( camera ) {
  10390. var levels = this.levels;
  10391. if ( levels.length > 1 ) {
  10392. v1.setFromMatrixPosition( camera.matrixWorld );
  10393. v2.setFromMatrixPosition( this.matrixWorld );
  10394. var distance = v1.distanceTo( v2 );
  10395. levels[ 0 ].object.visible = true;
  10396. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  10397. if ( distance >= levels[ i ].distance ) {
  10398. levels[ i - 1 ].object.visible = false;
  10399. levels[ i ].object.visible = true;
  10400. } else {
  10401. break;
  10402. }
  10403. }
  10404. for ( ; i < l; i ++ ) {
  10405. levels[ i ].object.visible = false;
  10406. }
  10407. }
  10408. };
  10409. }();
  10410. THREE.LOD.prototype.clone = function ( object ) {
  10411. if ( object === undefined ) object = new THREE.LOD();
  10412. THREE.Object3D.prototype.clone.call( this, object, false );
  10413. var levels = this.levels;
  10414. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  10415. var level = levels[ i ];
  10416. object.addLevel( level.object.clone(), level.distance );
  10417. }
  10418. return object;
  10419. };
  10420. // File:src/objects/Sprite.js
  10421. /**
  10422. * @author mikael emtinger / http://gomo.se/
  10423. * @author alteredq / http://alteredqualia.com/
  10424. */
  10425. THREE.Sprite = ( function () {
  10426. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  10427. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  10428. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  10429. var geometry = new THREE.BufferGeometry();
  10430. geometry.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  10431. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  10432. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  10433. return function ( material ) {
  10434. THREE.Object3D.call( this );
  10435. this.type = 'Sprite';
  10436. this.geometry = geometry;
  10437. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  10438. };
  10439. } )();
  10440. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  10441. THREE.Sprite.prototype.constructor = THREE.Sprite;
  10442. THREE.Sprite.prototype.raycast = ( function () {
  10443. var matrixPosition = new THREE.Vector3();
  10444. return function ( raycaster, intersects ) {
  10445. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  10446. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  10447. if ( distance > this.scale.x ) {
  10448. return;
  10449. }
  10450. intersects.push( {
  10451. distance: distance,
  10452. point: this.position,
  10453. face: null,
  10454. object: this
  10455. } );
  10456. };
  10457. }() );
  10458. THREE.Sprite.prototype.clone = function ( object ) {
  10459. if ( object === undefined ) object = new THREE.Sprite( this.material );
  10460. THREE.Object3D.prototype.clone.call( this, object );
  10461. return object;
  10462. };
  10463. THREE.Sprite.prototype.toJSON = function ( meta ) {
  10464. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  10465. // only serialize if not in meta materials cache
  10466. if ( meta.materials[ this.material.uuid ] === undefined ) {
  10467. meta.materials[ this.material.uuid ] = this.material.toJSON();
  10468. }
  10469. data.object.material = this.material.uuid;
  10470. return data;
  10471. };
  10472. // Backwards compatibility
  10473. THREE.Particle = THREE.Sprite;
  10474. // File:src/objects/LensFlare.js
  10475. /**
  10476. * @author mikael emtinger / http://gomo.se/
  10477. * @author alteredq / http://alteredqualia.com/
  10478. */
  10479. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  10480. THREE.Object3D.call( this );
  10481. this.lensFlares = [];
  10482. this.positionScreen = new THREE.Vector3();
  10483. this.customUpdateCallback = undefined;
  10484. if ( texture !== undefined ) {
  10485. this.add( texture, size, distance, blending, color );
  10486. }
  10487. };
  10488. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  10489. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  10490. /*
  10491. * Add: adds another flare
  10492. */
  10493. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  10494. if ( size === undefined ) size = - 1;
  10495. if ( distance === undefined ) distance = 0;
  10496. if ( opacity === undefined ) opacity = 1;
  10497. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  10498. if ( blending === undefined ) blending = THREE.NormalBlending;
  10499. distance = Math.min( distance, Math.max( 0, distance ) );
  10500. this.lensFlares.push( {
  10501. texture: texture, // THREE.Texture
  10502. size: size, // size in pixels (-1 = use texture.width)
  10503. distance: distance, // distance (0-1) from light source (0=at light source)
  10504. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  10505. scale: 1, // scale
  10506. rotation: 1, // rotation
  10507. opacity: opacity, // opacity
  10508. color: color, // color
  10509. blending: blending // blending
  10510. } );
  10511. };
  10512. /*
  10513. * Update lens flares update positions on all flares based on the screen position
  10514. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  10515. */
  10516. THREE.LensFlare.prototype.updateLensFlares = function () {
  10517. var f, fl = this.lensFlares.length;
  10518. var flare;
  10519. var vecX = - this.positionScreen.x * 2;
  10520. var vecY = - this.positionScreen.y * 2;
  10521. for ( f = 0; f < fl; f ++ ) {
  10522. flare = this.lensFlares[ f ];
  10523. flare.x = this.positionScreen.x + vecX * flare.distance;
  10524. flare.y = this.positionScreen.y + vecY * flare.distance;
  10525. flare.wantedRotation = flare.x * Math.PI * 0.25;
  10526. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  10527. }
  10528. };
  10529. THREE.LensFlare.prototype.clone = function ( object ) {
  10530. if ( object === undefined ) object = new THREE.LensFlare();
  10531. THREE.Object3D.prototype.clone.call( this, object );
  10532. object.positionScreen.copy( this.positionScreen );
  10533. object.customUpdateCallback = this.customUpdateCallback;
  10534. for ( var i = 0, l = this.lensFlares.length; i < l; i ++ ) {
  10535. object.lensFlares.push( this.lensFlares[ i ] );
  10536. }
  10537. return object;
  10538. };
  10539. // File:src/scenes/Scene.js
  10540. /**
  10541. * @author mrdoob / http://mrdoob.com/
  10542. */
  10543. THREE.Scene = function () {
  10544. THREE.Object3D.call( this );
  10545. this.type = 'Scene';
  10546. this.fog = null;
  10547. this.overrideMaterial = null;
  10548. this.autoUpdate = true; // checked by the renderer
  10549. };
  10550. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  10551. THREE.Scene.prototype.constructor = THREE.Scene;
  10552. THREE.Scene.prototype.clone = function ( object ) {
  10553. if ( object === undefined ) object = new THREE.Scene();
  10554. THREE.Object3D.prototype.clone.call( this, object );
  10555. if ( this.fog !== null ) object.fog = this.fog.clone();
  10556. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  10557. object.autoUpdate = this.autoUpdate;
  10558. object.matrixAutoUpdate = this.matrixAutoUpdate;
  10559. return object;
  10560. };
  10561. // File:src/scenes/Fog.js
  10562. /**
  10563. * @author mrdoob / http://mrdoob.com/
  10564. * @author alteredq / http://alteredqualia.com/
  10565. */
  10566. THREE.Fog = function ( color, near, far ) {
  10567. this.name = '';
  10568. this.color = new THREE.Color( color );
  10569. this.near = ( near !== undefined ) ? near : 1;
  10570. this.far = ( far !== undefined ) ? far : 1000;
  10571. };
  10572. THREE.Fog.prototype.clone = function () {
  10573. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  10574. };
  10575. // File:src/scenes/FogExp2.js
  10576. /**
  10577. * @author mrdoob / http://mrdoob.com/
  10578. * @author alteredq / http://alteredqualia.com/
  10579. */
  10580. THREE.FogExp2 = function ( color, density ) {
  10581. this.name = '';
  10582. this.color = new THREE.Color( color );
  10583. this.density = ( density !== undefined ) ? density : 0.00025;
  10584. };
  10585. THREE.FogExp2.prototype.clone = function () {
  10586. return new THREE.FogExp2( this.color.getHex(), this.density );
  10587. };
  10588. // File:src/renderers/shaders/ShaderChunk.js
  10589. THREE.ShaderChunk = {};
  10590. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  10591. THREE.ShaderChunk[ 'alphamap_fragment'] = "#ifdef USE_ALPHAMAP\n\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n\n#endif\n";
  10592. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  10593. THREE.ShaderChunk[ 'alphamap_pars_fragment'] = "#ifdef USE_ALPHAMAP\n\n uniform sampler2D alphaMap;\n\n#endif\n";
  10594. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  10595. THREE.ShaderChunk[ 'alphatest_fragment'] = "#ifdef ALPHATEST\n\n if ( diffuseColor.a < ALPHATEST ) discard;\n\n#endif\n";
  10596. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  10597. THREE.ShaderChunk[ 'aomap_fragment'] = "#ifdef USE_AOMAP\n\n totalAmbientLight *= ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\n#endif\n";
  10598. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  10599. THREE.ShaderChunk[ 'aomap_pars_fragment'] = "#ifdef USE_AOMAP\n\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n\n#endif";
  10600. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  10601. THREE.ShaderChunk[ 'bumpmap_pars_fragment'] = "#ifdef USE_BUMPMAP\n\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n\n // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\n // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\n\n // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\n\n vec2 dHdxy_fwd() {\n\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\n\n float Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\n return vec2( dBx, dBy );\n\n }\n\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm; // normalized\n\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n\n float fDet = dot( vSigmaX, R1 );\n\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n\n }\n\n#endif\n";
  10602. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  10603. THREE.ShaderChunk[ 'color_fragment'] = "#ifdef USE_COLOR\n\n diffuseColor.rgb *= vColor;\n\n#endif";
  10604. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  10605. THREE.ShaderChunk[ 'color_pars_fragment'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif\n";
  10606. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  10607. THREE.ShaderChunk[ 'color_pars_vertex'] = "#ifdef USE_COLOR\n\n varying vec3 vColor;\n\n#endif";
  10608. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  10609. THREE.ShaderChunk[ 'color_vertex'] = "#ifdef USE_COLOR\n\n vColor.xyz = color.xyz;\n\n#endif";
  10610. // File:src/renderers/shaders/ShaderChunk/common.glsl
  10611. THREE.ShaderChunk[ 'common'] = "#define PI 3.14159\n#define PI2 6.28318\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\n\nvec3 transformDirection( in vec3 normal, in mat4 matrix ) {\n\n return normalize( ( matrix * vec4( normal, 0.0 ) ).xyz );\n\n}\n\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\nvec3 inverseTransformDirection( in vec3 normal, in mat4 matrix ) {\n\n return normalize( ( vec4( normal, 0.0 ) * matrix ).xyz );\n\n}\n\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n float distance = dot( planeNormal, point - pointOnPlane );\n\n return - distance * planeNormal + point;\n\n}\n\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n return sign( dot( point - pointOnPlane, planeNormal ) );\n\n}\n\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\n return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n\n}\n\nfloat calcLightAttenuation( float lightDistance, float cutoffDistance, float decayExponent ) {\n\n if ( decayExponent > 0.0 ) {\n\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n\n }\n\n return 1.0;\n\n}\n\nvec3 F_Schlick( in vec3 specularColor, in float dotLH ) {\n\n return ( 1.0 - specularColor ) * pow( 1.0 - dotLH, 5.0 ) + specularColor;\n\n}\n\nfloat G_BlinnPhong_Implicit( /* in float dotNL, in float dotNV */ ) {\n\n // geometry term is (n⋅l)(n⋅v) / 4(n⋅l)(n⋅v)\n\n return 0.25;\n\n}\n\nfloat D_BlinnPhong( in float shininess, in float dotNH ) {\n\n // factor of 1/PI in distribution term omitted\n\n return ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n\n}\n\nvec3 BRDF_BlinnPhong( in vec3 specularColor, in float shininess, in vec3 normal, in vec3 lightDir, in vec3 viewDir ) {\n\n vec3 halfDir = normalize( lightDir + viewDir );\n\n //float dotNL = saturate( dot( normal, lightDir ) );\n //float dotNV = saturate( dot( normal, viewDir ) );\n float dotNH = saturate( dot( normal, halfDir ) );\n float dotLH = saturate( dot( lightDir, halfDir ) );\n\n vec3 F = F_Schlick( specularColor, dotLH );\n\n float G = G_BlinnPhong_Implicit( /* dotNL, dotNV */ );\n\n float D = D_BlinnPhong( shininess, dotNH );\n\n return F * G * D;\n\n}\n\nvec3 inputToLinear( in vec3 a ) {\n\n #ifdef GAMMA_INPUT\n\n return pow( a, vec3( float( GAMMA_FACTOR ) ) );\n\n #else\n\n return a;\n\n #endif\n\n}\n\nvec3 linearToOutput( in vec3 a ) {\n\n #ifdef GAMMA_OUTPUT\n\n return pow( a, vec3( 1.0 / float( GAMMA_FACTOR ) ) );\n\n #else\n\n return a;\n\n #endif\n\n}\n";
  10612. // File:src/renderers/shaders/ShaderChunk/default_vertex.glsl
  10613. THREE.ShaderChunk[ 'default_vertex'] = "#ifdef USE_SKINNING\n\n vec4 mvPosition = modelViewMatrix * skinned;\n\n#elif defined( USE_MORPHTARGETS )\n\n vec4 mvPosition = modelViewMatrix * vec4( morphed, 1.0 );\n\n#else\n\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\n#endif\n\ngl_Position = projectionMatrix * mvPosition;\n";
  10614. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  10615. THREE.ShaderChunk[ 'defaultnormal_vertex'] = "#ifdef USE_SKINNING\n\n vec3 objectNormal = skinnedNormal.xyz;\n\n#elif defined( USE_MORPHNORMALS )\n\n vec3 objectNormal = morphedNormal;\n\n#else\n\n vec3 objectNormal = normal;\n\n#endif\n\n#ifdef FLIP_SIDED\n\n objectNormal = -objectNormal;\n\n#endif\n\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  10616. // File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl
  10617. THREE.ShaderChunk[ 'emissivemap_fragment'] = "#ifdef USE_EMISSIVEMAP\n\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n\n emissiveColor.rgb = inputToLinear( emissiveColor.rgb );\n\n totalEmissiveLight *= emissiveColor.rgb;\n\n#endif\n";
  10618. // File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl
  10619. THREE.ShaderChunk[ 'emissivemap_pars_fragment'] = "#ifdef USE_EMISSIVEMAP\n\n uniform sampler2D emissiveMap;\n\n#endif\n";
  10620. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  10621. THREE.ShaderChunk[ 'envmap_fragment'] = "#ifdef USE_ENVMAP\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\n // Transforming Normal Vectors with the Inverse Transformation\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n #else\n\n vec3 reflectVec = vReflect;\n\n #endif\n\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\n #elif defined( ENVMAP_TYPE_EQUIREC )\n vec2 sampleUV;\n sampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n sampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n vec4 envColor = texture2D( envMap, sampleUV );\n\n #elif defined( ENVMAP_TYPE_SPHERE )\n vec3 reflectView = flipNormal * normalize((viewMatrix * vec4( reflectVec, 0.0 )).xyz + vec3(0.0,0.0,1.0));\n vec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n #endif\n\n envColor.xyz = inputToLinear( envColor.xyz );\n\n #ifdef ENVMAP_BLENDING_MULTIPLY\n\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_MIX )\n\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\n #elif defined( ENVMAP_BLENDING_ADD )\n\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n\n #endif\n\n#endif\n";
  10622. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  10623. THREE.ShaderChunk[ 'envmap_pars_fragment'] = "#ifdef USE_ENVMAP\n\n uniform float reflectivity;\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\n uniform float refractionRatio;\n\n #else\n\n varying vec3 vReflect;\n\n #endif\n\n#endif\n";
  10624. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  10625. THREE.ShaderChunk[ 'envmap_pars_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n varying vec3 vReflect;\n\n uniform float refractionRatio;\n\n#endif\n";
  10626. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  10627. THREE.ShaderChunk[ 'envmap_vertex'] = "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP ) && ! defined( PHONG )\n\n vec3 worldNormal = transformDirection( objectNormal, modelMatrix );\n\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\n #ifdef ENVMAP_MODE_REFLECTION\n\n vReflect = reflect( cameraToVertex, worldNormal );\n\n #else\n\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\n #endif\n\n#endif\n";
  10628. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  10629. THREE.ShaderChunk[ 'fog_fragment'] = "#ifdef USE_FOG\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n\n #else\n\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n\n #endif\n\n #ifdef FOG_EXP2\n\n float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\n #else\n\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n\n #endif\n \n outgoingLight = mix( outgoingLight, fogColor, fogFactor );\n\n#endif";
  10630. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  10631. THREE.ShaderChunk[ 'fog_pars_fragment'] = "#ifdef USE_FOG\n\n uniform vec3 fogColor;\n\n #ifdef FOG_EXP2\n\n uniform float fogDensity;\n\n #else\n\n uniform float fogNear;\n uniform float fogFar;\n #endif\n\n#endif";
  10632. // File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl
  10633. THREE.ShaderChunk[ 'lightmap_fragment'] = "#ifdef USE_LIGHTMAP\n\n totalAmbientLight += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\n#endif\n";
  10634. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  10635. THREE.ShaderChunk[ 'lightmap_pars_fragment'] = "#ifdef USE_LIGHTMAP\n\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n\n#endif";
  10636. // File:src/renderers/shaders/ShaderChunk/lights_lambert_pars_vertex.glsl
  10637. THREE.ShaderChunk[ 'lights_lambert_pars_vertex'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n";
  10638. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  10639. THREE.ShaderChunk[ 'lights_lambert_vertex'] = "vLightFront = vec3( 0.0 );\n\n#ifdef DOUBLE_SIDED\n\n vLightBack = vec3( 0.0 );\n\n#endif\n\nvec3 normal = normalize( transformedNormal );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec3 lightColor = pointLightColor[ i ];\n\n vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n vLightFront += lightColor * attenuation * saturate( dotProduct );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += lightColor * attenuation * saturate( - dotProduct );\n\n #endif\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec3 lightColor = spotLightColor[ i ];\n\n vec3 lightPosition = spotLightPosition[ i ];\n vec4 lPosition = viewMatrix * vec4( lightPosition, 1.0 );\n vec3 lVector = lPosition.xyz - mvPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( lightPosition - worldPosition.xyz ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = saturate( pow( saturate( spotEffect ), spotLightExponent[ i ] ) );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n attenuation *= spotEffect;\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n vLightFront += lightColor * attenuation * saturate( dotProduct );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += lightColor * attenuation * saturate( - dotProduct );\n\n #endif\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for ( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 lightColor = directionalLightColor[ i ];\n\n vec3 lightDir = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n vLightFront += lightColor * saturate( dotProduct );\n\n #ifdef DOUBLE_SIDED\n\n vLightBack += lightColor * saturate( - dotProduct );\n\n #endif\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for ( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lightDir = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n #ifdef DOUBLE_SIDED\n\n float hemiDiffuseWeightBack = - 0.5 * dotProduct + 0.5;\n\n vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );\n\n #endif\n\n }\n\n#endif\n\nvLightFront += ambientLightColor;\n\n#ifdef DOUBLE_SIDED\n\n vLightBack += ambientLightColor;\n\n#endif\n";
  10640. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  10641. THREE.ShaderChunk[ 'lights_phong_fragment'] = "#ifndef FLAT_SHADED\n\n vec3 normal = normalize( vNormal );\n\n #ifdef DOUBLE_SIDED\n\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n\n #endif\n\n#else\n\n vec3 fdx = dFdx( vViewPosition );\n vec3 fdy = dFdy( vViewPosition );\n vec3 normal = normalize( cross( fdx, fdy ) );\n\n#endif\n\n#ifdef USE_NORMALMAP\n\n normal = perturbNormal2Arb( -vViewPosition, normal );\n\n#elif defined( USE_BUMPMAP )\n\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n\n#endif\n\nvec3 viewDir = normalize( vViewPosition );\n\nvec3 totalDiffuseLight = vec3( 0.0 );\nvec3 totalSpecularLight = vec3( 0.0 );\n\n#if MAX_POINT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {\n\n vec3 lightColor = pointLightColor[ i ];\n\n vec3 lightPosition = pointLightPosition[ i ];\n vec4 lPosition = viewMatrix * vec4( lightPosition, 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), pointLightDistance[ i ], pointLightDecay[ i ] );\n\n // diffuse\n\n float cosineTerm = saturate( dot( normal, lightDir ) );\n\n totalDiffuseLight += lightColor * attenuation * cosineTerm;\n\n // specular\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * attenuation * cosineTerm;\n\n\n }\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {\n\n vec3 lightColor = spotLightColor[ i ];\n\n vec3 lightPosition = spotLightPosition[ i ];\n vec4 lPosition = viewMatrix * vec4( lightPosition, 1.0 );\n vec3 lVector = lPosition.xyz + vViewPosition.xyz;\n vec3 lightDir = normalize( lVector );\n\n float spotEffect = dot( spotLightDirection[ i ], normalize( lightPosition - vWorldPosition ) );\n\n if ( spotEffect > spotLightAngleCos[ i ] ) {\n\n spotEffect = saturate( pow( saturate( spotEffect ), spotLightExponent[ i ] ) );\n\n // attenuation\n\n float attenuation = calcLightAttenuation( length( lVector ), spotLightDistance[ i ], spotLightDecay[ i ] );\n\n attenuation *= spotEffect;\n\n // diffuse\n\n float cosineTerm = saturate( dot( normal, lightDir ) );\n\n totalDiffuseLight += lightColor * attenuation * cosineTerm;\n\n // specular\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * attenuation * cosineTerm;\n\n }\n\n }\n\n#endif\n\n#if MAX_DIR_LIGHTS > 0\n\n for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {\n\n vec3 lightColor = directionalLightColor[ i ];\n\n vec3 lightDir = transformDirection( directionalLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float cosineTerm = saturate( dot( normal, lightDir ) );\n\n totalDiffuseLight += lightColor * cosineTerm;\n\n // specular\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * cosineTerm;\n\n }\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {\n\n vec3 lightDir = transformDirection( hemisphereLightDirection[ i ], viewMatrix );\n\n // diffuse\n\n float dotProduct = dot( normal, lightDir );\n\n float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;\n\n vec3 lightColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );\n\n totalDiffuseLight += lightColor;\n\n // specular (sky term only)\n\n vec3 brdf = BRDF_BlinnPhong( specular, shininess, normal, lightDir, viewDir );\n\n totalSpecularLight += brdf * specularStrength * lightColor * max( dotProduct, 0.0 );\n\n }\n\n#endif\n\n#ifdef METAL\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalAmbientLight ) * specular + totalSpecularLight + totalEmissiveLight;\n\n#else\n\n outgoingLight += diffuseColor.rgb * ( totalDiffuseLight + totalAmbientLight ) + totalSpecularLight + totalEmissiveLight;\n\n#endif\n";
  10642. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  10643. THREE.ShaderChunk[ 'lights_phong_pars_fragment'] = "uniform vec3 ambientLightColor;\n\n#if MAX_DIR_LIGHTS > 0\n\n uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];\n uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];\n\n#endif\n\n#if MAX_HEMI_LIGHTS > 0\n\n uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];\n uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];\n\n#endif\n\n#if MAX_POINT_LIGHTS > 0\n\n uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];\n\n uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];\n uniform float pointLightDistance[ MAX_POINT_LIGHTS ];\n uniform float pointLightDecay[ MAX_POINT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0\n\n uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];\n uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];\n uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];\n uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];\n uniform float spotLightDecay[ MAX_SPOT_LIGHTS ];\n\n#endif\n\n#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n\nvarying vec3 vViewPosition;\n\n#ifndef FLAT_SHADED\n\n varying vec3 vNormal;\n\n#endif\n";
  10644. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_vertex.glsl
  10645. THREE.ShaderChunk[ 'lights_phong_pars_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n varying vec3 vWorldPosition;\n\n#endif\n";
  10646. // File:src/renderers/shaders/ShaderChunk/lights_phong_vertex.glsl
  10647. THREE.ShaderChunk[ 'lights_phong_vertex'] = "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )\n\n vWorldPosition = worldPosition.xyz;\n\n#endif";
  10648. // File:src/renderers/shaders/ShaderChunk/linear_to_gamma_fragment.glsl
  10649. THREE.ShaderChunk[ 'linear_to_gamma_fragment'] = "\n outgoingLight = linearToOutput( outgoingLight );\n";
  10650. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  10651. THREE.ShaderChunk[ 'logdepthbuf_fragment'] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n\n#endif";
  10652. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  10653. THREE.ShaderChunk[ 'logdepthbuf_pars_fragment'] = "#ifdef USE_LOGDEPTHBUF\n\n uniform float logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n #extension GL_EXT_frag_depth : enable\n varying float vFragDepth;\n\n #endif\n\n#endif";
  10654. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  10655. THREE.ShaderChunk[ 'logdepthbuf_pars_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n varying float vFragDepth;\n\n #endif\n\n uniform float logDepthBufFC;\n\n#endif";
  10656. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  10657. THREE.ShaderChunk[ 'logdepthbuf_vertex'] = "#ifdef USE_LOGDEPTHBUF\n\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\n #ifdef USE_LOGDEPTHBUF_EXT\n\n vFragDepth = 1.0 + gl_Position.w;\n\n#else\n\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\n #endif\n\n#endif";
  10658. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  10659. THREE.ShaderChunk[ 'map_fragment'] = "#ifdef USE_MAP\n\n vec4 texelColor = texture2D( map, vUv );\n\n texelColor.xyz = inputToLinear( texelColor.xyz );\n\n diffuseColor *= texelColor;\n\n#endif\n";
  10660. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  10661. THREE.ShaderChunk[ 'map_pars_fragment'] = "#ifdef USE_MAP\n\n uniform sampler2D map;\n\n#endif";
  10662. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  10663. THREE.ShaderChunk[ 'map_particle_fragment'] = "#ifdef USE_MAP\n\n diffuseColor *= texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\n#endif\n";
  10664. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  10665. THREE.ShaderChunk[ 'map_particle_pars_fragment'] = "#ifdef USE_MAP\n\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n\n#endif\n";
  10666. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  10667. THREE.ShaderChunk[ 'morphnormal_vertex'] = "#ifdef USE_MORPHNORMALS\n\n vec3 morphedNormal = vec3( 0.0 );\n\n morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n\n morphedNormal += normal;\n\n#endif";
  10668. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  10669. THREE.ShaderChunk[ 'morphtarget_pars_vertex'] = "#ifdef USE_MORPHTARGETS\n\n #ifndef USE_MORPHNORMALS\n\n uniform float morphTargetInfluences[ 8 ];\n\n #else\n\n uniform float morphTargetInfluences[ 4 ];\n\n #endif\n\n#endif";
  10670. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  10671. THREE.ShaderChunk[ 'morphtarget_vertex'] = "#ifdef USE_MORPHTARGETS\n\n vec3 morphed = vec3( 0.0 );\n morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\n #ifndef USE_MORPHNORMALS\n\n morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\n #endif\n\n morphed += position;\n\n#endif";
  10672. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  10673. THREE.ShaderChunk[ 'normalmap_pars_fragment'] = "#ifdef USE_NORMALMAP\n\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n\n // Per-Pixel Tangent Space Normal Mapping\n // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\n\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\n vec3 q0 = dFdx( eye_pos.xyz );\n vec3 q1 = dFdy( eye_pos.xyz );\n vec2 st0 = dFdx( vUv.st );\n vec2 st1 = dFdy( vUv.st );\n\n vec3 S = normalize( q0 * st1.t - q1 * st0.t );\n vec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n vec3 N = normalize( surf_norm );\n\n vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n mapN.xy = normalScale * mapN.xy;\n mat3 tsn = mat3( S, T, N );\n return normalize( tsn * mapN );\n\n }\n\n#endif\n";
  10674. // File:src/renderers/shaders/ShaderChunk/shadowmap_fragment.glsl
  10675. THREE.ShaderChunk[ 'shadowmap_fragment'] = "#ifdef USE_SHADOWMAP\n\n #ifdef SHADOWMAP_DEBUG\n\n vec3 frustumColors[3];\n frustumColors[0] = vec3( 1.0, 0.5, 0.0 );\n frustumColors[1] = vec3( 0.0, 1.0, 0.8 );\n frustumColors[2] = vec3( 0.0, 0.5, 1.0 );\n\n #endif\n\n #ifdef SHADOWMAP_CASCADE\n\n int inFrustumCount = 0;\n\n #endif\n\n float fDepth;\n vec3 shadowColor = vec3( 1.0 );\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;\n\n // if ( something && something ) breaks ATI OpenGL shader compiler\n // if ( all( something, something ) ) using this instead\n\n bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n bool inFrustum = all( inFrustumVec );\n\n // don't shadow pixels outside of light frustum\n // use just first frustum (for cascades)\n // don't shadow pixels behind far plane of light frustum\n\n #ifdef SHADOWMAP_CASCADE\n\n inFrustumCount += int( inFrustum );\n bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );\n\n #else\n\n bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\n #endif\n\n bool frustumTest = all( frustumTestVec );\n\n if ( frustumTest ) {\n\n shadowCoord.z += shadowBias[ i ];\n\n #if defined( SHADOWMAP_TYPE_PCF )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n /*\n // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL\n // must enroll loop manually\n\n for ( float y = -1.25; y <= 1.25; y += 1.25 )\n for ( float x = -1.25; x <= 1.25; x += 1.25 ) {\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );\n\n // doesn't seem to produce any noticeable visual difference compared to simple texture2D lookup\n //vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );\n\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n shadow += 1.0;\n\n }\n\n shadow /= 9.0;\n\n */\n\n const float shadowDelta = 1.0 / 9.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.25 * xPixelOffset;\n float dy0 = -1.25 * yPixelOffset;\n float dx1 = 1.25 * xPixelOffset;\n float dy1 = 1.25 * yPixelOffset;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n if ( fDepth < shadowCoord.z ) shadow += shadowDelta;\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\n // Percentage-close filtering\n // (9 pixel kernel)\n // http://fabiensanglard.net/shadowmappingPCF/\n\n float shadow = 0.0;\n\n float xPixelOffset = 1.0 / shadowMapSize[ i ].x;\n float yPixelOffset = 1.0 / shadowMapSize[ i ].y;\n\n float dx0 = -1.0 * xPixelOffset;\n float dy0 = -1.0 * yPixelOffset;\n float dx1 = 1.0 * xPixelOffset;\n float dy1 = 1.0 * yPixelOffset;\n\n mat3 shadowKernel;\n mat3 depthKernel;\n\n depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );\n depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );\n depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );\n depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );\n depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );\n depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );\n depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );\n depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );\n depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );\n\n vec3 shadowZ = vec3( shadowCoord.z );\n shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));\n shadowKernel[0] *= vec3(0.25);\n\n shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));\n shadowKernel[1] *= vec3(0.25);\n\n shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));\n shadowKernel[2] *= vec3(0.25);\n\n vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );\n\n shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );\n shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );\n\n vec4 shadowValues;\n shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );\n shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );\n shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );\n shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );\n\n shadow = dot( shadowValues, vec4( 1.0 ) );\n\n shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );\n\n #else\n\n vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );\n float fDepth = unpackDepth( rgbaDepth );\n\n if ( fDepth < shadowCoord.z )\n\n // spot with multiple shadows is darker\n\n shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );\n\n // spot with multiple shadows has the same color as single shadow spot\n\n // shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );\n\n #endif\n\n }\n\n\n #ifdef SHADOWMAP_DEBUG\n\n #ifdef SHADOWMAP_CASCADE\n\n if ( inFrustum && inFrustumCount == 1 ) outgoingLight *= frustumColors[ i ];\n\n #else\n\n if ( inFrustum ) outgoingLight *= frustumColors[ i ];\n\n #endif\n\n #endif\n\n }\n\n outgoingLight = outgoingLight * shadowColor;\n\n#endif\n";
  10676. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  10677. THREE.ShaderChunk[ 'shadowmap_pars_fragment'] = "#ifdef USE_SHADOWMAP\n\n uniform sampler2D shadowMap[ MAX_SHADOWS ];\n uniform vec2 shadowMapSize[ MAX_SHADOWS ];\n\n uniform float shadowDarkness[ MAX_SHADOWS ];\n uniform float shadowBias[ MAX_SHADOWS ];\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n\n float unpackDepth( const in vec4 rgba_depth ) {\n\n const vec4 bit_shift = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n float depth = dot( rgba_depth, bit_shift );\n return depth;\n\n }\n\n#endif";
  10678. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  10679. THREE.ShaderChunk[ 'shadowmap_pars_vertex'] = "#ifdef USE_SHADOWMAP\n\n varying vec4 vShadowCoord[ MAX_SHADOWS ];\n uniform mat4 shadowMatrix[ MAX_SHADOWS ];\n\n#endif";
  10680. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  10681. THREE.ShaderChunk[ 'shadowmap_vertex'] = "#ifdef USE_SHADOWMAP\n\n for( int i = 0; i < MAX_SHADOWS; i ++ ) {\n\n vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;\n\n }\n\n#endif";
  10682. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  10683. THREE.ShaderChunk[ 'skinbase_vertex'] = "#ifdef USE_SKINNING\n\n mat4 boneMatX = getBoneMatrix( skinIndex.x );\n mat4 boneMatY = getBoneMatrix( skinIndex.y );\n mat4 boneMatZ = getBoneMatrix( skinIndex.z );\n mat4 boneMatW = getBoneMatrix( skinIndex.w );\n\n#endif";
  10684. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  10685. THREE.ShaderChunk[ 'skinning_pars_vertex'] = "#ifdef USE_SKINNING\n\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n\n #ifdef BONE_TEXTURE\n\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n\n mat4 getBoneMatrix( const in float i ) {\n\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n\n y = dy * ( y + 0.5 );\n\n vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\n mat4 bone = mat4( v1, v2, v3, v4 );\n\n return bone;\n\n }\n\n #else\n\n uniform mat4 boneGlobalMatrices[ MAX_BONES ];\n\n mat4 getBoneMatrix( const in float i ) {\n\n mat4 bone = boneGlobalMatrices[ int(i) ];\n return bone;\n\n }\n\n #endif\n\n#endif\n";
  10686. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  10687. THREE.ShaderChunk[ 'skinning_vertex'] = "#ifdef USE_SKINNING\n\n #ifdef USE_MORPHTARGETS\n\n vec4 skinVertex = bindMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 skinVertex = bindMatrix * vec4( position, 1.0 );\n\n #endif\n\n vec4 skinned = vec4( 0.0 );\n skinned += boneMatX * skinVertex * skinWeight.x;\n skinned += boneMatY * skinVertex * skinWeight.y;\n skinned += boneMatZ * skinVertex * skinWeight.z;\n skinned += boneMatW * skinVertex * skinWeight.w;\n skinned = bindMatrixInverse * skinned;\n\n#endif\n";
  10688. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  10689. THREE.ShaderChunk[ 'skinnormal_vertex'] = "#ifdef USE_SKINNING\n\n mat4 skinMatrix = mat4( 0.0 );\n skinMatrix += skinWeight.x * boneMatX;\n skinMatrix += skinWeight.y * boneMatY;\n skinMatrix += skinWeight.z * boneMatZ;\n skinMatrix += skinWeight.w * boneMatW;\n skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\n #ifdef USE_MORPHNORMALS\n\n vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );\n\n #else\n\n vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );\n\n #endif\n\n#endif\n";
  10690. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  10691. THREE.ShaderChunk[ 'specularmap_fragment'] = "float specularStrength;\n\n#ifdef USE_SPECULARMAP\n\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n\n#else\n\n specularStrength = 1.0;\n\n#endif";
  10692. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  10693. THREE.ShaderChunk[ 'specularmap_pars_fragment'] = "#ifdef USE_SPECULARMAP\n\n uniform sampler2D specularMap;\n\n#endif";
  10694. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  10695. THREE.ShaderChunk[ 'uv2_pars_fragment'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n varying vec2 vUv2;\n\n#endif";
  10696. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  10697. THREE.ShaderChunk[ 'uv2_pars_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n attribute vec2 uv2;\n varying vec2 vUv2;\n\n#endif";
  10698. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  10699. THREE.ShaderChunk[ 'uv2_vertex'] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\n vUv2 = uv2;\n\n#endif";
  10700. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  10701. THREE.ShaderChunk[ 'uv_pars_fragment'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP )\n\n varying vec2 vUv;\n\n#endif";
  10702. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  10703. THREE.ShaderChunk[ 'uv_pars_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP )\n\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n\n#endif\n";
  10704. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  10705. THREE.ShaderChunk[ 'uv_vertex'] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP )\n\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n\n#endif";
  10706. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  10707. THREE.ShaderChunk[ 'worldpos_vertex'] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\n #ifdef USE_SKINNING\n\n vec4 worldPosition = modelMatrix * skinned;\n\n #elif defined( USE_MORPHTARGETS )\n\n vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );\n\n #else\n\n vec4 worldPosition = modelMatrix * vec4( position, 1.0 );\n\n #endif\n\n#endif\n";
  10708. // File:src/renderers/shaders/UniformsUtils.js
  10709. /**
  10710. * Uniform Utilities
  10711. */
  10712. THREE.UniformsUtils = {
  10713. merge: function ( uniforms ) {
  10714. var merged = {};
  10715. for ( var u = 0; u < uniforms.length; u ++ ) {
  10716. var tmp = this.clone( uniforms[ u ] );
  10717. for ( var p in tmp ) {
  10718. merged[ p ] = tmp[ p ];
  10719. }
  10720. }
  10721. return merged;
  10722. },
  10723. clone: function ( uniforms_src ) {
  10724. var uniforms_dst = {};
  10725. for ( var u in uniforms_src ) {
  10726. uniforms_dst[ u ] = {};
  10727. for ( var p in uniforms_src[ u ] ) {
  10728. var parameter_src = uniforms_src[ u ][ p ];
  10729. if ( parameter_src instanceof THREE.Color ||
  10730. parameter_src instanceof THREE.Vector2 ||
  10731. parameter_src instanceof THREE.Vector3 ||
  10732. parameter_src instanceof THREE.Vector4 ||
  10733. parameter_src instanceof THREE.Matrix3 ||
  10734. parameter_src instanceof THREE.Matrix4 ||
  10735. parameter_src instanceof THREE.Texture ) {
  10736. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10737. } else if ( Array.isArray( parameter_src ) ) {
  10738. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10739. } else {
  10740. uniforms_dst[ u ][ p ] = parameter_src;
  10741. }
  10742. }
  10743. }
  10744. return uniforms_dst;
  10745. }
  10746. };
  10747. // File:src/renderers/shaders/UniformsLib.js
  10748. /**
  10749. * Uniforms library for shared webgl shaders
  10750. */
  10751. THREE.UniformsLib = {
  10752. common: {
  10753. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10754. "opacity" : { type: "f", value: 1.0 },
  10755. "map" : { type: "t", value: null },
  10756. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10757. "specularMap" : { type: "t", value: null },
  10758. "alphaMap" : { type: "t", value: null },
  10759. "envMap" : { type: "t", value: null },
  10760. "flipEnvMap" : { type: "f", value: - 1 },
  10761. "reflectivity" : { type: "f", value: 1.0 },
  10762. "refractionRatio" : { type: "f", value: 0.98 }
  10763. },
  10764. aomap: {
  10765. "aoMap" : { type: "t", value: null },
  10766. "aoMapIntensity" : { type: "f", value: 1 },
  10767. },
  10768. lightmap: {
  10769. "lightMap" : { type: "t", value: null },
  10770. "lightMapIntensity" : { type: "f", value: 1 },
  10771. },
  10772. emissivemap: {
  10773. "emissiveMap" : { type: "t", value: null },
  10774. },
  10775. bump: {
  10776. "bumpMap" : { type: "t", value: null },
  10777. "bumpScale" : { type: "f", value: 1 }
  10778. },
  10779. normalmap: {
  10780. "normalMap" : { type: "t", value: null },
  10781. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10782. },
  10783. fog : {
  10784. "fogDensity" : { type: "f", value: 0.00025 },
  10785. "fogNear" : { type: "f", value: 1 },
  10786. "fogFar" : { type: "f", value: 2000 },
  10787. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10788. },
  10789. lights: {
  10790. "ambientLightColor" : { type: "fv", value: [] },
  10791. "directionalLightDirection" : { type: "fv", value: [] },
  10792. "directionalLightColor" : { type: "fv", value: [] },
  10793. "hemisphereLightDirection" : { type: "fv", value: [] },
  10794. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10795. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10796. "pointLightColor" : { type: "fv", value: [] },
  10797. "pointLightPosition" : { type: "fv", value: [] },
  10798. "pointLightDistance" : { type: "fv1", value: [] },
  10799. "pointLightDecay" : { type: "fv1", value: [] },
  10800. "spotLightColor" : { type: "fv", value: [] },
  10801. "spotLightPosition" : { type: "fv", value: [] },
  10802. "spotLightDirection" : { type: "fv", value: [] },
  10803. "spotLightDistance" : { type: "fv1", value: [] },
  10804. "spotLightAngleCos" : { type: "fv1", value: [] },
  10805. "spotLightExponent" : { type: "fv1", value: [] },
  10806. "spotLightDecay" : { type: "fv1", value: [] }
  10807. },
  10808. particle: {
  10809. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10810. "opacity" : { type: "f", value: 1.0 },
  10811. "size" : { type: "f", value: 1.0 },
  10812. "scale" : { type: "f", value: 1.0 },
  10813. "map" : { type: "t", value: null },
  10814. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10815. "fogDensity" : { type: "f", value: 0.00025 },
  10816. "fogNear" : { type: "f", value: 1 },
  10817. "fogFar" : { type: "f", value: 2000 },
  10818. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10819. },
  10820. shadowmap: {
  10821. "shadowMap": { type: "tv", value: [] },
  10822. "shadowMapSize": { type: "v2v", value: [] },
  10823. "shadowBias" : { type: "fv1", value: [] },
  10824. "shadowDarkness": { type: "fv1", value: [] },
  10825. "shadowMatrix" : { type: "m4v", value: [] }
  10826. }
  10827. };
  10828. // File:src/renderers/shaders/ShaderLib.js
  10829. /**
  10830. * Webgl Shader Library for three.js
  10831. *
  10832. * @author alteredq / http://alteredqualia.com/
  10833. * @author mrdoob / http://mrdoob.com/
  10834. * @author mikael emtinger / http://gomo.se/
  10835. */
  10836. THREE.ShaderLib = {
  10837. 'basic': {
  10838. uniforms: THREE.UniformsUtils.merge( [
  10839. THREE.UniformsLib[ "common" ],
  10840. THREE.UniformsLib[ "aomap" ],
  10841. THREE.UniformsLib[ "fog" ],
  10842. THREE.UniformsLib[ "shadowmap" ]
  10843. ] ),
  10844. vertexShader: [
  10845. THREE.ShaderChunk[ "common" ],
  10846. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10847. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10848. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10849. THREE.ShaderChunk[ "color_pars_vertex" ],
  10850. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10851. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10852. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10853. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10854. "void main() {",
  10855. THREE.ShaderChunk[ "uv_vertex" ],
  10856. THREE.ShaderChunk[ "uv2_vertex" ],
  10857. THREE.ShaderChunk[ "color_vertex" ],
  10858. THREE.ShaderChunk[ "skinbase_vertex" ],
  10859. " #ifdef USE_ENVMAP",
  10860. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10861. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10862. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10863. " #endif",
  10864. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10865. THREE.ShaderChunk[ "skinning_vertex" ],
  10866. THREE.ShaderChunk[ "default_vertex" ],
  10867. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10868. THREE.ShaderChunk[ "worldpos_vertex" ],
  10869. THREE.ShaderChunk[ "envmap_vertex" ],
  10870. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10871. "}"
  10872. ].join("\n"),
  10873. fragmentShader: [
  10874. "uniform vec3 diffuse;",
  10875. "uniform float opacity;",
  10876. THREE.ShaderChunk[ "common" ],
  10877. THREE.ShaderChunk[ "color_pars_fragment" ],
  10878. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10879. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10880. THREE.ShaderChunk[ "map_pars_fragment" ],
  10881. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10882. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  10883. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10884. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10885. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10886. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10887. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10888. "void main() {",
  10889. " vec3 outgoingLight = vec3( 0.0 );",
  10890. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10891. " vec3 totalAmbientLight = vec3( 1.0 );", // hardwired
  10892. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10893. THREE.ShaderChunk[ "map_fragment" ],
  10894. THREE.ShaderChunk[ "color_fragment" ],
  10895. THREE.ShaderChunk[ "alphamap_fragment" ],
  10896. THREE.ShaderChunk[ "alphatest_fragment" ],
  10897. THREE.ShaderChunk[ "specularmap_fragment" ],
  10898. THREE.ShaderChunk[ "aomap_fragment" ],
  10899. " outgoingLight = diffuseColor.rgb * totalAmbientLight;", // simple shader
  10900. THREE.ShaderChunk[ "envmap_fragment" ],
  10901. THREE.ShaderChunk[ "shadowmap_fragment" ], // TODO: Shadows on an otherwise unlit surface doesn't make sense.
  10902. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10903. THREE.ShaderChunk[ "fog_fragment" ],
  10904. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  10905. "}"
  10906. ].join("\n")
  10907. },
  10908. 'lambert': {
  10909. uniforms: THREE.UniformsUtils.merge( [
  10910. THREE.UniformsLib[ "common" ],
  10911. THREE.UniformsLib[ "fog" ],
  10912. THREE.UniformsLib[ "lights" ],
  10913. THREE.UniformsLib[ "shadowmap" ],
  10914. {
  10915. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }
  10916. }
  10917. ] ),
  10918. vertexShader: [
  10919. "#define LAMBERT",
  10920. "varying vec3 vLightFront;",
  10921. "#ifdef DOUBLE_SIDED",
  10922. " varying vec3 vLightBack;",
  10923. "#endif",
  10924. THREE.ShaderChunk[ "common" ],
  10925. THREE.ShaderChunk[ "uv_pars_vertex" ],
  10926. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  10927. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10928. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10929. THREE.ShaderChunk[ "color_pars_vertex" ],
  10930. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10931. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10932. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10933. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  10934. "void main() {",
  10935. THREE.ShaderChunk[ "uv_vertex" ],
  10936. THREE.ShaderChunk[ "uv2_vertex" ],
  10937. THREE.ShaderChunk[ "color_vertex" ],
  10938. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10939. THREE.ShaderChunk[ "skinbase_vertex" ],
  10940. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10941. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10942. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10943. THREE.ShaderChunk[ "skinning_vertex" ],
  10944. THREE.ShaderChunk[ "default_vertex" ],
  10945. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  10946. THREE.ShaderChunk[ "worldpos_vertex" ],
  10947. THREE.ShaderChunk[ "envmap_vertex" ],
  10948. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10949. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10950. "}"
  10951. ].join("\n"),
  10952. fragmentShader: [
  10953. "uniform vec3 diffuse;",
  10954. "uniform vec3 emissive;",
  10955. "uniform float opacity;",
  10956. "varying vec3 vLightFront;",
  10957. "#ifdef DOUBLE_SIDED",
  10958. " varying vec3 vLightBack;",
  10959. "#endif",
  10960. THREE.ShaderChunk[ "common" ],
  10961. THREE.ShaderChunk[ "color_pars_fragment" ],
  10962. THREE.ShaderChunk[ "uv_pars_fragment" ],
  10963. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  10964. THREE.ShaderChunk[ "map_pars_fragment" ],
  10965. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  10966. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10967. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10968. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10969. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10970. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  10971. "void main() {",
  10972. " vec3 outgoingLight = vec3( 0.0 );", // outgoing light does not have an alpha, the surface does
  10973. " vec4 diffuseColor = vec4( diffuse, opacity );",
  10974. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  10975. THREE.ShaderChunk[ "map_fragment" ],
  10976. THREE.ShaderChunk[ "color_fragment" ],
  10977. THREE.ShaderChunk[ "alphamap_fragment" ],
  10978. THREE.ShaderChunk[ "alphatest_fragment" ],
  10979. THREE.ShaderChunk[ "specularmap_fragment" ],
  10980. " #ifdef DOUBLE_SIDED",
  10981. " if ( gl_FrontFacing )",
  10982. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10983. " else",
  10984. " outgoingLight += diffuseColor.rgb * vLightBack + emissive;",
  10985. " #else",
  10986. " outgoingLight += diffuseColor.rgb * vLightFront + emissive;",
  10987. " #endif",
  10988. THREE.ShaderChunk[ "envmap_fragment" ],
  10989. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10990. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10991. THREE.ShaderChunk[ "fog_fragment" ],
  10992. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  10993. "}"
  10994. ].join("\n")
  10995. },
  10996. 'phong': {
  10997. uniforms: THREE.UniformsUtils.merge( [
  10998. THREE.UniformsLib[ "common" ],
  10999. THREE.UniformsLib[ "aomap" ],
  11000. THREE.UniformsLib[ "lightmap" ],
  11001. THREE.UniformsLib[ "emissivemap" ],
  11002. THREE.UniformsLib[ "bump" ],
  11003. THREE.UniformsLib[ "normalmap" ],
  11004. THREE.UniformsLib[ "fog" ],
  11005. THREE.UniformsLib[ "lights" ],
  11006. THREE.UniformsLib[ "shadowmap" ],
  11007. {
  11008. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11009. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11010. "shininess": { type: "f", value: 30 }
  11011. }
  11012. ] ),
  11013. vertexShader: [
  11014. "#define PHONG",
  11015. "varying vec3 vViewPosition;",
  11016. "#ifndef FLAT_SHADED",
  11017. " varying vec3 vNormal;",
  11018. "#endif",
  11019. THREE.ShaderChunk[ "common" ],
  11020. THREE.ShaderChunk[ "uv_pars_vertex" ],
  11021. THREE.ShaderChunk[ "uv2_pars_vertex" ],
  11022. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11023. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11024. THREE.ShaderChunk[ "color_pars_vertex" ],
  11025. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11026. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11027. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11028. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11029. "void main() {",
  11030. THREE.ShaderChunk[ "uv_vertex" ],
  11031. THREE.ShaderChunk[ "uv2_vertex" ],
  11032. THREE.ShaderChunk[ "color_vertex" ],
  11033. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11034. THREE.ShaderChunk[ "skinbase_vertex" ],
  11035. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11036. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11037. "#ifndef FLAT_SHADED", // Normal computed with derivatives when FLAT_SHADED
  11038. " vNormal = normalize( transformedNormal );",
  11039. "#endif",
  11040. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11041. THREE.ShaderChunk[ "skinning_vertex" ],
  11042. THREE.ShaderChunk[ "default_vertex" ],
  11043. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11044. " vViewPosition = - mvPosition.xyz;",
  11045. THREE.ShaderChunk[ "worldpos_vertex" ],
  11046. THREE.ShaderChunk[ "envmap_vertex" ],
  11047. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11048. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11049. "}"
  11050. ].join("\n"),
  11051. fragmentShader: [
  11052. "#define PHONG",
  11053. "uniform vec3 diffuse;",
  11054. "uniform vec3 emissive;",
  11055. "uniform vec3 specular;",
  11056. "uniform float shininess;",
  11057. "uniform float opacity;",
  11058. THREE.ShaderChunk[ "common" ],
  11059. THREE.ShaderChunk[ "color_pars_fragment" ],
  11060. THREE.ShaderChunk[ "uv_pars_fragment" ],
  11061. THREE.ShaderChunk[ "uv2_pars_fragment" ],
  11062. THREE.ShaderChunk[ "map_pars_fragment" ],
  11063. THREE.ShaderChunk[ "alphamap_pars_fragment" ],
  11064. THREE.ShaderChunk[ "aomap_pars_fragment" ],
  11065. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11066. THREE.ShaderChunk[ "emissivemap_pars_fragment" ],
  11067. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11068. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11069. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11070. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11071. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11072. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11073. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11074. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11075. "void main() {",
  11076. " vec3 outgoingLight = vec3( 0.0 );",
  11077. " vec4 diffuseColor = vec4( diffuse, opacity );",
  11078. " vec3 totalAmbientLight = ambientLightColor;",
  11079. " vec3 totalEmissiveLight = emissive;",
  11080. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11081. THREE.ShaderChunk[ "map_fragment" ],
  11082. THREE.ShaderChunk[ "color_fragment" ],
  11083. THREE.ShaderChunk[ "alphamap_fragment" ],
  11084. THREE.ShaderChunk[ "alphatest_fragment" ],
  11085. THREE.ShaderChunk[ "specularmap_fragment" ],
  11086. THREE.ShaderChunk[ "lightmap_fragment" ],
  11087. THREE.ShaderChunk[ "aomap_fragment" ],
  11088. THREE.ShaderChunk[ "emissivemap_fragment" ],
  11089. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11090. THREE.ShaderChunk[ "envmap_fragment" ],
  11091. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11092. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11093. THREE.ShaderChunk[ "fog_fragment" ],
  11094. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  11095. "}"
  11096. ].join("\n")
  11097. },
  11098. 'particle_basic': {
  11099. uniforms: THREE.UniformsUtils.merge( [
  11100. THREE.UniformsLib[ "particle" ],
  11101. THREE.UniformsLib[ "shadowmap" ]
  11102. ] ),
  11103. vertexShader: [
  11104. "uniform float size;",
  11105. "uniform float scale;",
  11106. THREE.ShaderChunk[ "common" ],
  11107. THREE.ShaderChunk[ "color_pars_vertex" ],
  11108. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11109. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11110. "void main() {",
  11111. THREE.ShaderChunk[ "color_vertex" ],
  11112. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11113. " #ifdef USE_SIZEATTENUATION",
  11114. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11115. " #else",
  11116. " gl_PointSize = size;",
  11117. " #endif",
  11118. " gl_Position = projectionMatrix * mvPosition;",
  11119. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11120. THREE.ShaderChunk[ "worldpos_vertex" ],
  11121. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11122. "}"
  11123. ].join("\n"),
  11124. fragmentShader: [
  11125. "uniform vec3 psColor;",
  11126. "uniform float opacity;",
  11127. THREE.ShaderChunk[ "common" ],
  11128. THREE.ShaderChunk[ "color_pars_fragment" ],
  11129. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11130. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11131. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11132. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11133. "void main() {",
  11134. " vec3 outgoingLight = vec3( 0.0 );",
  11135. " vec4 diffuseColor = vec4( psColor, opacity );",
  11136. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11137. THREE.ShaderChunk[ "map_particle_fragment" ],
  11138. THREE.ShaderChunk[ "color_fragment" ],
  11139. THREE.ShaderChunk[ "alphatest_fragment" ],
  11140. " outgoingLight = diffuseColor.rgb;", // simple shader
  11141. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11142. THREE.ShaderChunk[ "fog_fragment" ],
  11143. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  11144. "}"
  11145. ].join("\n")
  11146. },
  11147. 'dashed': {
  11148. uniforms: THREE.UniformsUtils.merge( [
  11149. THREE.UniformsLib[ "common" ],
  11150. THREE.UniformsLib[ "fog" ],
  11151. {
  11152. "scale" : { type: "f", value: 1 },
  11153. "dashSize" : { type: "f", value: 1 },
  11154. "totalSize": { type: "f", value: 2 }
  11155. }
  11156. ] ),
  11157. vertexShader: [
  11158. "uniform float scale;",
  11159. "attribute float lineDistance;",
  11160. "varying float vLineDistance;",
  11161. THREE.ShaderChunk[ "common" ],
  11162. THREE.ShaderChunk[ "color_pars_vertex" ],
  11163. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11164. "void main() {",
  11165. THREE.ShaderChunk[ "color_vertex" ],
  11166. " vLineDistance = scale * lineDistance;",
  11167. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11168. " gl_Position = projectionMatrix * mvPosition;",
  11169. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11170. "}"
  11171. ].join("\n"),
  11172. fragmentShader: [
  11173. "uniform vec3 diffuse;",
  11174. "uniform float opacity;",
  11175. "uniform float dashSize;",
  11176. "uniform float totalSize;",
  11177. "varying float vLineDistance;",
  11178. THREE.ShaderChunk[ "common" ],
  11179. THREE.ShaderChunk[ "color_pars_fragment" ],
  11180. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11181. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11182. "void main() {",
  11183. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11184. " discard;",
  11185. " }",
  11186. " vec3 outgoingLight = vec3( 0.0 );",
  11187. " vec4 diffuseColor = vec4( diffuse, opacity );",
  11188. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11189. THREE.ShaderChunk[ "color_fragment" ],
  11190. " outgoingLight = diffuseColor.rgb;", // simple shader
  11191. THREE.ShaderChunk[ "fog_fragment" ],
  11192. " gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
  11193. "}"
  11194. ].join("\n")
  11195. },
  11196. 'depth': {
  11197. uniforms: {
  11198. "mNear": { type: "f", value: 1.0 },
  11199. "mFar" : { type: "f", value: 2000.0 },
  11200. "opacity" : { type: "f", value: 1.0 }
  11201. },
  11202. vertexShader: [
  11203. THREE.ShaderChunk[ "common" ],
  11204. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11205. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11206. "void main() {",
  11207. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11208. THREE.ShaderChunk[ "default_vertex" ],
  11209. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11210. "}"
  11211. ].join("\n"),
  11212. fragmentShader: [
  11213. "uniform float mNear;",
  11214. "uniform float mFar;",
  11215. "uniform float opacity;",
  11216. THREE.ShaderChunk[ "common" ],
  11217. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11218. "void main() {",
  11219. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11220. " #ifdef USE_LOGDEPTHBUF_EXT",
  11221. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  11222. " #else",
  11223. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11224. " #endif",
  11225. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11226. " gl_FragColor = vec4( vec3( color ), opacity );",
  11227. "}"
  11228. ].join("\n")
  11229. },
  11230. 'normal': {
  11231. uniforms: {
  11232. "opacity" : { type: "f", value: 1.0 }
  11233. },
  11234. vertexShader: [
  11235. "varying vec3 vNormal;",
  11236. THREE.ShaderChunk[ "common" ],
  11237. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11238. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11239. "void main() {",
  11240. " vNormal = normalize( normalMatrix * normal );",
  11241. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11242. THREE.ShaderChunk[ "default_vertex" ],
  11243. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11244. "}"
  11245. ].join("\n"),
  11246. fragmentShader: [
  11247. "uniform float opacity;",
  11248. "varying vec3 vNormal;",
  11249. THREE.ShaderChunk[ "common" ],
  11250. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11251. "void main() {",
  11252. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11253. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11254. "}"
  11255. ].join("\n")
  11256. },
  11257. /* -------------------------------------------------------------------------
  11258. // Cube map shader
  11259. ------------------------------------------------------------------------- */
  11260. 'cube': {
  11261. uniforms: { "tCube": { type: "t", value: null },
  11262. "tFlip": { type: "f", value: - 1 } },
  11263. vertexShader: [
  11264. "varying vec3 vWorldPosition;",
  11265. THREE.ShaderChunk[ "common" ],
  11266. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11267. "void main() {",
  11268. " vWorldPosition = transformDirection( position, modelMatrix );",
  11269. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11270. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11271. "}"
  11272. ].join("\n"),
  11273. fragmentShader: [
  11274. "uniform samplerCube tCube;",
  11275. "uniform float tFlip;",
  11276. "varying vec3 vWorldPosition;",
  11277. THREE.ShaderChunk[ "common" ],
  11278. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11279. "void main() {",
  11280. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11281. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11282. "}"
  11283. ].join("\n")
  11284. },
  11285. /* -------------------------------------------------------------------------
  11286. // Cube map shader
  11287. ------------------------------------------------------------------------- */
  11288. 'equirect': {
  11289. uniforms: { "tEquirect": { type: "t", value: null },
  11290. "tFlip": { type: "f", value: - 1 } },
  11291. vertexShader: [
  11292. "varying vec3 vWorldPosition;",
  11293. THREE.ShaderChunk[ "common" ],
  11294. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11295. "void main() {",
  11296. " vWorldPosition = transformDirection( position, modelMatrix );",
  11297. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11298. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11299. "}"
  11300. ].join("\n"),
  11301. fragmentShader: [
  11302. "uniform sampler2D tEquirect;",
  11303. "uniform float tFlip;",
  11304. "varying vec3 vWorldPosition;",
  11305. THREE.ShaderChunk[ "common" ],
  11306. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11307. "void main() {",
  11308. // " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11309. "vec3 direction = normalize( vWorldPosition );",
  11310. "vec2 sampleUV;",
  11311. "sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );",
  11312. "sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;",
  11313. "gl_FragColor = texture2D( tEquirect, sampleUV );",
  11314. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11315. "}"
  11316. ].join("\n")
  11317. },
  11318. /* Depth encoding into RGBA texture
  11319. *
  11320. * based on SpiderGL shadow map example
  11321. * http://spidergl.org/example.php?id=6
  11322. *
  11323. * originally from
  11324. * http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11325. *
  11326. * see also
  11327. * http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11328. */
  11329. 'depthRGBA': {
  11330. uniforms: {},
  11331. vertexShader: [
  11332. THREE.ShaderChunk[ "common" ],
  11333. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11334. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11335. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11336. "void main() {",
  11337. THREE.ShaderChunk[ "skinbase_vertex" ],
  11338. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11339. THREE.ShaderChunk[ "skinning_vertex" ],
  11340. THREE.ShaderChunk[ "default_vertex" ],
  11341. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11342. "}"
  11343. ].join("\n"),
  11344. fragmentShader: [
  11345. THREE.ShaderChunk[ "common" ],
  11346. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11347. "vec4 pack_depth( const in float depth ) {",
  11348. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11349. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11350. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  11351. " res -= res.xxyz * bit_mask;",
  11352. " return res;",
  11353. "}",
  11354. "void main() {",
  11355. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11356. " #ifdef USE_LOGDEPTHBUF_EXT",
  11357. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  11358. " #else",
  11359. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11360. " #endif",
  11361. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11362. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11363. //"gl_FragData[ 0 ] = pack_depth( z );",
  11364. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11365. "}"
  11366. ].join("\n")
  11367. }
  11368. };
  11369. // File:src/renderers/WebGLRenderer.js
  11370. /**
  11371. * @author supereggbert / http://www.paulbrunt.co.uk/
  11372. * @author mrdoob / http://mrdoob.com/
  11373. * @author alteredq / http://alteredqualia.com/
  11374. * @author szimek / https://github.com/szimek/
  11375. */
  11376. THREE.WebGLRenderer = function ( parameters ) {
  11377. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11378. parameters = parameters || {};
  11379. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11380. _context = parameters.context !== undefined ? parameters.context : null,
  11381. _width = _canvas.width,
  11382. _height = _canvas.height,
  11383. pixelRatio = 1,
  11384. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11385. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11386. _depth = parameters.depth !== undefined ? parameters.depth : true,
  11387. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11388. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11389. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11390. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11391. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  11392. _clearColor = new THREE.Color( 0x000000 ),
  11393. _clearAlpha = 0;
  11394. var lights = [];
  11395. var opaqueObjects = [];
  11396. var transparentObjects = [];
  11397. var sprites = [];
  11398. var lensFlares = [];
  11399. // public properties
  11400. this.domElement = _canvas;
  11401. this.context = null;
  11402. // clearing
  11403. this.autoClear = true;
  11404. this.autoClearColor = true;
  11405. this.autoClearDepth = true;
  11406. this.autoClearStencil = true;
  11407. // scene graph
  11408. this.sortObjects = true;
  11409. // physically based shading
  11410. this.gammaFactor = 2.0; // for backwards compatibility
  11411. this.gammaInput = false;
  11412. this.gammaOutput = false;
  11413. // morphs
  11414. this.maxMorphTargets = 8;
  11415. this.maxMorphNormals = 4;
  11416. // flags
  11417. this.autoScaleCubemaps = true;
  11418. // info
  11419. this.info = {
  11420. memory: {
  11421. programs: 0,
  11422. geometries: 0,
  11423. textures: 0
  11424. },
  11425. render: {
  11426. calls: 0,
  11427. vertices: 0,
  11428. faces: 0,
  11429. points: 0
  11430. }
  11431. };
  11432. // internal properties
  11433. var _this = this,
  11434. _programs = [],
  11435. // internal state cache
  11436. _currentProgram = null,
  11437. _currentFramebuffer = null,
  11438. _currentMaterialId = - 1,
  11439. _currentGeometryProgram = '',
  11440. _currentCamera = null,
  11441. _usedTextureUnits = 0,
  11442. _viewportX = 0,
  11443. _viewportY = 0,
  11444. _viewportWidth = _canvas.width,
  11445. _viewportHeight = _canvas.height,
  11446. _currentWidth = 0,
  11447. _currentHeight = 0,
  11448. // frustum
  11449. _frustum = new THREE.Frustum(),
  11450. // camera matrices cache
  11451. _projScreenMatrix = new THREE.Matrix4(),
  11452. _vector3 = new THREE.Vector3(),
  11453. // light arrays cache
  11454. _direction = new THREE.Vector3(),
  11455. _lightsNeedUpdate = true,
  11456. _lights = {
  11457. ambient: [ 0, 0, 0 ],
  11458. directional: { length: 0, colors:[], positions: [] },
  11459. point: { length: 0, colors: [], positions: [], distances: [], decays: [] },
  11460. spot: { length: 0, colors: [], positions: [], distances: [], directions: [], anglesCos: [], exponents: [], decays: [] },
  11461. hemi: { length: 0, skyColors: [], groundColors: [], positions: [] }
  11462. };
  11463. // initialize
  11464. var _gl;
  11465. try {
  11466. var attributes = {
  11467. alpha: _alpha,
  11468. depth: _depth,
  11469. stencil: _stencil,
  11470. antialias: _antialias,
  11471. premultipliedAlpha: _premultipliedAlpha,
  11472. preserveDrawingBuffer: _preserveDrawingBuffer
  11473. };
  11474. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  11475. if ( _gl === null ) {
  11476. if ( _canvas.getContext( 'webgl') !== null ) {
  11477. throw 'Error creating WebGL context with your selected attributes.';
  11478. } else {
  11479. throw 'Error creating WebGL context.';
  11480. }
  11481. }
  11482. _canvas.addEventListener( 'webglcontextlost', function ( event ) {
  11483. event.preventDefault();
  11484. resetGLState();
  11485. setDefaultGLState();
  11486. objects.objects = {};
  11487. }, false);
  11488. } catch ( error ) {
  11489. console.error( 'THREE.WebGLRenderer: ' + error );
  11490. }
  11491. var state = new THREE.WebGLState( _gl, paramThreeToGL );
  11492. if ( _gl.getShaderPrecisionFormat === undefined ) {
  11493. _gl.getShaderPrecisionFormat = function () {
  11494. return {
  11495. 'rangeMin': 1,
  11496. 'rangeMax': 1,
  11497. 'precision': 1
  11498. };
  11499. }
  11500. }
  11501. var extensions = new THREE.WebGLExtensions( _gl );
  11502. var objects = new THREE.WebGLObjects( _gl, this.info );
  11503. extensions.get( 'OES_texture_float' );
  11504. extensions.get( 'OES_texture_float_linear' );
  11505. extensions.get( 'OES_texture_half_float' );
  11506. extensions.get( 'OES_texture_half_float_linear' );
  11507. extensions.get( 'OES_standard_derivatives' );
  11508. extensions.get( 'ANGLE_instanced_arrays' );
  11509. if ( extensions.get( 'OES_element_index_uint' ) ) {
  11510. THREE.BufferGeometry.MaxIndex = 4294967296;
  11511. }
  11512. if ( _logarithmicDepthBuffer ) {
  11513. extensions.get( 'EXT_frag_depth' );
  11514. }
  11515. //
  11516. var glClearColor = function ( r, g, b, a ) {
  11517. if ( _premultipliedAlpha === true ) {
  11518. r *= a; g *= a; b *= a;
  11519. }
  11520. _gl.clearColor( r, g, b, a );
  11521. };
  11522. var setDefaultGLState = function () {
  11523. state.init();
  11524. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11525. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11526. };
  11527. var resetGLState = function () {
  11528. _currentProgram = null;
  11529. _currentCamera = null;
  11530. _currentGeometryProgram = '';
  11531. _currentMaterialId = - 1;
  11532. _lightsNeedUpdate = true;
  11533. state.reset();
  11534. };
  11535. setDefaultGLState();
  11536. this.context = _gl;
  11537. this.extensions = extensions;
  11538. this.state = state;
  11539. // shadow map
  11540. var shadowMap = new THREE.WebGLShadowMap( this, lights, objects );
  11541. this.shadowMap = shadowMap;
  11542. // GPU capabilities
  11543. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11544. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11545. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11546. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11547. var _supportsVertexTextures = _maxVertexTextures > 0;
  11548. var _supportsBoneTextures = _supportsVertexTextures && extensions.get( 'OES_texture_float' );
  11549. var _supportsInstancedArrays = extensions.get( 'ANGLE_instanced_arrays' );
  11550. //
  11551. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11552. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11553. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11554. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11555. var getCompressedTextureFormats = ( function () {
  11556. var array;
  11557. return function () {
  11558. if ( array !== undefined ) {
  11559. return array;
  11560. }
  11561. array = [];
  11562. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) || extensions.get( 'WEBGL_compressed_texture_s3tc' ) ) {
  11563. var formats = _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS );
  11564. for ( var i = 0; i < formats.length; i ++ ) {
  11565. array.push( formats[ i ] );
  11566. }
  11567. }
  11568. return array;
  11569. };
  11570. } )();
  11571. // clamp precision to maximum available
  11572. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11573. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11574. if ( _precision === 'highp' && ! highpAvailable ) {
  11575. if ( mediumpAvailable ) {
  11576. _precision = 'mediump';
  11577. console.warn( 'THREE.WebGLRenderer: highp not supported, using mediump.' );
  11578. } else {
  11579. _precision = 'lowp';
  11580. console.warn( 'THREE.WebGLRenderer: highp and mediump not supported, using lowp.' );
  11581. }
  11582. }
  11583. if ( _precision === 'mediump' && ! mediumpAvailable ) {
  11584. _precision = 'lowp';
  11585. console.warn( 'THREE.WebGLRenderer: mediump not supported, using lowp.' );
  11586. }
  11587. // Plugins
  11588. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  11589. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  11590. // API
  11591. this.getContext = function () {
  11592. return _gl;
  11593. };
  11594. this.forceContextLoss = function () {
  11595. extensions.get( 'WEBGL_lose_context' ).loseContext();
  11596. };
  11597. this.supportsVertexTextures = function () {
  11598. return _supportsVertexTextures;
  11599. };
  11600. this.supportsInstancedArrays = function () {
  11601. return _supportsInstancedArrays;
  11602. };
  11603. this.supportsFloatTextures = function () {
  11604. return extensions.get( 'OES_texture_float' );
  11605. };
  11606. this.supportsHalfFloatTextures = function () {
  11607. return extensions.get( 'OES_texture_half_float' );
  11608. };
  11609. this.supportsStandardDerivatives = function () {
  11610. return extensions.get( 'OES_standard_derivatives' );
  11611. };
  11612. this.supportsCompressedTextureS3TC = function () {
  11613. return extensions.get( 'WEBGL_compressed_texture_s3tc' );
  11614. };
  11615. this.supportsCompressedTexturePVRTC = function () {
  11616. return extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  11617. };
  11618. this.supportsBlendMinMax = function () {
  11619. return extensions.get( 'EXT_blend_minmax' );
  11620. };
  11621. this.getMaxAnisotropy = ( function () {
  11622. var value;
  11623. return function () {
  11624. if ( value !== undefined ) return value;
  11625. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  11626. if ( extension !== null ) {
  11627. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  11628. } else {
  11629. value = 0;
  11630. }
  11631. return value;
  11632. }
  11633. } )();
  11634. this.getPrecision = function () {
  11635. return _precision;
  11636. };
  11637. this.getPixelRatio = function () {
  11638. return pixelRatio;
  11639. };
  11640. this.setPixelRatio = function ( value ) {
  11641. if ( value !== undefined ) pixelRatio = value;
  11642. };
  11643. this.getSize = function () {
  11644. return {
  11645. width: _width,
  11646. height: _height
  11647. };
  11648. };
  11649. this.setSize = function ( width, height, updateStyle ) {
  11650. _width = width;
  11651. _height = height;
  11652. _canvas.width = width * pixelRatio;
  11653. _canvas.height = height * pixelRatio;
  11654. if ( updateStyle !== false ) {
  11655. _canvas.style.width = width + 'px';
  11656. _canvas.style.height = height + 'px';
  11657. }
  11658. this.setViewport( 0, 0, width, height );
  11659. };
  11660. this.setViewport = function ( x, y, width, height ) {
  11661. _viewportX = x * pixelRatio;
  11662. _viewportY = y * pixelRatio;
  11663. _viewportWidth = width * pixelRatio;
  11664. _viewportHeight = height * pixelRatio;
  11665. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11666. };
  11667. this.setScissor = function ( x, y, width, height ) {
  11668. _gl.scissor(
  11669. x * pixelRatio,
  11670. y * pixelRatio,
  11671. width * pixelRatio,
  11672. height * pixelRatio
  11673. );
  11674. };
  11675. this.enableScissorTest = function ( enable ) {
  11676. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11677. };
  11678. // Clearing
  11679. this.getClearColor = function () {
  11680. return _clearColor;
  11681. };
  11682. this.setClearColor = function ( color, alpha ) {
  11683. _clearColor.set( color );
  11684. _clearAlpha = alpha !== undefined ? alpha : 1;
  11685. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11686. };
  11687. this.getClearAlpha = function () {
  11688. return _clearAlpha;
  11689. };
  11690. this.setClearAlpha = function ( alpha ) {
  11691. _clearAlpha = alpha;
  11692. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11693. };
  11694. this.clear = function ( color, depth, stencil ) {
  11695. var bits = 0;
  11696. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11697. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11698. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11699. _gl.clear( bits );
  11700. };
  11701. this.clearColor = function () {
  11702. _gl.clear( _gl.COLOR_BUFFER_BIT );
  11703. };
  11704. this.clearDepth = function () {
  11705. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  11706. };
  11707. this.clearStencil = function () {
  11708. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  11709. };
  11710. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11711. this.setRenderTarget( renderTarget );
  11712. this.clear( color, depth, stencil );
  11713. };
  11714. // Reset
  11715. this.resetGLState = resetGLState;
  11716. // Events
  11717. var onTextureDispose = function ( event ) {
  11718. var texture = event.target;
  11719. texture.removeEventListener( 'dispose', onTextureDispose );
  11720. deallocateTexture( texture );
  11721. _this.info.memory.textures --;
  11722. };
  11723. var onRenderTargetDispose = function ( event ) {
  11724. var renderTarget = event.target;
  11725. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11726. deallocateRenderTarget( renderTarget );
  11727. _this.info.memory.textures --;
  11728. };
  11729. var onMaterialDispose = function ( event ) {
  11730. var material = event.target;
  11731. material.removeEventListener( 'dispose', onMaterialDispose );
  11732. deallocateMaterial( material );
  11733. };
  11734. // Buffer deallocation
  11735. var deallocateTexture = function ( texture ) {
  11736. if ( texture.image && texture.image.__webglTextureCube ) {
  11737. // cube texture
  11738. _gl.deleteTexture( texture.image.__webglTextureCube );
  11739. delete texture.image.__webglTextureCube;
  11740. } else {
  11741. // 2D texture
  11742. if ( texture.__webglInit === undefined ) return;
  11743. _gl.deleteTexture( texture.__webglTexture );
  11744. delete texture.__webglTexture;
  11745. delete texture.__webglInit;
  11746. }
  11747. };
  11748. var deallocateRenderTarget = function ( renderTarget ) {
  11749. if ( ! renderTarget || renderTarget.__webglTexture === undefined ) return;
  11750. _gl.deleteTexture( renderTarget.__webglTexture );
  11751. delete renderTarget.__webglTexture;
  11752. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11753. for ( var i = 0; i < 6; i ++ ) {
  11754. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11755. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11756. }
  11757. } else {
  11758. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11759. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11760. }
  11761. delete renderTarget.__webglFramebuffer;
  11762. delete renderTarget.__webglRenderbuffer;
  11763. };
  11764. var deallocateMaterial = function ( material ) {
  11765. var program = material.program.program;
  11766. if ( program === undefined ) return;
  11767. material.program = undefined;
  11768. // only deallocate GL program if this was the last use of shared program
  11769. // assumed there is only single copy of any program in the _programs list
  11770. // (that's how it's constructed)
  11771. var i, il, programInfo;
  11772. var deleteProgram = false;
  11773. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11774. programInfo = _programs[ i ];
  11775. if ( programInfo.program === program ) {
  11776. programInfo.usedTimes --;
  11777. if ( programInfo.usedTimes === 0 ) {
  11778. deleteProgram = true;
  11779. }
  11780. break;
  11781. }
  11782. }
  11783. if ( deleteProgram === true ) {
  11784. // avoid using array.splice, this is costlier than creating new array from scratch
  11785. var newPrograms = [];
  11786. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11787. programInfo = _programs[ i ];
  11788. if ( programInfo.program !== program ) {
  11789. newPrograms.push( programInfo );
  11790. }
  11791. }
  11792. _programs = newPrograms;
  11793. _gl.deleteProgram( program );
  11794. _this.info.memory.programs --;
  11795. }
  11796. };
  11797. // Buffer rendering
  11798. this.renderBufferImmediate = function ( object, program, material ) {
  11799. state.initAttributes();
  11800. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11801. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11802. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11803. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11804. var attributes = program.getAttributes();
  11805. if ( object.hasPositions ) {
  11806. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11807. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11808. state.enableAttribute( attributes.position );
  11809. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11810. }
  11811. if ( object.hasNormals ) {
  11812. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11813. if ( material instanceof THREE.MeshPhongMaterial === false && material.shading === THREE.FlatShading ) {
  11814. var nx, ny, nz,
  11815. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11816. normalArray,
  11817. i, il = object.count * 3;
  11818. for ( i = 0; i < il; i += 9 ) {
  11819. normalArray = object.normalArray;
  11820. nax = normalArray[ i ];
  11821. nay = normalArray[ i + 1 ];
  11822. naz = normalArray[ i + 2 ];
  11823. nbx = normalArray[ i + 3 ];
  11824. nby = normalArray[ i + 4 ];
  11825. nbz = normalArray[ i + 5 ];
  11826. ncx = normalArray[ i + 6 ];
  11827. ncy = normalArray[ i + 7 ];
  11828. ncz = normalArray[ i + 8 ];
  11829. nx = ( nax + nbx + ncx ) / 3;
  11830. ny = ( nay + nby + ncy ) / 3;
  11831. nz = ( naz + nbz + ncz ) / 3;
  11832. normalArray[ i ] = nx;
  11833. normalArray[ i + 1 ] = ny;
  11834. normalArray[ i + 2 ] = nz;
  11835. normalArray[ i + 3 ] = nx;
  11836. normalArray[ i + 4 ] = ny;
  11837. normalArray[ i + 5 ] = nz;
  11838. normalArray[ i + 6 ] = nx;
  11839. normalArray[ i + 7 ] = ny;
  11840. normalArray[ i + 8 ] = nz;
  11841. }
  11842. }
  11843. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11844. state.enableAttribute( attributes.normal );
  11845. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11846. }
  11847. if ( object.hasUvs && material.map ) {
  11848. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11849. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11850. state.enableAttribute( attributes.uv );
  11851. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11852. }
  11853. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11854. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11855. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11856. state.enableAttribute( attributes.color );
  11857. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11858. }
  11859. state.disableUnusedAttributes();
  11860. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11861. object.count = 0;
  11862. };
  11863. function setupVertexAttributes( material, program, geometry, startIndex ) {
  11864. var extension;
  11865. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  11866. extension = extensions.get( 'ANGLE_instanced_arrays' );
  11867. if ( extension === null ) {
  11868. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11869. return;
  11870. }
  11871. }
  11872. var geometryAttributes = geometry.attributes;
  11873. var programAttributes = program.getAttributes();
  11874. var materialDefaultAttributeValues = material.defaultAttributeValues;
  11875. for ( var name in programAttributes ) {
  11876. var programAttribute = programAttributes[ name ];
  11877. if ( programAttribute >= 0 ) {
  11878. var geometryAttribute = geometryAttributes[ name ];
  11879. if ( geometryAttribute !== undefined ) {
  11880. var size = geometryAttribute.itemSize;
  11881. state.enableAttribute( programAttribute );
  11882. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  11883. var data = geometryAttribute.data;
  11884. var stride = data.stride;
  11885. var offset = geometryAttribute.offset;
  11886. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.data.buffer );
  11887. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  11888. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  11889. if ( extension === null ) {
  11890. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferAttribute but hardware does not support extension ANGLE_instanced_arrays.' );
  11891. return;
  11892. }
  11893. extension.vertexAttribDivisorANGLE( programAttribute, data.meshPerAttribute );
  11894. if ( geometry.maxInstancedCount === undefined ) {
  11895. geometry.maxInstancedCount = data.meshPerAttribute * ( data.array.length / data.stride );
  11896. }
  11897. }
  11898. } else {
  11899. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryAttribute.buffer );
  11900. _gl.vertexAttribPointer( programAttribute, size, _gl.FLOAT, false, 0, startIndex * size * 4 ); // 4 bytes per Float32
  11901. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  11902. if ( extension === null ) {
  11903. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferAttribute but hardware does not support extension ANGLE_instanced_arrays.' );
  11904. return;
  11905. }
  11906. extension.vertexAttribDivisorANGLE( programAttribute, geometryAttribute.meshPerAttribute );
  11907. if ( geometry.maxInstancedCount === undefined ) {
  11908. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * ( geometryAttribute.array.length / geometryAttribute.itemSize );
  11909. }
  11910. }
  11911. }
  11912. } else if ( materialDefaultAttributeValues !== undefined ) {
  11913. var value = materialDefaultAttributeValues[ name ];
  11914. if ( value !== undefined ) {
  11915. switch ( value.length ) {
  11916. case 2:
  11917. _gl.vertexAttrib2fv( programAttribute, value );
  11918. break;
  11919. case 3:
  11920. _gl.vertexAttrib3fv( programAttribute, value );
  11921. break;
  11922. case 4:
  11923. _gl.vertexAttrib4fv( programAttribute, value );
  11924. break;
  11925. default:
  11926. _gl.vertexAttrib1fv( programAttribute, value );
  11927. }
  11928. }
  11929. }
  11930. }
  11931. }
  11932. state.disableUnusedAttributes();
  11933. }
  11934. this.renderBufferDirect = function ( camera, lights, fog, material, object ) {
  11935. if ( material.visible === false ) return;
  11936. setMaterial( material );
  11937. var geometry = objects.geometries.get( object );
  11938. var program = setProgram( camera, lights, fog, material, object );
  11939. var updateBuffers = false,
  11940. wireframeBit = material.wireframe ? 1 : 0,
  11941. geometryProgram = geometry.id + '_' + program.id + '_' + wireframeBit;
  11942. if ( geometryProgram !== _currentGeometryProgram ) {
  11943. _currentGeometryProgram = geometryProgram;
  11944. updateBuffers = true;
  11945. }
  11946. if ( updateBuffers ) {
  11947. state.initAttributes();
  11948. }
  11949. if ( object instanceof THREE.Mesh ) {
  11950. renderMesh( material, geometry, object, program, updateBuffers );
  11951. } else if ( object instanceof THREE.Line ) {
  11952. renderLine( material, geometry, object, program, updateBuffers );
  11953. } else if ( object instanceof THREE.PointCloud ) {
  11954. renderPointCloud( material, geometry, object, program, updateBuffers );
  11955. }
  11956. };
  11957. function renderMesh( material, geometry, object, program, updateBuffers ) {
  11958. var mode = material.wireframe === true ? _gl.LINES : _gl.TRIANGLES;
  11959. var index = geometry.attributes.index;
  11960. if ( index ) {
  11961. // indexed triangles
  11962. var type, size;
  11963. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  11964. type = _gl.UNSIGNED_INT;
  11965. size = 4;
  11966. } else {
  11967. type = _gl.UNSIGNED_SHORT;
  11968. size = 2;
  11969. }
  11970. var offsets = geometry.offsets;
  11971. if ( offsets.length === 0 ) {
  11972. if ( updateBuffers ) {
  11973. setupVertexAttributes( material, program, geometry, 0 );
  11974. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11975. }
  11976. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  11977. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  11978. if ( extension === null ) {
  11979. console.error( 'THREE.WebGLRenderer.renderMesh: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  11980. return;
  11981. }
  11982. extension.drawElementsInstancedANGLE( mode, index.array.length, type, 0, geometry.maxInstancedCount ); // Draw the instanced meshes
  11983. } else {
  11984. _gl.drawElements( mode, index.array.length, type, 0 );
  11985. }
  11986. _this.info.render.calls ++;
  11987. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  11988. _this.info.render.faces += index.array.length / 3;
  11989. } else {
  11990. // if there is more than 1 chunk
  11991. // must set attribute pointers to use new offsets for each chunk
  11992. // even if geometry and materials didn't change
  11993. updateBuffers = true;
  11994. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11995. var startIndex = offsets[ i ].index;
  11996. if ( updateBuffers ) {
  11997. setupVertexAttributes( material, program, geometry, startIndex );
  11998. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11999. }
  12000. // render indexed triangles
  12001. if ( geometry instanceof THREE.InstancedBufferGeometry && offsets[i].instances > 0 ) {
  12002. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  12003. if ( extension === null ) {
  12004. console.error( 'THREE.WebGLRenderer.renderMesh: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12005. return;
  12006. }
  12007. extension.drawElementsInstancedANGLE( mode, offsets[i].count, type, offsets[i].start * size, offsets[i].count, type, offsets[i].instances ); // Draw the instanced meshes
  12008. } else {
  12009. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  12010. }
  12011. _this.info.render.calls ++;
  12012. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12013. _this.info.render.faces += offsets[ i ].count / 3;
  12014. }
  12015. }
  12016. } else {
  12017. // non-indexed triangles
  12018. var offsets = geometry.offsets;
  12019. if ( offsets.length === 0 ) {
  12020. if ( updateBuffers ) {
  12021. setupVertexAttributes( material, program, geometry, 0 );
  12022. }
  12023. var position = geometry.attributes.position;
  12024. // render non-indexed triangles
  12025. if ( geometry instanceof THREE.InstancedBufferGeometry && geometry.maxInstancedCount > 0 ) {
  12026. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  12027. if ( extension === null ) {
  12028. console.error( 'THREE.WebGLRenderer.renderMesh: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  12029. return;
  12030. }
  12031. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  12032. extension.drawArraysInstancedANGLE( mode, 0, position.data.array.length / position.data.stride, geometry.maxInstancedCount ); // Draw the instanced meshes
  12033. } else {
  12034. extension.drawArraysInstancedANGLE( mode, 0, position.array.length / position.itemSize, geometry.maxInstancedCount ); // Draw the instanced meshes
  12035. }
  12036. } else {
  12037. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  12038. _gl.drawArrays( mode, 0, position.data.array.length / position.data.stride );
  12039. } else {
  12040. _gl.drawArrays( mode, 0, position.array.length / position.itemSize );
  12041. }
  12042. }
  12043. _this.info.render.calls++;
  12044. _this.info.render.vertices += position.array.length / position.itemSize;
  12045. _this.info.render.faces += position.array.length / ( 3 * position.itemSize );
  12046. } else {
  12047. // if there is more than 1 chunk
  12048. // must set attribute pointers to use new offsets for each chunk
  12049. // even if geometry and materials didn't change
  12050. if ( updateBuffers ) {
  12051. setupVertexAttributes( material, program, geometry, 0 );
  12052. }
  12053. for ( var i = 0, il = offsets.length; i < il; i++ ) {
  12054. // render non-indexed triangles
  12055. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  12056. console.error( 'THREE.WebGLRenderer.renderMesh: cannot use drawCalls with THREE.InstancedBufferGeometry.' );
  12057. return;
  12058. } else {
  12059. _gl.drawArrays( mode, offsets[ i ].start, offsets[ i ].count );
  12060. }
  12061. _this.info.render.calls++;
  12062. _this.info.render.vertices += offsets[ i ].count;
  12063. _this.info.render.faces += ( offsets[ i ].count ) / 3;
  12064. }
  12065. }
  12066. }
  12067. }
  12068. function renderLine( material, geometry, object, program, updateBuffers ) {
  12069. var mode = object instanceof THREE.LineSegments ? _gl.LINES : _gl.LINE_STRIP;
  12070. // In case user is not using Line*Material by mistake
  12071. var lineWidth = material.linewidth !== undefined ? material.linewidth : 1;
  12072. state.setLineWidth( lineWidth * pixelRatio );
  12073. var index = geometry.attributes.index;
  12074. if ( index ) {
  12075. // indexed lines
  12076. var type, size;
  12077. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  12078. type = _gl.UNSIGNED_INT;
  12079. size = 4;
  12080. } else {
  12081. type = _gl.UNSIGNED_SHORT;
  12082. size = 2;
  12083. }
  12084. var offsets = geometry.offsets;
  12085. if ( offsets.length === 0 ) {
  12086. if ( updateBuffers ) {
  12087. setupVertexAttributes( material, program, geometry, 0 );
  12088. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12089. }
  12090. _gl.drawElements( mode, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  12091. _this.info.render.calls ++;
  12092. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  12093. } else {
  12094. // if there is more than 1 chunk
  12095. // must set attribute pointers to use new offsets for each chunk
  12096. // even if geometry and materials didn't change
  12097. if ( offsets.length > 1 ) updateBuffers = true;
  12098. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12099. var startIndex = offsets[ i ].index;
  12100. if ( updateBuffers ) {
  12101. setupVertexAttributes( material, program, geometry, startIndex );
  12102. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12103. }
  12104. // render indexed lines
  12105. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  12106. _this.info.render.calls ++;
  12107. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12108. }
  12109. }
  12110. } else {
  12111. // non-indexed lines
  12112. if ( updateBuffers ) {
  12113. setupVertexAttributes( material, program, geometry, 0 );
  12114. }
  12115. var position = geometry.attributes.position;
  12116. var offsets = geometry.offsets;
  12117. if ( offsets.length === 0 ) {
  12118. _gl.drawArrays( mode, 0, position.array.length / 3 );
  12119. _this.info.render.calls ++;
  12120. _this.info.render.vertices += position.array.length / 3;
  12121. } else {
  12122. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12123. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  12124. _this.info.render.calls ++;
  12125. _this.info.render.vertices += offsets[ i ].count;
  12126. }
  12127. }
  12128. }
  12129. }
  12130. function renderPointCloud( material, geometry, object, program, updateBuffers ) {
  12131. var mode = _gl.POINTS;
  12132. var index = geometry.attributes.index;
  12133. if ( index ) {
  12134. // indexed points
  12135. var type, size;
  12136. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  12137. type = _gl.UNSIGNED_INT;
  12138. size = 4;
  12139. } else {
  12140. type = _gl.UNSIGNED_SHORT;
  12141. size = 2;
  12142. }
  12143. var offsets = geometry.offsets;
  12144. if ( offsets.length === 0 ) {
  12145. if ( updateBuffers ) {
  12146. setupVertexAttributes( material, program, geometry, 0 );
  12147. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12148. }
  12149. _gl.drawElements( mode, index.array.length, type, 0);
  12150. _this.info.render.calls ++;
  12151. _this.info.render.points += index.array.length;
  12152. } else {
  12153. // if there is more than 1 chunk
  12154. // must set attribute pointers to use new offsets for each chunk
  12155. // even if geometry and materials didn't change
  12156. if ( offsets.length > 1 ) updateBuffers = true;
  12157. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12158. var startIndex = offsets[ i ].index;
  12159. if ( updateBuffers ) {
  12160. setupVertexAttributes( material, program, geometry, startIndex );
  12161. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12162. }
  12163. // render indexed points
  12164. _gl.drawElements( mode, offsets[ i ].count, type, offsets[ i ].start * size );
  12165. _this.info.render.calls ++;
  12166. _this.info.render.points += offsets[ i ].count;
  12167. }
  12168. }
  12169. } else {
  12170. // non-indexed points
  12171. if ( updateBuffers ) {
  12172. setupVertexAttributes( material, program, geometry, 0 );
  12173. }
  12174. var position = geometry.attributes.position;
  12175. var offsets = geometry.offsets;
  12176. if ( offsets.length === 0 ) {
  12177. _gl.drawArrays( mode, 0, position.array.length / 3 );
  12178. _this.info.render.calls ++;
  12179. _this.info.render.points += position.array.length / 3;
  12180. } else {
  12181. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12182. _gl.drawArrays( mode, offsets[ i ].index, offsets[ i ].count );
  12183. _this.info.render.calls ++;
  12184. _this.info.render.points += offsets[ i ].count;
  12185. }
  12186. }
  12187. }
  12188. }
  12189. // Sorting
  12190. function painterSortStable ( a, b ) {
  12191. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12192. return a.object.renderOrder - b.object.renderOrder;
  12193. } else if ( a.object.material.id !== b.object.material.id ) {
  12194. return a.object.material.id - b.object.material.id;
  12195. } else if ( a.z !== b.z ) {
  12196. return a.z - b.z;
  12197. } else {
  12198. return a.id - b.id;
  12199. }
  12200. }
  12201. function reversePainterSortStable ( a, b ) {
  12202. if ( a.object.renderOrder !== b.object.renderOrder ) {
  12203. return a.object.renderOrder - b.object.renderOrder;
  12204. } if ( a.z !== b.z ) {
  12205. return b.z - a.z;
  12206. } else {
  12207. return a.id - b.id;
  12208. }
  12209. }
  12210. // Rendering
  12211. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12212. if ( camera instanceof THREE.Camera === false ) {
  12213. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12214. return;
  12215. }
  12216. var fog = scene.fog;
  12217. // reset caching for this frame
  12218. _currentGeometryProgram = '';
  12219. _currentMaterialId = - 1;
  12220. _currentCamera = null;
  12221. _lightsNeedUpdate = true;
  12222. // update scene graph
  12223. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  12224. // update camera matrices and frustum
  12225. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12226. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12227. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12228. _frustum.setFromMatrix( _projScreenMatrix );
  12229. lights.length = 0;
  12230. opaqueObjects.length = 0;
  12231. transparentObjects.length = 0;
  12232. sprites.length = 0;
  12233. lensFlares.length = 0;
  12234. projectObject( scene );
  12235. if ( _this.sortObjects === true ) {
  12236. opaqueObjects.sort( painterSortStable );
  12237. transparentObjects.sort( reversePainterSortStable );
  12238. }
  12239. objects.update( opaqueObjects );
  12240. objects.update( transparentObjects );
  12241. //
  12242. shadowMap.render( scene, camera );
  12243. //
  12244. _this.info.render.calls = 0;
  12245. _this.info.render.vertices = 0;
  12246. _this.info.render.faces = 0;
  12247. _this.info.render.points = 0;
  12248. this.setRenderTarget( renderTarget );
  12249. if ( this.autoClear || forceClear ) {
  12250. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12251. }
  12252. // set matrices for immediate objects
  12253. for ( var i = 0, il = objects.objectsImmediate.length; i < il; i ++ ) {
  12254. var webglObject = objects.objectsImmediate[ i ];
  12255. var object = webglObject.object;
  12256. if ( object.visible === true ) {
  12257. setupMatrices( object, camera );
  12258. var material = object.material;
  12259. if ( material.transparent ) {
  12260. webglObject.transparent = material;
  12261. webglObject.opaque = null;
  12262. } else {
  12263. webglObject.opaque = material;
  12264. webglObject.transparent = null;
  12265. }
  12266. }
  12267. }
  12268. if ( scene.overrideMaterial ) {
  12269. var overrideMaterial = scene.overrideMaterial;
  12270. renderObjects( opaqueObjects, camera, lights, fog, overrideMaterial );
  12271. renderObjects( transparentObjects, camera, lights, fog, overrideMaterial );
  12272. renderObjectsImmediate( objects.objectsImmediate, '', camera, lights, fog, overrideMaterial );
  12273. } else {
  12274. // opaque pass (front-to-back order)
  12275. state.setBlending( THREE.NoBlending );
  12276. renderObjects( opaqueObjects, camera, lights, fog, null );
  12277. renderObjectsImmediate( objects.objectsImmediate, 'opaque', camera, lights, fog, null );
  12278. // transparent pass (back-to-front order)
  12279. renderObjects( transparentObjects, camera, lights, fog, null );
  12280. renderObjectsImmediate( objects.objectsImmediate, 'transparent', camera, lights, fog, null );
  12281. }
  12282. // custom render plugins (post pass)
  12283. spritePlugin.render( scene, camera );
  12284. lensFlarePlugin.render( scene, camera, _currentWidth, _currentHeight );
  12285. // Generate mipmap if we're using any kind of mipmap filtering
  12286. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12287. updateRenderTargetMipmap( renderTarget );
  12288. }
  12289. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12290. state.setDepthTest( true );
  12291. state.setDepthWrite( true );
  12292. state.setColorWrite( true );
  12293. // _gl.finish();
  12294. };
  12295. function projectObject( object ) {
  12296. if ( object.visible === true ) {
  12297. if ( object instanceof THREE.Scene || object instanceof THREE.Group ) {
  12298. // skip
  12299. } else {
  12300. // update Skeleton objects
  12301. if ( object instanceof THREE.SkinnedMesh ) {
  12302. object.skeleton.update();
  12303. }
  12304. objects.init( object );
  12305. if ( object instanceof THREE.Light ) {
  12306. lights.push( object );
  12307. } else if ( object instanceof THREE.Sprite ) {
  12308. sprites.push( object );
  12309. } else if ( object instanceof THREE.LensFlare ) {
  12310. lensFlares.push( object );
  12311. } else {
  12312. var webglObject = objects.objects[ object.id ];
  12313. if ( webglObject && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  12314. var material = object.material;
  12315. if ( material.transparent ) {
  12316. transparentObjects.push( webglObject );
  12317. } else {
  12318. opaqueObjects.push( webglObject );
  12319. }
  12320. if ( _this.sortObjects === true ) {
  12321. _vector3.setFromMatrixPosition( object.matrixWorld );
  12322. _vector3.applyProjection( _projScreenMatrix );
  12323. webglObject.z = _vector3.z;
  12324. }
  12325. }
  12326. }
  12327. }
  12328. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  12329. projectObject( object.children[ i ] );
  12330. }
  12331. }
  12332. }
  12333. function renderObjects( renderList, camera, lights, fog, overrideMaterial ) {
  12334. var material = overrideMaterial;
  12335. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12336. var webglObject = renderList[ i ];
  12337. var object = webglObject.object;
  12338. setupMatrices( object, camera );
  12339. if ( overrideMaterial === null ) material = object.material;
  12340. if ( material instanceof THREE.MeshFaceMaterial ) {
  12341. var materials = material.materials;
  12342. for ( var j = 0, jl = materials.length; j < jl; j ++ ) {
  12343. _this.renderBufferDirect( camera, lights, fog, materials[ j ], object );
  12344. }
  12345. continue;
  12346. }
  12347. _this.renderBufferDirect( camera, lights, fog, material, object );
  12348. }
  12349. }
  12350. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, overrideMaterial ) {
  12351. var material = overrideMaterial;
  12352. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  12353. var webglObject = renderList[ i ];
  12354. var object = webglObject.object;
  12355. if ( object.visible === true ) {
  12356. if ( overrideMaterial === null ) material = webglObject[ materialType ];
  12357. _this.renderImmediateObject( camera, lights, fog, material, object );
  12358. }
  12359. }
  12360. }
  12361. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12362. setMaterial( material );
  12363. var program = setProgram( camera, lights, fog, material, object );
  12364. _currentGeometryProgram = '';
  12365. if ( object.immediateRenderCallback ) {
  12366. object.immediateRenderCallback( program, _gl, _frustum );
  12367. } else {
  12368. object.render( function ( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12369. }
  12370. };
  12371. // Materials
  12372. var shaderIDs = {
  12373. MeshDepthMaterial: 'depth',
  12374. MeshNormalMaterial: 'normal',
  12375. MeshBasicMaterial: 'basic',
  12376. MeshLambertMaterial: 'lambert',
  12377. MeshPhongMaterial: 'phong',
  12378. LineBasicMaterial: 'basic',
  12379. LineDashedMaterial: 'dashed',
  12380. PointCloudMaterial: 'particle_basic'
  12381. };
  12382. function initMaterial( material, lights, fog, object ) {
  12383. var shaderID = shaderIDs[ material.type ];
  12384. // heuristics to create shader parameters according to lights in the scene
  12385. // (not to blow over maxLights budget)
  12386. var maxLightCount = allocateLights( lights );
  12387. var maxShadows = allocateShadows( lights );
  12388. var maxBones = allocateBones( object );
  12389. var parameters = {
  12390. precision: _precision,
  12391. supportsVertexTextures: _supportsVertexTextures,
  12392. map: !! material.map,
  12393. envMap: !! material.envMap,
  12394. envMapMode: material.envMap && material.envMap.mapping,
  12395. lightMap: !! material.lightMap,
  12396. aoMap: !! material.aoMap,
  12397. emissiveMap: !! material.emissiveMap,
  12398. bumpMap: !! material.bumpMap,
  12399. normalMap: !! material.normalMap,
  12400. specularMap: !! material.specularMap,
  12401. alphaMap: !! material.alphaMap,
  12402. combine: material.combine,
  12403. vertexColors: material.vertexColors,
  12404. fog: fog,
  12405. useFog: material.fog,
  12406. fogExp: fog instanceof THREE.FogExp2,
  12407. flatShading: material.shading === THREE.FlatShading,
  12408. sizeAttenuation: material.sizeAttenuation,
  12409. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  12410. skinning: material.skinning,
  12411. maxBones: maxBones,
  12412. useVertexTexture: _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  12413. morphTargets: material.morphTargets,
  12414. morphNormals: material.morphNormals,
  12415. maxMorphTargets: _this.maxMorphTargets,
  12416. maxMorphNormals: _this.maxMorphNormals,
  12417. maxDirLights: maxLightCount.directional,
  12418. maxPointLights: maxLightCount.point,
  12419. maxSpotLights: maxLightCount.spot,
  12420. maxHemiLights: maxLightCount.hemi,
  12421. maxShadows: maxShadows,
  12422. shadowMapEnabled: shadowMap.enabled && object.receiveShadow && maxShadows > 0,
  12423. shadowMapType: shadowMap.type,
  12424. shadowMapDebug: shadowMap.debug,
  12425. shadowMapCascade: shadowMap.cascade,
  12426. alphaTest: material.alphaTest,
  12427. metal: material.metal,
  12428. doubleSided: material.side === THREE.DoubleSide,
  12429. flipSided: material.side === THREE.BackSide
  12430. };
  12431. // Generate code
  12432. var chunks = [];
  12433. if ( shaderID ) {
  12434. chunks.push( shaderID );
  12435. } else {
  12436. chunks.push( material.fragmentShader );
  12437. chunks.push( material.vertexShader );
  12438. }
  12439. if ( material.defines !== undefined ) {
  12440. for ( var name in material.defines ) {
  12441. chunks.push( name );
  12442. chunks.push( material.defines[ name ] );
  12443. }
  12444. }
  12445. for ( var name in parameters ) {
  12446. chunks.push( name );
  12447. chunks.push( parameters[ name ] );
  12448. }
  12449. var code = chunks.join();
  12450. if ( !material.program ) {
  12451. // new material
  12452. material.addEventListener( 'dispose', onMaterialDispose );
  12453. } else if ( material.program.code !== code ) {
  12454. // changed glsl or parameters
  12455. deallocateMaterial( material );
  12456. } else if ( shaderID !== undefined ) {
  12457. // same glsl
  12458. return;
  12459. } else if ( material.__webglShader.uniforms === material.uniforms ) {
  12460. // same uniforms (container object)
  12461. return;
  12462. }
  12463. if ( shaderID ) {
  12464. var shader = THREE.ShaderLib[ shaderID ];
  12465. material.__webglShader = {
  12466. name: material.type,
  12467. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  12468. vertexShader: shader.vertexShader,
  12469. fragmentShader: shader.fragmentShader
  12470. }
  12471. } else {
  12472. material.__webglShader = {
  12473. name: material.type,
  12474. uniforms: material.uniforms,
  12475. vertexShader: material.vertexShader,
  12476. fragmentShader: material.fragmentShader
  12477. }
  12478. }
  12479. var program;
  12480. // Check if code has been already compiled
  12481. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  12482. var programInfo = _programs[ p ];
  12483. if ( programInfo.code === code ) {
  12484. program = programInfo;
  12485. program.usedTimes ++;
  12486. break;
  12487. }
  12488. }
  12489. if ( program === undefined ) {
  12490. program = new THREE.WebGLProgram( _this, code, material, parameters );
  12491. _programs.push( program );
  12492. _this.info.memory.programs = _programs.length;
  12493. }
  12494. material.program = program;
  12495. var attributes = program.getAttributes();
  12496. if ( material.morphTargets ) {
  12497. material.numSupportedMorphTargets = 0;
  12498. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  12499. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  12500. material.numSupportedMorphTargets ++;
  12501. }
  12502. }
  12503. }
  12504. if ( material.morphNormals ) {
  12505. material.numSupportedMorphNormals = 0;
  12506. for ( i = 0; i < _this.maxMorphNormals; i ++ ) {
  12507. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  12508. material.numSupportedMorphNormals ++;
  12509. }
  12510. }
  12511. }
  12512. material.uniformsList = [];
  12513. var uniformLocations = material.program.getUniforms();
  12514. for ( var u in material.__webglShader.uniforms ) {
  12515. var location = uniformLocations[ u ];
  12516. if ( location ) {
  12517. material.uniformsList.push( [ material.__webglShader.uniforms[ u ], location ] );
  12518. }
  12519. }
  12520. }
  12521. function setMaterial( material ) {
  12522. setMaterialFaces( material );
  12523. if ( material.transparent === true ) {
  12524. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha );
  12525. } else {
  12526. state.setBlending( THREE.NoBlending );
  12527. }
  12528. state.setDepthFunc( material.depthFunc );
  12529. state.setDepthTest( material.depthTest );
  12530. state.setDepthWrite( material.depthWrite );
  12531. state.setColorWrite( material.colorWrite );
  12532. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12533. }
  12534. function setMaterialFaces( material ) {
  12535. state.setDoubleSided( material.side === THREE.DoubleSide );
  12536. state.setFlipSided( material.side === THREE.BackSide );
  12537. }
  12538. function setProgram( camera, lights, fog, material, object ) {
  12539. _usedTextureUnits = 0;
  12540. if ( material.needsUpdate ) {
  12541. initMaterial( material, lights, fog, object );
  12542. material.needsUpdate = false;
  12543. }
  12544. var refreshProgram = false;
  12545. var refreshMaterial = false;
  12546. var refreshLights = false;
  12547. var program = material.program,
  12548. p_uniforms = program.getUniforms(),
  12549. m_uniforms = material.__webglShader.uniforms;
  12550. if ( program.id !== _currentProgram ) {
  12551. _gl.useProgram( program.program );
  12552. _currentProgram = program.id;
  12553. refreshProgram = true;
  12554. refreshMaterial = true;
  12555. refreshLights = true;
  12556. }
  12557. if ( material.id !== _currentMaterialId ) {
  12558. if ( _currentMaterialId === -1 ) refreshLights = true;
  12559. _currentMaterialId = material.id;
  12560. refreshMaterial = true;
  12561. }
  12562. if ( refreshProgram || camera !== _currentCamera ) {
  12563. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  12564. if ( _logarithmicDepthBuffer ) {
  12565. _gl.uniform1f( p_uniforms.logDepthBufFC, 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  12566. }
  12567. if ( camera !== _currentCamera ) _currentCamera = camera;
  12568. // load material specific uniforms
  12569. // (shader material also gets them for the sake of genericity)
  12570. if ( material instanceof THREE.ShaderMaterial ||
  12571. material instanceof THREE.MeshPhongMaterial ||
  12572. material.envMap ) {
  12573. if ( p_uniforms.cameraPosition !== null ) {
  12574. _vector3.setFromMatrixPosition( camera.matrixWorld );
  12575. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  12576. }
  12577. }
  12578. if ( material instanceof THREE.MeshPhongMaterial ||
  12579. material instanceof THREE.MeshLambertMaterial ||
  12580. material instanceof THREE.MeshBasicMaterial ||
  12581. material instanceof THREE.ShaderMaterial ||
  12582. material.skinning ) {
  12583. if ( p_uniforms.viewMatrix !== null ) {
  12584. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  12585. }
  12586. }
  12587. }
  12588. // skinning uniforms must be set even if material didn't change
  12589. // auto-setting of texture unit for bone texture must go before other textures
  12590. // not sure why, but otherwise weird things happen
  12591. if ( material.skinning ) {
  12592. if ( object.bindMatrix && p_uniforms.bindMatrix !== null ) {
  12593. _gl.uniformMatrix4fv( p_uniforms.bindMatrix, false, object.bindMatrix.elements );
  12594. }
  12595. if ( object.bindMatrixInverse && p_uniforms.bindMatrixInverse !== null ) {
  12596. _gl.uniformMatrix4fv( p_uniforms.bindMatrixInverse, false, object.bindMatrixInverse.elements );
  12597. }
  12598. if ( _supportsBoneTextures && object.skeleton && object.skeleton.useVertexTexture ) {
  12599. if ( p_uniforms.boneTexture !== null ) {
  12600. var textureUnit = getTextureUnit();
  12601. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12602. _this.setTexture( object.skeleton.boneTexture, textureUnit );
  12603. }
  12604. if ( p_uniforms.boneTextureWidth !== null ) {
  12605. _gl.uniform1i( p_uniforms.boneTextureWidth, object.skeleton.boneTextureWidth );
  12606. }
  12607. if ( p_uniforms.boneTextureHeight !== null ) {
  12608. _gl.uniform1i( p_uniforms.boneTextureHeight, object.skeleton.boneTextureHeight );
  12609. }
  12610. } else if ( object.skeleton && object.skeleton.boneMatrices ) {
  12611. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12612. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.skeleton.boneMatrices );
  12613. }
  12614. }
  12615. }
  12616. if ( refreshMaterial ) {
  12617. // refresh uniforms common to several materials
  12618. if ( fog && material.fog ) {
  12619. refreshUniformsFog( m_uniforms, fog );
  12620. }
  12621. if ( material instanceof THREE.MeshPhongMaterial ||
  12622. material instanceof THREE.MeshLambertMaterial ||
  12623. material.lights ) {
  12624. if ( _lightsNeedUpdate ) {
  12625. refreshLights = true;
  12626. setupLights( lights );
  12627. _lightsNeedUpdate = false;
  12628. }
  12629. if ( refreshLights ) {
  12630. refreshUniformsLights( m_uniforms, _lights );
  12631. markUniformsLightsNeedsUpdate( m_uniforms, true );
  12632. } else {
  12633. markUniformsLightsNeedsUpdate( m_uniforms, false );
  12634. }
  12635. }
  12636. if ( material instanceof THREE.MeshBasicMaterial ||
  12637. material instanceof THREE.MeshLambertMaterial ||
  12638. material instanceof THREE.MeshPhongMaterial ) {
  12639. refreshUniformsCommon( m_uniforms, material );
  12640. }
  12641. // refresh single material specific uniforms
  12642. if ( material instanceof THREE.LineBasicMaterial ) {
  12643. refreshUniformsLine( m_uniforms, material );
  12644. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12645. refreshUniformsLine( m_uniforms, material );
  12646. refreshUniformsDash( m_uniforms, material );
  12647. } else if ( material instanceof THREE.PointCloudMaterial ) {
  12648. refreshUniformsParticle( m_uniforms, material );
  12649. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12650. refreshUniformsPhong( m_uniforms, material );
  12651. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12652. refreshUniformsLambert( m_uniforms, material );
  12653. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12654. refreshUniformsBasic( m_uniforms, material );
  12655. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12656. m_uniforms.mNear.value = camera.near;
  12657. m_uniforms.mFar.value = camera.far;
  12658. m_uniforms.opacity.value = material.opacity;
  12659. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12660. m_uniforms.opacity.value = material.opacity;
  12661. }
  12662. if ( object.receiveShadow && ! material._shadowPass ) {
  12663. refreshUniformsShadow( m_uniforms, lights );
  12664. }
  12665. // load common uniforms
  12666. loadUniformsGeneric( material.uniformsList );
  12667. }
  12668. loadUniformsMatrices( p_uniforms, object );
  12669. if ( p_uniforms.modelMatrix !== null ) {
  12670. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12671. }
  12672. return program;
  12673. }
  12674. // Uniforms (refresh uniforms objects)
  12675. function refreshUniformsCommon ( uniforms, material ) {
  12676. uniforms.opacity.value = material.opacity;
  12677. uniforms.diffuse.value = material.color;
  12678. uniforms.map.value = material.map;
  12679. uniforms.specularMap.value = material.specularMap;
  12680. uniforms.alphaMap.value = material.alphaMap;
  12681. if ( material.bumpMap ) {
  12682. uniforms.bumpMap.value = material.bumpMap;
  12683. uniforms.bumpScale.value = material.bumpScale;
  12684. }
  12685. if ( material.normalMap ) {
  12686. uniforms.normalMap.value = material.normalMap;
  12687. uniforms.normalScale.value.copy( material.normalScale );
  12688. }
  12689. // uv repeat and offset setting priorities
  12690. // 1. color map
  12691. // 2. specular map
  12692. // 3. normal map
  12693. // 4. bump map
  12694. // 5. alpha map
  12695. // 6. emissive map
  12696. var uvScaleMap;
  12697. if ( material.map ) {
  12698. uvScaleMap = material.map;
  12699. } else if ( material.specularMap ) {
  12700. uvScaleMap = material.specularMap;
  12701. } else if ( material.normalMap ) {
  12702. uvScaleMap = material.normalMap;
  12703. } else if ( material.bumpMap ) {
  12704. uvScaleMap = material.bumpMap;
  12705. } else if ( material.alphaMap ) {
  12706. uvScaleMap = material.alphaMap;
  12707. } else if ( material.emissiveMap ) {
  12708. uvScaleMap = material.emissiveMap;
  12709. }
  12710. if ( uvScaleMap !== undefined ) {
  12711. var offset = uvScaleMap.offset;
  12712. var repeat = uvScaleMap.repeat;
  12713. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12714. }
  12715. uniforms.envMap.value = material.envMap;
  12716. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  12717. uniforms.reflectivity.value = material.reflectivity;
  12718. uniforms.refractionRatio.value = material.refractionRatio;
  12719. }
  12720. function refreshUniformsLine ( uniforms, material ) {
  12721. uniforms.diffuse.value = material.color;
  12722. uniforms.opacity.value = material.opacity;
  12723. }
  12724. function refreshUniformsDash ( uniforms, material ) {
  12725. uniforms.dashSize.value = material.dashSize;
  12726. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12727. uniforms.scale.value = material.scale;
  12728. }
  12729. function refreshUniformsParticle ( uniforms, material ) {
  12730. uniforms.psColor.value = material.color;
  12731. uniforms.opacity.value = material.opacity;
  12732. uniforms.size.value = material.size;
  12733. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12734. uniforms.map.value = material.map;
  12735. if ( material.map !== null ) {
  12736. var offset = material.map.offset;
  12737. var repeat = material.map.repeat;
  12738. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12739. }
  12740. }
  12741. function refreshUniformsFog ( uniforms, fog ) {
  12742. uniforms.fogColor.value = fog.color;
  12743. if ( fog instanceof THREE.Fog ) {
  12744. uniforms.fogNear.value = fog.near;
  12745. uniforms.fogFar.value = fog.far;
  12746. } else if ( fog instanceof THREE.FogExp2 ) {
  12747. uniforms.fogDensity.value = fog.density;
  12748. }
  12749. }
  12750. function refreshUniformsPhong ( uniforms, material ) {
  12751. uniforms.shininess.value = material.shininess;
  12752. uniforms.emissive.value = material.emissive;
  12753. uniforms.specular.value = material.specular;
  12754. uniforms.lightMap.value = material.lightMap;
  12755. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  12756. uniforms.aoMap.value = material.aoMap;
  12757. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12758. uniforms.emissiveMap.value = material.emissiveMap;
  12759. }
  12760. function refreshUniformsLambert ( uniforms, material ) {
  12761. uniforms.emissive.value = material.emissive;
  12762. }
  12763. function refreshUniformsBasic ( uniforms, material ) {
  12764. uniforms.aoMap.value = material.aoMap;
  12765. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  12766. }
  12767. function refreshUniformsLights ( uniforms, lights ) {
  12768. uniforms.ambientLightColor.value = lights.ambient;
  12769. uniforms.directionalLightColor.value = lights.directional.colors;
  12770. uniforms.directionalLightDirection.value = lights.directional.positions;
  12771. uniforms.pointLightColor.value = lights.point.colors;
  12772. uniforms.pointLightPosition.value = lights.point.positions;
  12773. uniforms.pointLightDistance.value = lights.point.distances;
  12774. uniforms.pointLightDecay.value = lights.point.decays;
  12775. uniforms.spotLightColor.value = lights.spot.colors;
  12776. uniforms.spotLightPosition.value = lights.spot.positions;
  12777. uniforms.spotLightDistance.value = lights.spot.distances;
  12778. uniforms.spotLightDirection.value = lights.spot.directions;
  12779. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12780. uniforms.spotLightExponent.value = lights.spot.exponents;
  12781. uniforms.spotLightDecay.value = lights.spot.decays;
  12782. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12783. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12784. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12785. }
  12786. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  12787. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  12788. uniforms.ambientLightColor.needsUpdate = value;
  12789. uniforms.directionalLightColor.needsUpdate = value;
  12790. uniforms.directionalLightDirection.needsUpdate = value;
  12791. uniforms.pointLightColor.needsUpdate = value;
  12792. uniforms.pointLightPosition.needsUpdate = value;
  12793. uniforms.pointLightDistance.needsUpdate = value;
  12794. uniforms.pointLightDecay.needsUpdate = value;
  12795. uniforms.spotLightColor.needsUpdate = value;
  12796. uniforms.spotLightPosition.needsUpdate = value;
  12797. uniforms.spotLightDistance.needsUpdate = value;
  12798. uniforms.spotLightDirection.needsUpdate = value;
  12799. uniforms.spotLightAngleCos.needsUpdate = value;
  12800. uniforms.spotLightExponent.needsUpdate = value;
  12801. uniforms.spotLightDecay.needsUpdate = value;
  12802. uniforms.hemisphereLightSkyColor.needsUpdate = value;
  12803. uniforms.hemisphereLightGroundColor.needsUpdate = value;
  12804. uniforms.hemisphereLightDirection.needsUpdate = value;
  12805. }
  12806. function refreshUniformsShadow ( uniforms, lights ) {
  12807. if ( uniforms.shadowMatrix ) {
  12808. var j = 0;
  12809. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12810. var light = lights[ i ];
  12811. if ( ! light.castShadow ) continue;
  12812. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12813. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12814. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12815. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12816. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12817. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12818. j ++;
  12819. }
  12820. }
  12821. }
  12822. }
  12823. // Uniforms (load to GPU)
  12824. function loadUniformsMatrices ( uniforms, object ) {
  12825. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12826. if ( uniforms.normalMatrix ) {
  12827. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12828. }
  12829. }
  12830. function getTextureUnit() {
  12831. var textureUnit = _usedTextureUnits;
  12832. if ( textureUnit >= _maxTextures ) {
  12833. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + _maxTextures );
  12834. }
  12835. _usedTextureUnits += 1;
  12836. return textureUnit;
  12837. }
  12838. function loadUniformsGeneric ( uniforms ) {
  12839. var texture, textureUnit, offset;
  12840. for ( var j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12841. var uniform = uniforms[ j ][ 0 ];
  12842. // needsUpdate property is not added to all uniforms.
  12843. if ( uniform.needsUpdate === false ) continue;
  12844. var type = uniform.type;
  12845. var value = uniform.value;
  12846. var location = uniforms[ j ][ 1 ];
  12847. switch ( type ) {
  12848. case '1i':
  12849. _gl.uniform1i( location, value );
  12850. break;
  12851. case '1f':
  12852. _gl.uniform1f( location, value );
  12853. break;
  12854. case '2f':
  12855. _gl.uniform2f( location, value[ 0 ], value[ 1 ] );
  12856. break;
  12857. case '3f':
  12858. _gl.uniform3f( location, value[ 0 ], value[ 1 ], value[ 2 ] );
  12859. break;
  12860. case '4f':
  12861. _gl.uniform4f( location, value[ 0 ], value[ 1 ], value[ 2 ], value[ 3 ] );
  12862. break;
  12863. case '1iv':
  12864. _gl.uniform1iv( location, value );
  12865. break;
  12866. case '3iv':
  12867. _gl.uniform3iv( location, value );
  12868. break;
  12869. case '1fv':
  12870. _gl.uniform1fv( location, value );
  12871. break;
  12872. case '2fv':
  12873. _gl.uniform2fv( location, value );
  12874. break;
  12875. case '3fv':
  12876. _gl.uniform3fv( location, value );
  12877. break;
  12878. case '4fv':
  12879. _gl.uniform4fv( location, value );
  12880. break;
  12881. case 'Matrix3fv':
  12882. _gl.uniformMatrix3fv( location, false, value );
  12883. break;
  12884. case 'Matrix4fv':
  12885. _gl.uniformMatrix4fv( location, false, value );
  12886. break;
  12887. //
  12888. case 'i':
  12889. // single integer
  12890. _gl.uniform1i( location, value );
  12891. break;
  12892. case 'f':
  12893. // single float
  12894. _gl.uniform1f( location, value );
  12895. break;
  12896. case 'v2':
  12897. // single THREE.Vector2
  12898. _gl.uniform2f( location, value.x, value.y );
  12899. break;
  12900. case 'v3':
  12901. // single THREE.Vector3
  12902. _gl.uniform3f( location, value.x, value.y, value.z );
  12903. break;
  12904. case 'v4':
  12905. // single THREE.Vector4
  12906. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12907. break;
  12908. case 'c':
  12909. // single THREE.Color
  12910. _gl.uniform3f( location, value.r, value.g, value.b );
  12911. break;
  12912. case 'iv1':
  12913. // flat array of integers (JS or typed array)
  12914. _gl.uniform1iv( location, value );
  12915. break;
  12916. case 'iv':
  12917. // flat array of integers with 3 x N size (JS or typed array)
  12918. _gl.uniform3iv( location, value );
  12919. break;
  12920. case 'fv1':
  12921. // flat array of floats (JS or typed array)
  12922. _gl.uniform1fv( location, value );
  12923. break;
  12924. case 'fv':
  12925. // flat array of floats with 3 x N size (JS or typed array)
  12926. _gl.uniform3fv( location, value );
  12927. break;
  12928. case 'v2v':
  12929. // array of THREE.Vector2
  12930. if ( uniform._array === undefined ) {
  12931. uniform._array = new Float32Array( 2 * value.length );
  12932. }
  12933. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12934. offset = i * 2;
  12935. uniform._array[ offset + 0 ] = value[ i ].x;
  12936. uniform._array[ offset + 1 ] = value[ i ].y;
  12937. }
  12938. _gl.uniform2fv( location, uniform._array );
  12939. break;
  12940. case 'v3v':
  12941. // array of THREE.Vector3
  12942. if ( uniform._array === undefined ) {
  12943. uniform._array = new Float32Array( 3 * value.length );
  12944. }
  12945. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12946. offset = i * 3;
  12947. uniform._array[ offset + 0 ] = value[ i ].x;
  12948. uniform._array[ offset + 1 ] = value[ i ].y;
  12949. uniform._array[ offset + 2 ] = value[ i ].z;
  12950. }
  12951. _gl.uniform3fv( location, uniform._array );
  12952. break;
  12953. case 'v4v':
  12954. // array of THREE.Vector4
  12955. if ( uniform._array === undefined ) {
  12956. uniform._array = new Float32Array( 4 * value.length );
  12957. }
  12958. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12959. offset = i * 4;
  12960. uniform._array[ offset + 0 ] = value[ i ].x;
  12961. uniform._array[ offset + 1 ] = value[ i ].y;
  12962. uniform._array[ offset + 2 ] = value[ i ].z;
  12963. uniform._array[ offset + 3 ] = value[ i ].w;
  12964. }
  12965. _gl.uniform4fv( location, uniform._array );
  12966. break;
  12967. case 'm3':
  12968. // single THREE.Matrix3
  12969. _gl.uniformMatrix3fv( location, false, value.elements );
  12970. break;
  12971. case 'm3v':
  12972. // array of THREE.Matrix3
  12973. if ( uniform._array === undefined ) {
  12974. uniform._array = new Float32Array( 9 * value.length );
  12975. }
  12976. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12977. value[ i ].flattenToArrayOffset( uniform._array, i * 9 );
  12978. }
  12979. _gl.uniformMatrix3fv( location, false, uniform._array );
  12980. break;
  12981. case 'm4':
  12982. // single THREE.Matrix4
  12983. _gl.uniformMatrix4fv( location, false, value.elements );
  12984. break;
  12985. case 'm4v':
  12986. // array of THREE.Matrix4
  12987. if ( uniform._array === undefined ) {
  12988. uniform._array = new Float32Array( 16 * value.length );
  12989. }
  12990. for ( var i = 0, il = value.length; i < il; i ++ ) {
  12991. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12992. }
  12993. _gl.uniformMatrix4fv( location, false, uniform._array );
  12994. break;
  12995. case 't':
  12996. // single THREE.Texture (2d or cube)
  12997. texture = value;
  12998. textureUnit = getTextureUnit();
  12999. _gl.uniform1i( location, textureUnit );
  13000. if ( ! texture ) continue;
  13001. if ( texture instanceof THREE.CubeTexture ||
  13002. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) { // CompressedTexture can have Array in image :/
  13003. setCubeTexture( texture, textureUnit );
  13004. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13005. setCubeTextureDynamic( texture, textureUnit );
  13006. } else {
  13007. _this.setTexture( texture, textureUnit );
  13008. }
  13009. break;
  13010. case 'tv':
  13011. // array of THREE.Texture (2d)
  13012. if ( uniform._array === undefined ) {
  13013. uniform._array = [];
  13014. }
  13015. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  13016. uniform._array[ i ] = getTextureUnit();
  13017. }
  13018. _gl.uniform1iv( location, uniform._array );
  13019. for ( var i = 0, il = uniform.value.length; i < il; i ++ ) {
  13020. texture = uniform.value[ i ];
  13021. textureUnit = uniform._array[ i ];
  13022. if ( ! texture ) continue;
  13023. _this.setTexture( texture, textureUnit );
  13024. }
  13025. break;
  13026. default:
  13027. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  13028. }
  13029. }
  13030. }
  13031. function setupMatrices ( object, camera ) {
  13032. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13033. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  13034. }
  13035. function setColorLinear( array, offset, color, intensity ) {
  13036. array[ offset + 0 ] = color.r * intensity;
  13037. array[ offset + 1 ] = color.g * intensity;
  13038. array[ offset + 2 ] = color.b * intensity;
  13039. }
  13040. function setupLights ( lights ) {
  13041. var l, ll, light,
  13042. r = 0, g = 0, b = 0,
  13043. color, skyColor, groundColor,
  13044. intensity,
  13045. distance,
  13046. zlights = _lights,
  13047. dirColors = zlights.directional.colors,
  13048. dirPositions = zlights.directional.positions,
  13049. pointColors = zlights.point.colors,
  13050. pointPositions = zlights.point.positions,
  13051. pointDistances = zlights.point.distances,
  13052. pointDecays = zlights.point.decays,
  13053. spotColors = zlights.spot.colors,
  13054. spotPositions = zlights.spot.positions,
  13055. spotDistances = zlights.spot.distances,
  13056. spotDirections = zlights.spot.directions,
  13057. spotAnglesCos = zlights.spot.anglesCos,
  13058. spotExponents = zlights.spot.exponents,
  13059. spotDecays = zlights.spot.decays,
  13060. hemiSkyColors = zlights.hemi.skyColors,
  13061. hemiGroundColors = zlights.hemi.groundColors,
  13062. hemiPositions = zlights.hemi.positions,
  13063. dirLength = 0,
  13064. pointLength = 0,
  13065. spotLength = 0,
  13066. hemiLength = 0,
  13067. dirCount = 0,
  13068. pointCount = 0,
  13069. spotCount = 0,
  13070. hemiCount = 0,
  13071. dirOffset = 0,
  13072. pointOffset = 0,
  13073. spotOffset = 0,
  13074. hemiOffset = 0;
  13075. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13076. light = lights[ l ];
  13077. if ( light.onlyShadow ) continue;
  13078. color = light.color;
  13079. intensity = light.intensity;
  13080. distance = light.distance;
  13081. if ( light instanceof THREE.AmbientLight ) {
  13082. if ( ! light.visible ) continue;
  13083. r += color.r;
  13084. g += color.g;
  13085. b += color.b;
  13086. } else if ( light instanceof THREE.DirectionalLight ) {
  13087. dirCount += 1;
  13088. if ( ! light.visible ) continue;
  13089. _direction.setFromMatrixPosition( light.matrixWorld );
  13090. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13091. _direction.sub( _vector3 );
  13092. _direction.normalize();
  13093. dirOffset = dirLength * 3;
  13094. dirPositions[ dirOffset + 0 ] = _direction.x;
  13095. dirPositions[ dirOffset + 1 ] = _direction.y;
  13096. dirPositions[ dirOffset + 2 ] = _direction.z;
  13097. setColorLinear( dirColors, dirOffset, color, intensity );
  13098. dirLength += 1;
  13099. } else if ( light instanceof THREE.PointLight ) {
  13100. pointCount += 1;
  13101. if ( ! light.visible ) continue;
  13102. pointOffset = pointLength * 3;
  13103. setColorLinear( pointColors, pointOffset, color, intensity );
  13104. _vector3.setFromMatrixPosition( light.matrixWorld );
  13105. pointPositions[ pointOffset + 0 ] = _vector3.x;
  13106. pointPositions[ pointOffset + 1 ] = _vector3.y;
  13107. pointPositions[ pointOffset + 2 ] = _vector3.z;
  13108. // distance is 0 if decay is 0, because there is no attenuation at all.
  13109. pointDistances[ pointLength ] = distance;
  13110. pointDecays[ pointLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  13111. pointLength += 1;
  13112. } else if ( light instanceof THREE.SpotLight ) {
  13113. spotCount += 1;
  13114. if ( ! light.visible ) continue;
  13115. spotOffset = spotLength * 3;
  13116. setColorLinear( spotColors, spotOffset, color, intensity );
  13117. _direction.setFromMatrixPosition( light.matrixWorld );
  13118. spotPositions[ spotOffset + 0 ] = _direction.x;
  13119. spotPositions[ spotOffset + 1 ] = _direction.y;
  13120. spotPositions[ spotOffset + 2 ] = _direction.z;
  13121. spotDistances[ spotLength ] = distance;
  13122. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  13123. _direction.sub( _vector3 );
  13124. _direction.normalize();
  13125. spotDirections[ spotOffset + 0 ] = _direction.x;
  13126. spotDirections[ spotOffset + 1 ] = _direction.y;
  13127. spotDirections[ spotOffset + 2 ] = _direction.z;
  13128. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13129. spotExponents[ spotLength ] = light.exponent;
  13130. spotDecays[ spotLength ] = ( light.distance === 0 ) ? 0.0 : light.decay;
  13131. spotLength += 1;
  13132. } else if ( light instanceof THREE.HemisphereLight ) {
  13133. hemiCount += 1;
  13134. if ( ! light.visible ) continue;
  13135. _direction.setFromMatrixPosition( light.matrixWorld );
  13136. _direction.normalize();
  13137. hemiOffset = hemiLength * 3;
  13138. hemiPositions[ hemiOffset + 0 ] = _direction.x;
  13139. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13140. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13141. skyColor = light.color;
  13142. groundColor = light.groundColor;
  13143. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13144. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13145. hemiLength += 1;
  13146. }
  13147. }
  13148. // null eventual remains from removed lights
  13149. // (this is to avoid if in shader)
  13150. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13151. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13152. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13153. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13154. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13155. zlights.directional.length = dirLength;
  13156. zlights.point.length = pointLength;
  13157. zlights.spot.length = spotLength;
  13158. zlights.hemi.length = hemiLength;
  13159. zlights.ambient[ 0 ] = r;
  13160. zlights.ambient[ 1 ] = g;
  13161. zlights.ambient[ 2 ] = b;
  13162. }
  13163. // GL state setting
  13164. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13165. if ( cullFace === THREE.CullFaceNone ) {
  13166. _gl.disable( _gl.CULL_FACE );
  13167. } else {
  13168. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13169. _gl.frontFace( _gl.CW );
  13170. } else {
  13171. _gl.frontFace( _gl.CCW );
  13172. }
  13173. if ( cullFace === THREE.CullFaceBack ) {
  13174. _gl.cullFace( _gl.BACK );
  13175. } else if ( cullFace === THREE.CullFaceFront ) {
  13176. _gl.cullFace( _gl.FRONT );
  13177. } else {
  13178. _gl.cullFace( _gl.FRONT_AND_BACK );
  13179. }
  13180. _gl.enable( _gl.CULL_FACE );
  13181. }
  13182. };
  13183. this.setMaterialFaces = setMaterialFaces;
  13184. // Textures
  13185. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13186. var extension;
  13187. if ( isImagePowerOfTwo ) {
  13188. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13189. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13190. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13191. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13192. } else {
  13193. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13194. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13195. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  13196. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping. ( ' + texture.sourceFile + ' )' );
  13197. }
  13198. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13199. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13200. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  13201. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter. ( ' + texture.sourceFile + ' )' );
  13202. }
  13203. }
  13204. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  13205. if ( extension && texture.type !== THREE.FloatType && texture.type !== THREE.HalfFloatType ) {
  13206. if ( texture.anisotropy > 1 || texture.__currentAnisotropy ) {
  13207. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  13208. texture.__currentAnisotropy = texture.anisotropy;
  13209. }
  13210. }
  13211. }
  13212. this.uploadTexture = function ( texture, slot ) {
  13213. if ( texture.__webglInit === undefined ) {
  13214. texture.__webglInit = true;
  13215. texture.addEventListener( 'dispose', onTextureDispose );
  13216. texture.__webglTexture = _gl.createTexture();
  13217. _this.info.memory.textures ++;
  13218. }
  13219. state.activeTexture( _gl.TEXTURE0 + slot );
  13220. state.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13221. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13222. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13223. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13224. texture.image = clampToMaxSize( texture.image, _maxTextureSize );
  13225. var image = texture.image,
  13226. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13227. glFormat = paramThreeToGL( texture.format ),
  13228. glType = paramThreeToGL( texture.type );
  13229. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13230. var mipmap, mipmaps = texture.mipmaps;
  13231. if ( texture instanceof THREE.DataTexture ) {
  13232. // use manually created mipmaps if available
  13233. // if there are no manual mipmaps
  13234. // set 0 level mipmap and then use GL to generate other mipmap levels
  13235. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13236. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13237. mipmap = mipmaps[ i ];
  13238. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13239. }
  13240. texture.generateMipmaps = false;
  13241. } else {
  13242. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13243. }
  13244. } else if ( texture instanceof THREE.CompressedTexture ) {
  13245. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13246. mipmap = mipmaps[ i ];
  13247. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13248. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13249. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13250. } else {
  13251. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  13252. }
  13253. } else {
  13254. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13255. }
  13256. }
  13257. } else { // regular Texture (image, video, canvas)
  13258. // use manually created mipmaps if available
  13259. // if there are no manual mipmaps
  13260. // set 0 level mipmap and then use GL to generate other mipmap levels
  13261. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13262. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13263. mipmap = mipmaps[ i ];
  13264. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  13265. }
  13266. texture.generateMipmaps = false;
  13267. } else {
  13268. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13269. }
  13270. }
  13271. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13272. texture.needsUpdate = false;
  13273. if ( texture.onUpdate ) texture.onUpdate( texture );
  13274. };
  13275. this.setTexture = function ( texture, slot ) {
  13276. if ( texture.needsUpdate === true ) {
  13277. var image = texture.image;
  13278. if ( image === undefined ) {
  13279. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  13280. return;
  13281. }
  13282. if ( image.complete === false ) {
  13283. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  13284. return;
  13285. }
  13286. _this.uploadTexture( texture, slot );
  13287. return;
  13288. }
  13289. state.activeTexture( _gl.TEXTURE0 + slot );
  13290. state.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13291. };
  13292. function clampToMaxSize ( image, maxSize ) {
  13293. if ( image.width > maxSize || image.height > maxSize ) {
  13294. // Warning: Scaling through the canvas will only work with images that use
  13295. // premultiplied alpha.
  13296. var scale = maxSize / Math.max( image.width, image.height );
  13297. var canvas = document.createElement( 'canvas' );
  13298. canvas.width = Math.floor( image.width * scale );
  13299. canvas.height = Math.floor( image.height * scale );
  13300. var context = canvas.getContext( '2d' );
  13301. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  13302. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  13303. return canvas;
  13304. }
  13305. return image;
  13306. }
  13307. function setCubeTexture ( texture, slot ) {
  13308. if ( texture.image.length === 6 ) {
  13309. if ( texture.needsUpdate ) {
  13310. if ( ! texture.image.__webglTextureCube ) {
  13311. texture.addEventListener( 'dispose', onTextureDispose );
  13312. texture.image.__webglTextureCube = _gl.createTexture();
  13313. _this.info.memory.textures ++;
  13314. }
  13315. state.activeTexture( _gl.TEXTURE0 + slot );
  13316. state.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13317. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13318. var isCompressed = texture instanceof THREE.CompressedTexture;
  13319. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  13320. var cubeImage = [];
  13321. for ( var i = 0; i < 6; i ++ ) {
  13322. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  13323. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13324. } else {
  13325. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  13326. }
  13327. }
  13328. var image = cubeImage[ 0 ],
  13329. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  13330. glFormat = paramThreeToGL( texture.format ),
  13331. glType = paramThreeToGL( texture.type );
  13332. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13333. for ( var i = 0; i < 6; i ++ ) {
  13334. if ( ! isCompressed ) {
  13335. if ( isDataTexture ) {
  13336. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  13337. } else {
  13338. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13339. }
  13340. } else {
  13341. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13342. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13343. mipmap = mipmaps[ j ];
  13344. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  13345. if ( getCompressedTextureFormats().indexOf( glFormat ) > -1 ) {
  13346. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13347. } else {
  13348. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  13349. }
  13350. } else {
  13351. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13352. }
  13353. }
  13354. }
  13355. }
  13356. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13357. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13358. }
  13359. texture.needsUpdate = false;
  13360. if ( texture.onUpdate ) texture.onUpdate( texture );
  13361. } else {
  13362. state.activeTexture( _gl.TEXTURE0 + slot );
  13363. state.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13364. }
  13365. }
  13366. }
  13367. function setCubeTextureDynamic ( texture, slot ) {
  13368. state.activeTexture( _gl.TEXTURE0 + slot );
  13369. state.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13370. }
  13371. // Render targets
  13372. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13373. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13374. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13375. }
  13376. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13377. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13378. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13379. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13380. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13381. /* For some reason this is not working. Defaulting to RGBA4.
  13382. } else if ( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13383. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13384. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13385. */
  13386. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13387. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13388. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13389. } else {
  13390. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13391. }
  13392. }
  13393. this.setRenderTarget = function ( renderTarget ) {
  13394. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13395. if ( renderTarget && renderTarget.__webglFramebuffer === undefined ) {
  13396. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13397. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13398. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  13399. renderTarget.__webglTexture = _gl.createTexture();
  13400. _this.info.memory.textures ++;
  13401. // Setup texture, create render and frame buffers
  13402. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  13403. glFormat = paramThreeToGL( renderTarget.format ),
  13404. glType = paramThreeToGL( renderTarget.type );
  13405. if ( isCube ) {
  13406. renderTarget.__webglFramebuffer = [];
  13407. renderTarget.__webglRenderbuffer = [];
  13408. state.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13409. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13410. for ( var i = 0; i < 6; i ++ ) {
  13411. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13412. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13413. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13414. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13415. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13416. }
  13417. if ( renderTarget.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13418. } else {
  13419. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13420. if ( renderTarget.shareDepthFrom ) {
  13421. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  13422. } else {
  13423. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13424. }
  13425. state.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13426. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13427. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13428. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13429. if ( renderTarget.shareDepthFrom ) {
  13430. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13431. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13432. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13433. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  13434. }
  13435. } else {
  13436. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13437. }
  13438. if ( renderTarget.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13439. }
  13440. // Release everything
  13441. if ( isCube ) {
  13442. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13443. } else {
  13444. state.bindTexture( _gl.TEXTURE_2D, null );
  13445. }
  13446. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13447. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  13448. }
  13449. var framebuffer, width, height, vx, vy;
  13450. if ( renderTarget ) {
  13451. if ( isCube ) {
  13452. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13453. } else {
  13454. framebuffer = renderTarget.__webglFramebuffer;
  13455. }
  13456. width = renderTarget.width;
  13457. height = renderTarget.height;
  13458. vx = 0;
  13459. vy = 0;
  13460. } else {
  13461. framebuffer = null;
  13462. width = _viewportWidth;
  13463. height = _viewportHeight;
  13464. vx = _viewportX;
  13465. vy = _viewportY;
  13466. }
  13467. if ( framebuffer !== _currentFramebuffer ) {
  13468. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13469. _gl.viewport( vx, vy, width, height );
  13470. _currentFramebuffer = framebuffer;
  13471. }
  13472. _currentWidth = width;
  13473. _currentHeight = height;
  13474. };
  13475. this.readRenderTargetPixels = function( renderTarget, x, y, width, height, buffer ) {
  13476. if ( ! ( renderTarget instanceof THREE.WebGLRenderTarget ) ) {
  13477. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  13478. return;
  13479. }
  13480. if ( renderTarget.__webglFramebuffer ) {
  13481. if ( renderTarget.format !== THREE.RGBAFormat ) {
  13482. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA format. readPixels can read only RGBA format.' );
  13483. return;
  13484. }
  13485. var restore = false;
  13486. if ( renderTarget.__webglFramebuffer !== _currentFramebuffer ) {
  13487. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTarget.__webglFramebuffer );
  13488. restore = true;
  13489. }
  13490. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  13491. _gl.readPixels( x, y, width, height, _gl.RGBA, _gl.UNSIGNED_BYTE, buffer );
  13492. } else {
  13493. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  13494. }
  13495. if ( restore ) {
  13496. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  13497. }
  13498. }
  13499. };
  13500. function updateRenderTargetMipmap ( renderTarget ) {
  13501. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13502. state.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13503. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13504. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13505. } else {
  13506. state.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13507. _gl.generateMipmap( _gl.TEXTURE_2D );
  13508. state.bindTexture( _gl.TEXTURE_2D, null );
  13509. }
  13510. }
  13511. // Fallback filters for non-power-of-2 textures
  13512. function filterFallback ( f ) {
  13513. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13514. return _gl.NEAREST;
  13515. }
  13516. return _gl.LINEAR;
  13517. }
  13518. // Map three.js constants to WebGL constants
  13519. function paramThreeToGL ( p ) {
  13520. var extension;
  13521. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13522. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13523. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13524. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13525. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13526. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13527. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13528. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13529. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13530. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13531. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13532. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13533. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13534. if ( p === THREE.ByteType ) return _gl.BYTE;
  13535. if ( p === THREE.ShortType ) return _gl.SHORT;
  13536. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13537. if ( p === THREE.IntType ) return _gl.INT;
  13538. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13539. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13540. extension = extensions.get( 'OES_texture_half_float' );
  13541. if ( extension !== null ) {
  13542. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  13543. }
  13544. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13545. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13546. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13547. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13548. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13549. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13550. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13551. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13552. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13553. if ( p === THREE.OneFactor ) return _gl.ONE;
  13554. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13555. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13556. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13557. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13558. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13559. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13560. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13561. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13562. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13563. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  13564. if ( extension !== null ) {
  13565. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13566. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13567. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13568. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13569. }
  13570. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  13571. if ( extension !== null ) {
  13572. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  13573. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  13574. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  13575. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  13576. }
  13577. extension = extensions.get( 'EXT_blend_minmax' );
  13578. if ( extension !== null ) {
  13579. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  13580. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  13581. }
  13582. return 0;
  13583. }
  13584. // Allocations
  13585. function allocateBones ( object ) {
  13586. if ( _supportsBoneTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  13587. return 1024;
  13588. } else {
  13589. // default for when object is not specified
  13590. // ( for example when prebuilding shader to be used with multiple objects )
  13591. //
  13592. // - leave some extra space for other uniforms
  13593. // - limit here is ANGLE's 254 max uniform vectors
  13594. // (up to 54 should be safe)
  13595. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13596. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13597. var maxBones = nVertexMatrices;
  13598. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13599. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  13600. if ( maxBones < object.skeleton.bones.length ) {
  13601. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  13602. }
  13603. }
  13604. return maxBones;
  13605. }
  13606. }
  13607. function allocateLights( lights ) {
  13608. var dirLights = 0;
  13609. var pointLights = 0;
  13610. var spotLights = 0;
  13611. var hemiLights = 0;
  13612. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  13613. var light = lights[ l ];
  13614. if ( light.onlyShadow || light.visible === false ) continue;
  13615. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13616. if ( light instanceof THREE.PointLight ) pointLights ++;
  13617. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13618. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13619. }
  13620. return { 'directional': dirLights, 'point': pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13621. }
  13622. function allocateShadows( lights ) {
  13623. var maxShadows = 0;
  13624. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  13625. var light = lights[ l ];
  13626. if ( ! light.castShadow ) continue;
  13627. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13628. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13629. }
  13630. return maxShadows;
  13631. }
  13632. // DEPRECATED
  13633. this.initMaterial = function () {
  13634. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  13635. };
  13636. this.addPrePlugin = function () {
  13637. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  13638. };
  13639. this.addPostPlugin = function () {
  13640. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  13641. };
  13642. this.updateShadowMap = function () {
  13643. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  13644. };
  13645. Object.defineProperties( this, {
  13646. shadowMapEnabled: {
  13647. get: function () {
  13648. return shadowMap.enabled;
  13649. },
  13650. set: function ( value ) {
  13651. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  13652. shadowMap.enabled = value;
  13653. }
  13654. },
  13655. shadowMapType: {
  13656. get: function () {
  13657. return shadowMap.type;
  13658. },
  13659. set: function ( value ) {
  13660. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  13661. shadowMap.type = value;
  13662. }
  13663. },
  13664. shadowMapCullFace: {
  13665. get: function () {
  13666. return shadowMap.cullFace;
  13667. },
  13668. set: function ( value ) {
  13669. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  13670. shadowMap.cullFace = value;
  13671. }
  13672. },
  13673. shadowMapDebug: {
  13674. get: function () {
  13675. return shadowMap.debug;
  13676. },
  13677. set: function ( value ) {
  13678. console.warn( 'THREE.WebGLRenderer: .shadowMapDebug is now .shadowMap.debug.' );
  13679. shadowMap.debug = value;
  13680. }
  13681. },
  13682. shadowMapCascade: {
  13683. get: function () {
  13684. return shadowMap.cascade;
  13685. },
  13686. set: function ( value ) {
  13687. console.warn( 'THREE.WebGLRenderer: .shadowMapCascade is now .shadowMap.cascade.' );
  13688. shadowMap.cascade = value;
  13689. }
  13690. }
  13691. } );
  13692. };
  13693. // File:src/renderers/WebGLRenderTarget.js
  13694. /**
  13695. * @author szimek / https://github.com/szimek/
  13696. * @author alteredq / http://alteredqualia.com/
  13697. */
  13698. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13699. this.width = width;
  13700. this.height = height;
  13701. options = options || {};
  13702. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13703. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13704. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13705. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13706. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13707. this.offset = new THREE.Vector2( 0, 0 );
  13708. this.repeat = new THREE.Vector2( 1, 1 );
  13709. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13710. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13711. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13712. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13713. this.generateMipmaps = true;
  13714. this.shareDepthFrom = options.shareDepthFrom !== undefined ? options.shareDepthFrom : null;
  13715. };
  13716. THREE.WebGLRenderTarget.prototype = {
  13717. constructor: THREE.WebGLRenderTarget,
  13718. setSize: function ( width, height ) {
  13719. if ( this.width !== width || this.height !== height ) {
  13720. this.width = width;
  13721. this.height = height;
  13722. this.dispose();
  13723. }
  13724. },
  13725. clone: function () {
  13726. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13727. tmp.wrapS = this.wrapS;
  13728. tmp.wrapT = this.wrapT;
  13729. tmp.magFilter = this.magFilter;
  13730. tmp.minFilter = this.minFilter;
  13731. tmp.anisotropy = this.anisotropy;
  13732. tmp.offset.copy( this.offset );
  13733. tmp.repeat.copy( this.repeat );
  13734. tmp.format = this.format;
  13735. tmp.type = this.type;
  13736. tmp.depthBuffer = this.depthBuffer;
  13737. tmp.stencilBuffer = this.stencilBuffer;
  13738. tmp.generateMipmaps = this.generateMipmaps;
  13739. tmp.shareDepthFrom = this.shareDepthFrom;
  13740. return tmp;
  13741. },
  13742. dispose: function () {
  13743. this.dispatchEvent( { type: 'dispose' } );
  13744. }
  13745. };
  13746. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  13747. // File:src/renderers/WebGLRenderTargetCube.js
  13748. /**
  13749. * @author alteredq / http://alteredqualia.com
  13750. */
  13751. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13752. THREE.WebGLRenderTarget.call( this, width, height, options );
  13753. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13754. };
  13755. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13756. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  13757. // File:src/renderers/webgl/WebGLExtensions.js
  13758. /**
  13759. * @author mrdoob / http://mrdoob.com/
  13760. */
  13761. THREE.WebGLExtensions = function ( gl ) {
  13762. var extensions = {};
  13763. this.get = function ( name ) {
  13764. if ( extensions[ name ] !== undefined ) {
  13765. return extensions[ name ];
  13766. }
  13767. var extension;
  13768. switch ( name ) {
  13769. case 'EXT_texture_filter_anisotropic':
  13770. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13771. break;
  13772. case 'WEBGL_compressed_texture_s3tc':
  13773. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13774. break;
  13775. case 'WEBGL_compressed_texture_pvrtc':
  13776. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  13777. break;
  13778. default:
  13779. extension = gl.getExtension( name );
  13780. }
  13781. if ( extension === null ) {
  13782. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  13783. }
  13784. extensions[ name ] = extension;
  13785. return extension;
  13786. };
  13787. };
  13788. // File:src/renderers/webgl/WebGLGeometries.js
  13789. /**
  13790. * @author mrdoob / http://mrdoob.com/
  13791. */
  13792. THREE.WebGLGeometries = function ( gl, info ) {
  13793. var geometries = {};
  13794. this.get = function ( object ) {
  13795. var geometry = object.geometry;
  13796. if ( geometries[ geometry.id ] !== undefined ) {
  13797. return geometries[ geometry.id ];
  13798. }
  13799. geometry.addEventListener( 'dispose', onGeometryDispose );
  13800. if ( geometry instanceof THREE.BufferGeometry ) {
  13801. geometries[ geometry.id ] = geometry;
  13802. } else {
  13803. geometries[ geometry.id ] = new THREE.BufferGeometry().setFromObject( object );
  13804. }
  13805. info.memory.geometries ++;
  13806. return geometries[ geometry.id ];
  13807. };
  13808. function onGeometryDispose( event ) {
  13809. var geometry = event.target;
  13810. var buffergeometry = geometries[ geometry.id ];
  13811. for ( var name in buffergeometry.attributes ) {
  13812. var attribute = buffergeometry.attributes[ name ];
  13813. if ( attribute.buffer !== undefined ) {
  13814. gl.deleteBuffer( attribute.buffer );
  13815. delete attribute.buffer;
  13816. }
  13817. }
  13818. geometry.removeEventListener( 'dispose', onGeometryDispose );
  13819. delete geometries[ geometry.id ];
  13820. info.memory.geometries --;
  13821. }
  13822. };
  13823. // File:src/renderers/webgl/WebGLObjects.js
  13824. /**
  13825. * @author mrdoob / http://mrdoob.com/
  13826. */
  13827. THREE.WebGLObjects = function ( gl, info ) {
  13828. var objects = {};
  13829. var objectsImmediate = [];
  13830. var morphInfluences = new Float32Array( 8 );
  13831. var geometries = new THREE.WebGLGeometries( gl, info );
  13832. //
  13833. function onObjectRemoved( event ) {
  13834. var object = event.target;
  13835. object.traverse( function ( child ) {
  13836. child.removeEventListener( 'remove', onObjectRemoved );
  13837. removeObject( child );
  13838. } );
  13839. }
  13840. function removeObject( object ) {
  13841. if ( object instanceof THREE.Mesh ||
  13842. object instanceof THREE.PointCloud ||
  13843. object instanceof THREE.Line ) {
  13844. delete objects[ object.id ];
  13845. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13846. removeInstances( objectsImmediate, object );
  13847. }
  13848. delete object.__webglInit;
  13849. delete object._modelViewMatrix;
  13850. delete object._normalMatrix;
  13851. delete object.__webglActive;
  13852. }
  13853. function removeInstances( objlist, object ) {
  13854. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13855. if ( objlist[ o ].object === object ) {
  13856. objlist.splice( o, 1 );
  13857. }
  13858. }
  13859. }
  13860. //
  13861. this.objects = objects;
  13862. this.objectsImmediate = objectsImmediate;
  13863. this.geometries = geometries;
  13864. this.init = function ( object ) {
  13865. if ( object.__webglInit === undefined ) {
  13866. object.__webglInit = true;
  13867. object._modelViewMatrix = new THREE.Matrix4();
  13868. object._normalMatrix = new THREE.Matrix3();
  13869. object.addEventListener( 'removed', onObjectRemoved );
  13870. }
  13871. if ( object.__webglActive === undefined ) {
  13872. object.__webglActive = true;
  13873. if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.PointCloud ) {
  13874. objects[ object.id ] = {
  13875. id: object.id,
  13876. object: object,
  13877. z: 0
  13878. };
  13879. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13880. objectsImmediate.push( {
  13881. id: null,
  13882. object: object,
  13883. opaque: null,
  13884. transparent: null,
  13885. z: 0
  13886. } );
  13887. }
  13888. }
  13889. };
  13890. function numericalSort ( a, b ) {
  13891. return b[ 0 ] - a[ 0 ];
  13892. }
  13893. function updateObject( object ) {
  13894. var geometry = geometries.get( object );
  13895. if ( object.geometry.dynamic === true ) {
  13896. geometry.updateFromObject( object );
  13897. }
  13898. // morph targets
  13899. if ( object.morphTargetInfluences !== undefined ) {
  13900. var activeInfluences = [];
  13901. var morphTargetInfluences = object.morphTargetInfluences;
  13902. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  13903. var influence = morphTargetInfluences[ i ];
  13904. activeInfluences.push( [ influence, i ] );
  13905. }
  13906. activeInfluences.sort( numericalSort );
  13907. if ( activeInfluences.length > 8 ) {
  13908. activeInfluences.length = 8;
  13909. }
  13910. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  13911. morphInfluences[ i ] = activeInfluences[ i ][ 0 ];
  13912. var attribute = geometry.morphAttributes[ activeInfluences[ i ][ 1 ] ];
  13913. geometry.addAttribute( 'morphTarget' + i, attribute );
  13914. }
  13915. var material = object.material;
  13916. if ( material.program !== undefined ) {
  13917. var uniforms = material.program.getUniforms();
  13918. if ( uniforms.morphTargetInfluences !== null ) {
  13919. gl.uniform1fv( uniforms.morphTargetInfluences, morphInfluences );
  13920. }
  13921. } else {
  13922. console.warn( 'TOFIX: material.program is undefined' );
  13923. }
  13924. }
  13925. //
  13926. var attributes = geometry.attributes;
  13927. for ( var name in attributes ) {
  13928. var attribute = attributes[ name ];
  13929. var bufferType = ( name === 'index' ) ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;
  13930. var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
  13931. if ( data.buffer === undefined ) {
  13932. data.buffer = gl.createBuffer();
  13933. gl.bindBuffer( bufferType, data.buffer );
  13934. var usage = gl.STATIC_DRAW;
  13935. if ( data instanceof THREE.DynamicBufferAttribute
  13936. || ( data instanceof THREE.InstancedBufferAttribute && data.dynamic === true )
  13937. || ( data instanceof THREE.InterleavedBuffer && data.dynamic === true ) ) {
  13938. usage = gl.DYNAMIC_DRAW;
  13939. }
  13940. gl.bufferData( bufferType, data.array, usage );
  13941. data.needsUpdate = false;
  13942. } else if ( data.needsUpdate === true ) {
  13943. gl.bindBuffer( bufferType, data.buffer );
  13944. if ( data.updateRange === undefined || data.updateRange.count === -1 ) { // Not using update ranges
  13945. gl.bufferSubData( bufferType, 0, data.array );
  13946. } else if ( data.updateRange.count === 0 ) {
  13947. console.error( 'THREE.WebGLRenderer.updateObject: using updateRange for THREE.DynamicBufferAttribute and marked as needsUpdate but count is 0, ensure you are using set methods or updating manually.' );
  13948. } else {
  13949. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  13950. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  13951. data.updateRange.count = 0; // reset range
  13952. }
  13953. data.needsUpdate = false;
  13954. }
  13955. }
  13956. };
  13957. this.update = function ( renderList ) {
  13958. for ( var i = 0, ul = renderList.length; i < ul; i++ ) {
  13959. var object = renderList[i].object;
  13960. if ( object.material.visible !== false ) {
  13961. updateObject( object );
  13962. }
  13963. }
  13964. };
  13965. };
  13966. // File:src/renderers/webgl/WebGLProgram.js
  13967. THREE.WebGLProgram = ( function () {
  13968. var programIdCount = 0;
  13969. function generateDefines( defines ) {
  13970. var chunks = [];
  13971. for ( var name in defines ) {
  13972. var value = defines[ name ];
  13973. if ( value === false ) continue;
  13974. chunks.push( '#define ' + name + ' ' + value );
  13975. }
  13976. return chunks.join( '\n' );
  13977. }
  13978. function fetchUniformLocations( gl, program, identifiers ) {
  13979. var uniforms = {};
  13980. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  13981. for ( var i = 0; i < n; i ++ ) {
  13982. var info = gl.getActiveUniform( program , i );
  13983. var name = info.name;
  13984. var location = gl.getUniformLocation( program, name );
  13985. //console.log("THREE.WebGLProgram: ACTIVE UNIFORM:", name);
  13986. var suffixPos = name.lastIndexOf( '[0]' );
  13987. if ( suffixPos !== -1 && suffixPos === name.length - 3 ) {
  13988. uniforms[ name.substr( 0, suffixPos ) ] = location;
  13989. }
  13990. uniforms[ name ] = location;
  13991. }
  13992. return uniforms;
  13993. }
  13994. function fetchAttributeLocations( gl, program, identifiers ) {
  13995. var attributes = {};
  13996. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  13997. for ( var i = 0; i < n; i ++ ) {
  13998. var info = gl.getActiveAttrib( program , i );
  13999. var name = info.name;
  14000. //console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name);
  14001. attributes[ name ] = gl.getAttribLocation( program, name );
  14002. }
  14003. return attributes;
  14004. }
  14005. function filterEmptyLine( string ) {
  14006. return string !== '';
  14007. }
  14008. return function ( renderer, code, material, parameters ) {
  14009. var gl = renderer.context;
  14010. var defines = material.defines;
  14011. var uniforms = material.__webglShader.uniforms;
  14012. var attributes = material.attributes;
  14013. var vertexShader = material.__webglShader.vertexShader;
  14014. var fragmentShader = material.__webglShader.fragmentShader;
  14015. var index0AttributeName = material.index0AttributeName;
  14016. /*
  14017. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  14018. // programs with morphTargets displace position out of attribute 0
  14019. index0AttributeName = 'position';
  14020. }
  14021. */
  14022. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14023. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14024. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14025. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14026. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14027. }
  14028. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14029. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14030. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14031. if ( parameters.envMap ) {
  14032. switch ( material.envMap.mapping ) {
  14033. case THREE.CubeReflectionMapping:
  14034. case THREE.CubeRefractionMapping:
  14035. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14036. break;
  14037. case THREE.EquirectangularReflectionMapping:
  14038. case THREE.EquirectangularRefractionMapping:
  14039. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14040. break;
  14041. case THREE.SphericalReflectionMapping:
  14042. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14043. break;
  14044. }
  14045. switch ( material.envMap.mapping ) {
  14046. case THREE.CubeRefractionMapping:
  14047. case THREE.EquirectangularRefractionMapping:
  14048. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14049. break;
  14050. }
  14051. switch ( material.combine ) {
  14052. case THREE.MultiplyOperation:
  14053. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14054. break;
  14055. case THREE.MixOperation:
  14056. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14057. break;
  14058. case THREE.AddOperation:
  14059. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14060. break;
  14061. }
  14062. }
  14063. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14064. // console.log( 'building new program ' );
  14065. //
  14066. var customDefines = generateDefines( defines );
  14067. //
  14068. var program = gl.createProgram();
  14069. var prefixVertex, prefixFragment;
  14070. if ( material instanceof THREE.RawShaderMaterial ) {
  14071. prefixVertex = '';
  14072. prefixFragment = '';
  14073. } else {
  14074. prefixVertex = [
  14075. 'precision ' + parameters.precision + ' float;',
  14076. 'precision ' + parameters.precision + ' int;',
  14077. '#define SHADER_NAME ' + material.__webglShader.name,
  14078. customDefines,
  14079. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14080. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  14081. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14082. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14083. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14084. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14085. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14086. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14087. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14088. '#define MAX_BONES ' + parameters.maxBones,
  14089. parameters.map ? '#define USE_MAP' : '',
  14090. parameters.envMap ? '#define USE_ENVMAP' : '',
  14091. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14092. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14093. parameters.aoMap ? '#define USE_AOMAP' : '',
  14094. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14095. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14096. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14097. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14098. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14099. parameters.vertexColors ? '#define USE_COLOR' : '',
  14100. parameters.flatShading ? '#define FLAT_SHADED': '',
  14101. parameters.skinning ? '#define USE_SKINNING' : '',
  14102. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14103. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14104. parameters.morphNormals ? '#define USE_MORPHNORMALS' : '',
  14105. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14106. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14107. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14108. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14109. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14110. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14111. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14112. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14113. parameters.logarithmicDepthBuffer && renderer.extensions.get('EXT_frag_depth') ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14114. 'uniform mat4 modelMatrix;',
  14115. 'uniform mat4 modelViewMatrix;',
  14116. 'uniform mat4 projectionMatrix;',
  14117. 'uniform mat4 viewMatrix;',
  14118. 'uniform mat3 normalMatrix;',
  14119. 'uniform vec3 cameraPosition;',
  14120. 'attribute vec3 position;',
  14121. 'attribute vec3 normal;',
  14122. 'attribute vec2 uv;',
  14123. '#ifdef USE_COLOR',
  14124. ' attribute vec3 color;',
  14125. '#endif',
  14126. '#ifdef USE_MORPHTARGETS',
  14127. ' attribute vec3 morphTarget0;',
  14128. ' attribute vec3 morphTarget1;',
  14129. ' attribute vec3 morphTarget2;',
  14130. ' attribute vec3 morphTarget3;',
  14131. ' #ifdef USE_MORPHNORMALS',
  14132. ' attribute vec3 morphNormal0;',
  14133. ' attribute vec3 morphNormal1;',
  14134. ' attribute vec3 morphNormal2;',
  14135. ' attribute vec3 morphNormal3;',
  14136. ' #else',
  14137. ' attribute vec3 morphTarget4;',
  14138. ' attribute vec3 morphTarget5;',
  14139. ' attribute vec3 morphTarget6;',
  14140. ' attribute vec3 morphTarget7;',
  14141. ' #endif',
  14142. '#endif',
  14143. '#ifdef USE_SKINNING',
  14144. ' attribute vec4 skinIndex;',
  14145. ' attribute vec4 skinWeight;',
  14146. '#endif',
  14147. '\n'
  14148. ].filter( filterEmptyLine ).join( '\n' );
  14149. prefixFragment = [
  14150. ( parameters.bumpMap || parameters.normalMap || parameters.flatShading || material.derivatives ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14151. 'precision ' + parameters.precision + ' float;',
  14152. 'precision ' + parameters.precision + ' int;',
  14153. '#define SHADER_NAME ' + material.__webglShader.name,
  14154. customDefines,
  14155. '#define MAX_DIR_LIGHTS ' + parameters.maxDirLights,
  14156. '#define MAX_POINT_LIGHTS ' + parameters.maxPointLights,
  14157. '#define MAX_SPOT_LIGHTS ' + parameters.maxSpotLights,
  14158. '#define MAX_HEMI_LIGHTS ' + parameters.maxHemiLights,
  14159. '#define MAX_SHADOWS ' + parameters.maxShadows,
  14160. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  14161. renderer.gammaInput ? '#define GAMMA_INPUT' : '',
  14162. renderer.gammaOutput ? '#define GAMMA_OUTPUT' : '',
  14163. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14164. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14165. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14166. parameters.map ? '#define USE_MAP' : '',
  14167. parameters.envMap ? '#define USE_ENVMAP' : '',
  14168. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  14169. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14170. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  14171. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14172. parameters.aoMap ? '#define USE_AOMAP' : '',
  14173. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14174. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14175. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14176. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14177. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14178. parameters.vertexColors ? '#define USE_COLOR' : '',
  14179. parameters.flatShading ? '#define FLAT_SHADED': '',
  14180. parameters.metal ? '#define METAL' : '',
  14181. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14182. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14183. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14184. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14185. parameters.shadowMapDebug ? '#define SHADOWMAP_DEBUG' : '',
  14186. parameters.shadowMapCascade ? '#define SHADOWMAP_CASCADE' : '',
  14187. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14188. parameters.logarithmicDepthBuffer && renderer.extensions.get('EXT_frag_depth') ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14189. 'uniform mat4 viewMatrix;',
  14190. 'uniform vec3 cameraPosition;',
  14191. '\n'
  14192. ].filter( filterEmptyLine ).join( '\n' );
  14193. }
  14194. var vertexGlsl = prefixVertex + vertexShader;
  14195. var fragmentGlsl = prefixFragment + fragmentShader;
  14196. var glVertexShader = new THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  14197. var glFragmentShader = new THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  14198. gl.attachShader( program, glVertexShader );
  14199. gl.attachShader( program, glFragmentShader );
  14200. if ( index0AttributeName !== undefined ) {
  14201. // Force a particular attribute to index 0.
  14202. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14203. // And, color, for example is often automatically bound to index 0 so disabling it
  14204. gl.bindAttribLocation( program, 0, index0AttributeName );
  14205. }
  14206. gl.linkProgram( program );
  14207. var programLogInfo = gl.getProgramInfoLog( program );
  14208. var vertexErrorLogInfo = gl.getShaderInfoLog( glVertexShader );
  14209. var fragmentErrorLogInfo = gl.getShaderInfoLog( glFragmentShader );
  14210. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  14211. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLogInfo, vertexErrorLogInfo, fragmentErrorLogInfo );
  14212. }
  14213. if ( programLogInfo !== '' ) {
  14214. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLogInfo );
  14215. }
  14216. // clean up
  14217. gl.deleteShader( glVertexShader );
  14218. gl.deleteShader( glFragmentShader );
  14219. // set up caching for uniform locations
  14220. var getUniforms = function() { return this._cachedUniforms; };
  14221. this.getUniforms = function() {
  14222. // fetch, cache, and next time just use a dumb accessor
  14223. var uniforms = fetchUniformLocations( gl, program );
  14224. this._cachedUniforms = uniforms;
  14225. this.getUniforms = getUniforms;
  14226. return uniforms;
  14227. };
  14228. // set up caching for attribute locations
  14229. var getAttributes = function() { return this._cachedAttributes; };
  14230. this.getAttributes = function() {
  14231. var attributes = fetchAttributeLocations( gl, program );
  14232. this._cachedAttributes = attributes;
  14233. this.getAttributes = getAttributes;
  14234. return attributes;
  14235. };
  14236. // DEPRECATED
  14237. Object.defineProperties( this, {
  14238. uniforms: {
  14239. get: function() {
  14240. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  14241. return this.getUniforms();
  14242. }
  14243. },
  14244. attributes: {
  14245. get: function() {
  14246. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  14247. return this.getAttributes();
  14248. }
  14249. }
  14250. });
  14251. //
  14252. this.id = programIdCount ++;
  14253. this.code = code;
  14254. this.usedTimes = 1;
  14255. this.program = program;
  14256. this.vertexShader = glVertexShader;
  14257. this.fragmentShader = glFragmentShader;
  14258. return this;
  14259. };
  14260. } )();
  14261. // File:src/renderers/webgl/WebGLShader.js
  14262. THREE.WebGLShader = ( function () {
  14263. var addLineNumbers = function ( string ) {
  14264. var lines = string.split( '\n' );
  14265. for ( var i = 0; i < lines.length; i ++ ) {
  14266. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14267. }
  14268. return lines.join( '\n' );
  14269. };
  14270. return function ( gl, type, string ) {
  14271. var shader = gl.createShader( type );
  14272. gl.shaderSource( shader, string );
  14273. gl.compileShader( shader );
  14274. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  14275. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14276. }
  14277. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14278. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14279. }
  14280. // --enable-privileged-webgl-extension
  14281. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14282. return shader;
  14283. };
  14284. } )();
  14285. // File:src/renderers/webgl/WebGLShadowMap.js
  14286. /**
  14287. * @author alteredq / http://alteredqualia.com/
  14288. * @author mrdoob / http://mrdoob.com/
  14289. */
  14290. THREE.WebGLShadowMap = function ( _renderer, _lights, _objects ) {
  14291. var _gl = _renderer.context,
  14292. _state = _renderer.state,
  14293. _frustum = new THREE.Frustum(),
  14294. _projScreenMatrix = new THREE.Matrix4(),
  14295. _min = new THREE.Vector3(),
  14296. _max = new THREE.Vector3(),
  14297. _webglObjects = _objects.objects,
  14298. _webglObjectsImmediate = _objects.objectsImmediate,
  14299. _matrixPosition = new THREE.Vector3(),
  14300. _renderList = [];
  14301. // init
  14302. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  14303. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  14304. var _depthMaterial = new THREE.ShaderMaterial( {
  14305. uniforms: depthUniforms,
  14306. vertexShader: depthShader.vertexShader,
  14307. fragmentShader: depthShader.fragmentShader
  14308. } );
  14309. var _depthMaterialMorph = new THREE.ShaderMaterial( {
  14310. uniforms: depthUniforms,
  14311. vertexShader: depthShader.vertexShader,
  14312. fragmentShader: depthShader.fragmentShader,
  14313. morphTargets: true
  14314. } );
  14315. var _depthMaterialSkin = new THREE.ShaderMaterial( {
  14316. uniforms: depthUniforms,
  14317. vertexShader: depthShader.vertexShader,
  14318. fragmentShader: depthShader.fragmentShader,
  14319. skinning: true
  14320. } );
  14321. var _depthMaterialMorphSkin = new THREE.ShaderMaterial( {
  14322. uniforms: depthUniforms,
  14323. vertexShader: depthShader.vertexShader,
  14324. fragmentShader: depthShader.fragmentShader,
  14325. morphTargets: true,
  14326. skinning: true
  14327. } );
  14328. _depthMaterial._shadowPass = true;
  14329. _depthMaterialMorph._shadowPass = true;
  14330. _depthMaterialSkin._shadowPass = true;
  14331. _depthMaterialMorphSkin._shadowPass = true;
  14332. //
  14333. var scope = this;
  14334. this.enabled = false;
  14335. this.type = THREE.PCFShadowMap;
  14336. this.cullFace = THREE.CullFaceFront;
  14337. this.debug = false;
  14338. this.cascade = false;
  14339. this.render = function ( scene, camera ) {
  14340. if ( scope.enabled === false ) return;
  14341. var i, il, j, jl, n,
  14342. shadowMap, shadowMatrix, shadowCamera,
  14343. webglObject, object, material, light,
  14344. lights = [],
  14345. k = 0,
  14346. fog = null;
  14347. // set GL state for depth map
  14348. _gl.clearColor( 1, 1, 1, 1 );
  14349. _state.setBlend( false );
  14350. _gl.enable( _gl.CULL_FACE );
  14351. _gl.frontFace( _gl.CCW );
  14352. if ( scope.cullFace === THREE.CullFaceFront ) {
  14353. _gl.cullFace( _gl.FRONT );
  14354. } else {
  14355. _gl.cullFace( _gl.BACK );
  14356. }
  14357. _state.setDepthTest( true );
  14358. // preprocess lights
  14359. // - skip lights that are not casting shadows
  14360. // - create virtual lights for cascaded shadow maps
  14361. for ( i = 0, il = _lights.length; i < il; i ++ ) {
  14362. light = _lights[ i ];
  14363. if ( ! light.castShadow ) continue;
  14364. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  14365. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  14366. var virtualLight;
  14367. if ( ! light.shadowCascadeArray[ n ] ) {
  14368. virtualLight = createVirtualLight( light, n );
  14369. virtualLight.originalCamera = camera;
  14370. var gyro = new THREE.Gyroscope();
  14371. gyro.position.copy( light.shadowCascadeOffset );
  14372. gyro.add( virtualLight );
  14373. gyro.add( virtualLight.target );
  14374. camera.add( gyro );
  14375. light.shadowCascadeArray[ n ] = virtualLight;
  14376. //console.log( "Created virtualLight", virtualLight );
  14377. } else {
  14378. virtualLight = light.shadowCascadeArray[ n ];
  14379. }
  14380. updateVirtualLight( light, n );
  14381. lights[ k ] = virtualLight;
  14382. k ++;
  14383. }
  14384. } else {
  14385. lights[ k ] = light;
  14386. k ++;
  14387. }
  14388. }
  14389. // render depth map
  14390. for ( i = 0, il = lights.length; i < il; i ++ ) {
  14391. light = lights[ i ];
  14392. if ( ! light.shadowMap ) {
  14393. var shadowFilter = THREE.LinearFilter;
  14394. if ( scope.type === THREE.PCFSoftShadowMap ) {
  14395. shadowFilter = THREE.NearestFilter;
  14396. }
  14397. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  14398. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  14399. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  14400. light.shadowMatrix = new THREE.Matrix4();
  14401. }
  14402. if ( ! light.shadowCamera ) {
  14403. if ( light instanceof THREE.SpotLight ) {
  14404. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  14405. } else if ( light instanceof THREE.DirectionalLight ) {
  14406. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  14407. } else {
  14408. console.error( "THREE.ShadowMapPlugin: Unsupported light type for shadow", light );
  14409. continue;
  14410. }
  14411. scene.add( light.shadowCamera );
  14412. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14413. }
  14414. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  14415. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  14416. scene.add( light.cameraHelper );
  14417. }
  14418. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  14419. updateShadowCamera( camera, light );
  14420. }
  14421. shadowMap = light.shadowMap;
  14422. shadowMatrix = light.shadowMatrix;
  14423. shadowCamera = light.shadowCamera;
  14424. //
  14425. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  14426. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  14427. shadowCamera.lookAt( _matrixPosition );
  14428. shadowCamera.updateMatrixWorld();
  14429. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  14430. //
  14431. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  14432. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  14433. // compute shadow matrix
  14434. shadowMatrix.set(
  14435. 0.5, 0.0, 0.0, 0.5,
  14436. 0.0, 0.5, 0.0, 0.5,
  14437. 0.0, 0.0, 0.5, 0.5,
  14438. 0.0, 0.0, 0.0, 1.0
  14439. );
  14440. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  14441. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  14442. // update camera matrices and frustum
  14443. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  14444. _frustum.setFromMatrix( _projScreenMatrix );
  14445. // render shadow map
  14446. _renderer.setRenderTarget( shadowMap );
  14447. _renderer.clear();
  14448. // set object matrices & frustum culling
  14449. _renderList.length = 0;
  14450. projectObject( scene, shadowCamera );
  14451. // render regular objects
  14452. var objectMaterial, useMorphing, useSkinning;
  14453. for ( j = 0, jl = _renderList.length; j < jl; j ++ ) {
  14454. webglObject = _renderList[ j ];
  14455. object = webglObject.object;
  14456. // culling is overridden globally for all objects
  14457. // while rendering depth map
  14458. // need to deal with MeshFaceMaterial somehow
  14459. // in that case just use the first of material.materials for now
  14460. // (proper solution would require to break objects by materials
  14461. // similarly to regular rendering and then set corresponding
  14462. // depth materials per each chunk instead of just once per object)
  14463. objectMaterial = getObjectMaterial( object );
  14464. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  14465. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  14466. if ( object.customDepthMaterial ) {
  14467. material = object.customDepthMaterial;
  14468. } else if ( useSkinning ) {
  14469. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  14470. } else if ( useMorphing ) {
  14471. material = _depthMaterialMorph;
  14472. } else {
  14473. material = _depthMaterial;
  14474. }
  14475. _renderer.setMaterialFaces( objectMaterial );
  14476. _renderer.renderBufferDirect( shadowCamera, _lights, fog, material, object );
  14477. }
  14478. // set matrices and render immediate objects
  14479. for ( j = 0, jl = _webglObjectsImmediate.length; j < jl; j ++ ) {
  14480. webglObject = _webglObjectsImmediate[ j ];
  14481. object = webglObject.object;
  14482. if ( object.visible && object.castShadow ) {
  14483. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  14484. _renderer.renderImmediateObject( shadowCamera, _lights, fog, _depthMaterial, object );
  14485. }
  14486. }
  14487. }
  14488. // restore GL state
  14489. var clearColor = _renderer.getClearColor(),
  14490. clearAlpha = _renderer.getClearAlpha();
  14491. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  14492. _state.setBlend( true );
  14493. if ( scope.cullFace === THREE.CullFaceFront ) {
  14494. _gl.cullFace( _gl.BACK );
  14495. }
  14496. _renderer.resetGLState();
  14497. };
  14498. function projectObject( object, shadowCamera ) {
  14499. if ( object.visible === true ) {
  14500. var webglObject = _objects.objects[ object.id ];
  14501. if ( webglObject && object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  14502. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  14503. _renderList.push( webglObject );
  14504. }
  14505. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  14506. projectObject( object.children[ i ], shadowCamera );
  14507. }
  14508. }
  14509. }
  14510. function createVirtualLight( light, cascade ) {
  14511. var virtualLight = new THREE.DirectionalLight();
  14512. virtualLight.isVirtual = true;
  14513. virtualLight.onlyShadow = true;
  14514. virtualLight.castShadow = true;
  14515. virtualLight.shadowCameraNear = light.shadowCameraNear;
  14516. virtualLight.shadowCameraFar = light.shadowCameraFar;
  14517. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  14518. virtualLight.shadowCameraRight = light.shadowCameraRight;
  14519. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  14520. virtualLight.shadowCameraTop = light.shadowCameraTop;
  14521. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  14522. virtualLight.shadowDarkness = light.shadowDarkness;
  14523. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  14524. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  14525. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  14526. virtualLight.pointsWorld = [];
  14527. virtualLight.pointsFrustum = [];
  14528. var pointsWorld = virtualLight.pointsWorld,
  14529. pointsFrustum = virtualLight.pointsFrustum;
  14530. for ( var i = 0; i < 8; i ++ ) {
  14531. pointsWorld[ i ] = new THREE.Vector3();
  14532. pointsFrustum[ i ] = new THREE.Vector3();
  14533. }
  14534. var nearZ = light.shadowCascadeNearZ[ cascade ];
  14535. var farZ = light.shadowCascadeFarZ[ cascade ];
  14536. pointsFrustum[ 0 ].set( - 1, - 1, nearZ );
  14537. pointsFrustum[ 1 ].set( 1, - 1, nearZ );
  14538. pointsFrustum[ 2 ].set( - 1, 1, nearZ );
  14539. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  14540. pointsFrustum[ 4 ].set( - 1, - 1, farZ );
  14541. pointsFrustum[ 5 ].set( 1, - 1, farZ );
  14542. pointsFrustum[ 6 ].set( - 1, 1, farZ );
  14543. pointsFrustum[ 7 ].set( 1, 1, farZ );
  14544. return virtualLight;
  14545. }
  14546. // Synchronize virtual light with the original light
  14547. function updateVirtualLight( light, cascade ) {
  14548. var virtualLight = light.shadowCascadeArray[ cascade ];
  14549. virtualLight.position.copy( light.position );
  14550. virtualLight.target.position.copy( light.target.position );
  14551. virtualLight.lookAt( virtualLight.target );
  14552. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  14553. virtualLight.shadowDarkness = light.shadowDarkness;
  14554. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  14555. var nearZ = light.shadowCascadeNearZ[ cascade ];
  14556. var farZ = light.shadowCascadeFarZ[ cascade ];
  14557. var pointsFrustum = virtualLight.pointsFrustum;
  14558. pointsFrustum[ 0 ].z = nearZ;
  14559. pointsFrustum[ 1 ].z = nearZ;
  14560. pointsFrustum[ 2 ].z = nearZ;
  14561. pointsFrustum[ 3 ].z = nearZ;
  14562. pointsFrustum[ 4 ].z = farZ;
  14563. pointsFrustum[ 5 ].z = farZ;
  14564. pointsFrustum[ 6 ].z = farZ;
  14565. pointsFrustum[ 7 ].z = farZ;
  14566. }
  14567. // Fit shadow camera's ortho frustum to camera frustum
  14568. function updateShadowCamera( camera, light ) {
  14569. var shadowCamera = light.shadowCamera,
  14570. pointsFrustum = light.pointsFrustum,
  14571. pointsWorld = light.pointsWorld;
  14572. _min.set( Infinity, Infinity, Infinity );
  14573. _max.set( - Infinity, - Infinity, - Infinity );
  14574. for ( var i = 0; i < 8; i ++ ) {
  14575. var p = pointsWorld[ i ];
  14576. p.copy( pointsFrustum[ i ] );
  14577. p.unproject( camera );
  14578. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  14579. if ( p.x < _min.x ) _min.x = p.x;
  14580. if ( p.x > _max.x ) _max.x = p.x;
  14581. if ( p.y < _min.y ) _min.y = p.y;
  14582. if ( p.y > _max.y ) _max.y = p.y;
  14583. if ( p.z < _min.z ) _min.z = p.z;
  14584. if ( p.z > _max.z ) _max.z = p.z;
  14585. }
  14586. shadowCamera.left = _min.x;
  14587. shadowCamera.right = _max.x;
  14588. shadowCamera.top = _max.y;
  14589. shadowCamera.bottom = _min.y;
  14590. // can't really fit near/far
  14591. //shadowCamera.near = _min.z;
  14592. //shadowCamera.far = _max.z;
  14593. shadowCamera.updateProjectionMatrix();
  14594. }
  14595. // For the moment just ignore objects that have multiple materials with different animation methods
  14596. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  14597. function getObjectMaterial( object ) {
  14598. return object.material instanceof THREE.MeshFaceMaterial
  14599. ? object.material.materials[ 0 ]
  14600. : object.material;
  14601. }
  14602. };
  14603. // File:src/renderers/webgl/WebGLState.js
  14604. /**
  14605. * @author mrdoob / http://mrdoob.com/
  14606. */
  14607. THREE.WebGLState = function ( gl, paramThreeToGL ) {
  14608. var _this = this;
  14609. var newAttributes = new Uint8Array( 16 );
  14610. var enabledAttributes = new Uint8Array( 16 );
  14611. var currentBlend = null;
  14612. var currentBlending = null;
  14613. var currentBlendEquation = null;
  14614. var currentBlendSrc = null;
  14615. var currentBlendDst = null;
  14616. var currentBlendEquationAlpha = null;
  14617. var currentBlendSrcAlpha = null;
  14618. var currentBlendDstAlpha = null;
  14619. var currentDepthFunc = null;
  14620. var currentDepthTest = null;
  14621. var currentDepthWrite = null;
  14622. var currentColorWrite = null;
  14623. var currentDoubleSided = null;
  14624. var currentFlipSided = null;
  14625. var currentLineWidth = null;
  14626. var currentPolygonOffset = null;
  14627. var currentPolygonOffsetFactor = null;
  14628. var currentPolygonOffsetUnits = null;
  14629. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  14630. var currentTextureSlot = undefined;
  14631. var currentBoundTextures = {};
  14632. this.init = function () {
  14633. gl.clearColor( 0, 0, 0, 1 );
  14634. gl.clearDepth( 1 );
  14635. gl.clearStencil( 0 );
  14636. gl.enable( gl.DEPTH_TEST );
  14637. gl.depthFunc( gl.LEQUAL );
  14638. gl.frontFace( gl.CCW );
  14639. gl.cullFace( gl.BACK );
  14640. gl.enable( gl.CULL_FACE );
  14641. gl.enable( gl.BLEND );
  14642. gl.blendEquation( gl.FUNC_ADD );
  14643. gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );
  14644. };
  14645. this.initAttributes = function () {
  14646. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  14647. newAttributes[ i ] = 0;
  14648. }
  14649. };
  14650. this.enableAttribute = function ( attribute ) {
  14651. newAttributes[ attribute ] = 1;
  14652. if ( enabledAttributes[ attribute ] === 0 ) {
  14653. gl.enableVertexAttribArray( attribute );
  14654. enabledAttributes[ attribute ] = 1;
  14655. }
  14656. };
  14657. this.disableUnusedAttributes = function () {
  14658. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  14659. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  14660. gl.disableVertexAttribArray( i );
  14661. enabledAttributes[ i ] = 0;
  14662. }
  14663. }
  14664. };
  14665. this.setBlend = function ( blend ) {
  14666. if ( blend !== currentBlend ) {
  14667. if ( blend ) {
  14668. gl.enable( gl.BLEND );
  14669. } else {
  14670. gl.disable( gl.BLEND );
  14671. }
  14672. currentBlend = blend;
  14673. }
  14674. };
  14675. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha ) {
  14676. if ( blending !== currentBlending ) {
  14677. if ( blending === THREE.NoBlending ) {
  14678. this.setBlend( false );
  14679. } else if ( blending === THREE.AdditiveBlending ) {
  14680. this.setBlend( true );
  14681. gl.blendEquation( gl.FUNC_ADD );
  14682. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  14683. } else if ( blending === THREE.SubtractiveBlending ) {
  14684. // TODO: Find blendFuncSeparate() combination
  14685. this.setBlend( true );
  14686. gl.blendEquation( gl.FUNC_ADD );
  14687. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  14688. } else if ( blending === THREE.MultiplyBlending ) {
  14689. // TODO: Find blendFuncSeparate() combination
  14690. this.setBlend( true );
  14691. gl.blendEquation( gl.FUNC_ADD );
  14692. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  14693. } else if ( blending === THREE.CustomBlending ) {
  14694. this.setBlend( true );
  14695. } else {
  14696. this.setBlend( true );
  14697. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  14698. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  14699. }
  14700. currentBlending = blending;
  14701. }
  14702. if ( blending === THREE.CustomBlending ) {
  14703. blendEquationAlpha = blendEquationAlpha || blendEquation;
  14704. blendSrcAlpha = blendSrcAlpha || blendSrc;
  14705. blendDstAlpha = blendDstAlpha || blendDst;
  14706. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  14707. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  14708. currentBlendEquation = blendEquation;
  14709. currentBlendEquationAlpha = blendEquationAlpha;
  14710. }
  14711. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  14712. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  14713. currentBlendSrc = blendSrc;
  14714. currentBlendDst = blendDst;
  14715. currentBlendSrcAlpha = blendSrcAlpha;
  14716. currentBlendDstAlpha = blendDstAlpha;
  14717. }
  14718. } else {
  14719. currentBlendEquation = null;
  14720. currentBlendSrc = null;
  14721. currentBlendDst = null;
  14722. currentBlendEquationAlpha = null;
  14723. currentBlendSrcAlpha = null;
  14724. currentBlendDstAlpha = null;
  14725. }
  14726. };
  14727. this.setDepthFunc = function ( depthFunc ) {
  14728. if ( currentDepthFunc !== depthFunc ) {
  14729. if ( depthFunc ) {
  14730. switch ( depthFunc ) {
  14731. case THREE.NeverDepth:
  14732. gl.depthFunc( gl.NEVER );
  14733. break;
  14734. case THREE.AlwaysDepth:
  14735. gl.depthFunc( gl.ALWAYS );
  14736. break;
  14737. case THREE.LessDepth:
  14738. gl.depthFunc( gl.LESS );
  14739. break;
  14740. case THREE.LessEqualDepth:
  14741. gl.depthFunc( gl.LEQUAL );
  14742. break;
  14743. case THREE.EqualDepth:
  14744. gl.depthFunc( gl.EQUAL );
  14745. break;
  14746. case THREE.GreaterEqualDepth:
  14747. gl.depthFunc( gl.GEQUAL );
  14748. break;
  14749. case THREE.GreaterDepth:
  14750. gl.depthFunc( gl.GREATER );
  14751. break;
  14752. case THREE.NotEqualDepth:
  14753. gl.depthFunc( gl.NOTEQUAL );
  14754. break;
  14755. default:
  14756. gl.depthFunc( gl.LEQUAL );
  14757. }
  14758. } else {
  14759. gl.depthFunc( gl.LEQUAL );
  14760. }
  14761. currentDepthFunc = depthFunc;
  14762. }
  14763. };
  14764. this.setDepthTest = function ( depthTest ) {
  14765. if ( currentDepthTest !== depthTest ) {
  14766. if ( depthTest ) {
  14767. gl.enable( gl.DEPTH_TEST );
  14768. } else {
  14769. gl.disable( gl.DEPTH_TEST );
  14770. }
  14771. currentDepthTest = depthTest;
  14772. }
  14773. };
  14774. this.setDepthWrite = function ( depthWrite ) {
  14775. if ( currentDepthWrite !== depthWrite ) {
  14776. gl.depthMask( depthWrite );
  14777. currentDepthWrite = depthWrite;
  14778. }
  14779. };
  14780. this.setColorWrite = function ( colorWrite ) {
  14781. if ( currentColorWrite !== colorWrite ) {
  14782. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  14783. currentColorWrite = colorWrite;
  14784. }
  14785. };
  14786. this.setDoubleSided = function ( doubleSided ) {
  14787. if ( currentDoubleSided !== doubleSided ) {
  14788. if ( doubleSided ) {
  14789. gl.disable( gl.CULL_FACE );
  14790. } else {
  14791. gl.enable( gl.CULL_FACE );
  14792. }
  14793. currentDoubleSided = doubleSided;
  14794. }
  14795. };
  14796. this.setFlipSided = function ( flipSided ) {
  14797. if ( currentFlipSided !== flipSided ) {
  14798. if ( flipSided ) {
  14799. gl.frontFace( gl.CW );
  14800. } else {
  14801. gl.frontFace( gl.CCW );
  14802. }
  14803. currentFlipSided = flipSided;
  14804. }
  14805. };
  14806. this.setLineWidth = function ( width ) {
  14807. if ( width !== currentLineWidth ) {
  14808. gl.lineWidth( width );
  14809. currentLineWidth = width;
  14810. }
  14811. };
  14812. this.setPolygonOffset = function ( polygonoffset, factor, units ) {
  14813. if ( currentPolygonOffset !== polygonoffset ) {
  14814. if ( polygonoffset ) {
  14815. gl.enable( gl.POLYGON_OFFSET_FILL );
  14816. } else {
  14817. gl.disable( gl.POLYGON_OFFSET_FILL );
  14818. }
  14819. currentPolygonOffset = polygonoffset;
  14820. }
  14821. if ( polygonoffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  14822. gl.polygonOffset( factor, units );
  14823. currentPolygonOffsetFactor = factor;
  14824. currentPolygonOffsetUnits = units;
  14825. }
  14826. };
  14827. // texture
  14828. this.activeTexture = function ( webglSlot ) {
  14829. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  14830. if ( currentTextureSlot !== webglSlot ) {
  14831. gl.activeTexture( webglSlot );
  14832. currentTextureSlot = webglSlot;
  14833. }
  14834. }
  14835. this.bindTexture = function ( webglType, webglTexture ) {
  14836. if ( currentTextureSlot === undefined ) {
  14837. _this.activeTexture();
  14838. }
  14839. var boundTexture = currentBoundTextures[currentTextureSlot];
  14840. if ( boundTexture === undefined ) {
  14841. boundTexture = { type: undefined, texture: undefined };
  14842. currentBoundTextures[currentTextureSlot] = boundTexture;
  14843. }
  14844. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  14845. gl.bindTexture( webglType, webglTexture );
  14846. boundTexture.type = webglType;
  14847. boundTexture.texture = webglTexture;
  14848. }
  14849. };
  14850. this.compressedTexImage2D = function () {
  14851. try {
  14852. gl.compressedTexImage2D.apply( gl, arguments );
  14853. } catch ( error ) {
  14854. console.error( error );
  14855. }
  14856. };
  14857. this.texImage2D = function () {
  14858. try {
  14859. gl.texImage2D.apply( gl, arguments );
  14860. } catch ( error ) {
  14861. console.error( error );
  14862. }
  14863. };
  14864. //
  14865. this.reset = function () {
  14866. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  14867. if ( enabledAttributes[ i ] === 1 ) {
  14868. gl.disableVertexAttribArray( i );
  14869. enabledAttributes[ i ] = 0;
  14870. }
  14871. }
  14872. currentBlending = null;
  14873. currentDepthTest = null;
  14874. currentDepthWrite = null;
  14875. currentColorWrite = null;
  14876. currentDoubleSided = null;
  14877. currentFlipSided = null;
  14878. };
  14879. };
  14880. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  14881. /**
  14882. * @author mikael emtinger / http://gomo.se/
  14883. * @author alteredq / http://alteredqualia.com/
  14884. */
  14885. THREE.LensFlarePlugin = function ( renderer, flares ) {
  14886. var gl = renderer.context;
  14887. var state = renderer.state;
  14888. var vertexBuffer, elementBuffer;
  14889. var program, attributes, uniforms;
  14890. var hasVertexTexture;
  14891. var tempTexture, occlusionTexture;
  14892. var init = function () {
  14893. var vertices = new Float32Array( [
  14894. -1, -1, 0, 0,
  14895. 1, -1, 1, 0,
  14896. 1, 1, 1, 1,
  14897. -1, 1, 0, 1
  14898. ] );
  14899. var faces = new Uint16Array( [
  14900. 0, 1, 2,
  14901. 0, 2, 3
  14902. ] );
  14903. // buffers
  14904. vertexBuffer = gl.createBuffer();
  14905. elementBuffer = gl.createBuffer();
  14906. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  14907. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  14908. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  14909. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  14910. // textures
  14911. tempTexture = gl.createTexture();
  14912. occlusionTexture = gl.createTexture();
  14913. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  14914. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  14915. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14916. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14917. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14918. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14919. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  14920. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  14921. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  14922. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  14923. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  14924. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  14925. hasVertexTexture = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) > 0;
  14926. var shader;
  14927. if ( hasVertexTexture ) {
  14928. shader = {
  14929. vertexShader: [
  14930. "uniform lowp int renderType;",
  14931. "uniform vec3 screenPosition;",
  14932. "uniform vec2 scale;",
  14933. "uniform float rotation;",
  14934. "uniform sampler2D occlusionMap;",
  14935. "attribute vec2 position;",
  14936. "attribute vec2 uv;",
  14937. "varying vec2 vUV;",
  14938. "varying float vVisibility;",
  14939. "void main() {",
  14940. "vUV = uv;",
  14941. "vec2 pos = position;",
  14942. "if( renderType == 2 ) {",
  14943. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  14944. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  14945. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  14946. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  14947. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  14948. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  14949. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  14950. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  14951. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  14952. "vVisibility = visibility.r / 9.0;",
  14953. "vVisibility *= 1.0 - visibility.g / 9.0;",
  14954. "vVisibility *= visibility.b / 9.0;",
  14955. "vVisibility *= 1.0 - visibility.a / 9.0;",
  14956. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  14957. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  14958. "}",
  14959. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  14960. "}"
  14961. ].join( "\n" ),
  14962. fragmentShader: [
  14963. "uniform lowp int renderType;",
  14964. "uniform sampler2D map;",
  14965. "uniform float opacity;",
  14966. "uniform vec3 color;",
  14967. "varying vec2 vUV;",
  14968. "varying float vVisibility;",
  14969. "void main() {",
  14970. // pink square
  14971. "if( renderType == 0 ) {",
  14972. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  14973. // restore
  14974. "} else if( renderType == 1 ) {",
  14975. "gl_FragColor = texture2D( map, vUV );",
  14976. // flare
  14977. "} else {",
  14978. "vec4 texture = texture2D( map, vUV );",
  14979. "texture.a *= opacity * vVisibility;",
  14980. "gl_FragColor = texture;",
  14981. "gl_FragColor.rgb *= color;",
  14982. "}",
  14983. "}"
  14984. ].join( "\n" )
  14985. };
  14986. } else {
  14987. shader = {
  14988. vertexShader: [
  14989. "uniform lowp int renderType;",
  14990. "uniform vec3 screenPosition;",
  14991. "uniform vec2 scale;",
  14992. "uniform float rotation;",
  14993. "attribute vec2 position;",
  14994. "attribute vec2 uv;",
  14995. "varying vec2 vUV;",
  14996. "void main() {",
  14997. "vUV = uv;",
  14998. "vec2 pos = position;",
  14999. "if( renderType == 2 ) {",
  15000. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  15001. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  15002. "}",
  15003. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  15004. "}"
  15005. ].join( "\n" ),
  15006. fragmentShader: [
  15007. "precision mediump float;",
  15008. "uniform lowp int renderType;",
  15009. "uniform sampler2D map;",
  15010. "uniform sampler2D occlusionMap;",
  15011. "uniform float opacity;",
  15012. "uniform vec3 color;",
  15013. "varying vec2 vUV;",
  15014. "void main() {",
  15015. // pink square
  15016. "if( renderType == 0 ) {",
  15017. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  15018. // restore
  15019. "} else if( renderType == 1 ) {",
  15020. "gl_FragColor = texture2D( map, vUV );",
  15021. // flare
  15022. "} else {",
  15023. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  15024. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  15025. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  15026. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  15027. "visibility = ( 1.0 - visibility / 4.0 );",
  15028. "vec4 texture = texture2D( map, vUV );",
  15029. "texture.a *= opacity * visibility;",
  15030. "gl_FragColor = texture;",
  15031. "gl_FragColor.rgb *= color;",
  15032. "}",
  15033. "}"
  15034. ].join( "\n" )
  15035. };
  15036. }
  15037. program = createProgram( shader );
  15038. attributes = {
  15039. vertex: gl.getAttribLocation ( program, "position" ),
  15040. uv: gl.getAttribLocation ( program, "uv" )
  15041. };
  15042. uniforms = {
  15043. renderType: gl.getUniformLocation( program, "renderType" ),
  15044. map: gl.getUniformLocation( program, "map" ),
  15045. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  15046. opacity: gl.getUniformLocation( program, "opacity" ),
  15047. color: gl.getUniformLocation( program, "color" ),
  15048. scale: gl.getUniformLocation( program, "scale" ),
  15049. rotation: gl.getUniformLocation( program, "rotation" ),
  15050. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  15051. };
  15052. };
  15053. /*
  15054. * Render lens flares
  15055. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  15056. * reads these back and calculates occlusion.
  15057. */
  15058. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  15059. if ( flares.length === 0 ) return;
  15060. var tempPosition = new THREE.Vector3();
  15061. var invAspect = viewportHeight / viewportWidth,
  15062. halfViewportWidth = viewportWidth * 0.5,
  15063. halfViewportHeight = viewportHeight * 0.5;
  15064. var size = 16 / viewportHeight,
  15065. scale = new THREE.Vector2( size * invAspect, size );
  15066. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  15067. screenPositionPixels = new THREE.Vector2( 1, 1 );
  15068. if ( program === undefined ) {
  15069. init();
  15070. }
  15071. gl.useProgram( program );
  15072. state.initAttributes();
  15073. state.enableAttribute( attributes.vertex );
  15074. state.enableAttribute( attributes.uv );
  15075. state.disableUnusedAttributes();
  15076. // loop through all lens flares to update their occlusion and positions
  15077. // setup gl and common used attribs/uniforms
  15078. gl.uniform1i( uniforms.occlusionMap, 0 );
  15079. gl.uniform1i( uniforms.map, 1 );
  15080. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15081. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  15082. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15083. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15084. gl.disable( gl.CULL_FACE );
  15085. gl.depthMask( false );
  15086. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  15087. size = 16 / viewportHeight;
  15088. scale.set( size * invAspect, size );
  15089. // calc object screen position
  15090. var flare = flares[ i ];
  15091. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  15092. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  15093. tempPosition.applyProjection( camera.projectionMatrix );
  15094. // setup arrays for gl programs
  15095. screenPosition.copy( tempPosition );
  15096. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  15097. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  15098. // screen cull
  15099. if ( hasVertexTexture || (
  15100. screenPositionPixels.x > 0 &&
  15101. screenPositionPixels.x < viewportWidth &&
  15102. screenPositionPixels.y > 0 &&
  15103. screenPositionPixels.y < viewportHeight ) ) {
  15104. // save current RGB to temp texture
  15105. state.activeTexture( gl.TEXTURE0 );
  15106. state.bindTexture( gl.TEXTURE_2D, null );
  15107. state.activeTexture( gl.TEXTURE1 );
  15108. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  15109. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  15110. // render pink quad
  15111. gl.uniform1i( uniforms.renderType, 0 );
  15112. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  15113. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  15114. state.setBlend( false );
  15115. gl.enable( gl.DEPTH_TEST );
  15116. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15117. // copy result to occlusionMap
  15118. state.activeTexture( gl.TEXTURE0 );
  15119. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  15120. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  15121. // restore graphics
  15122. gl.uniform1i( uniforms.renderType, 1 );
  15123. gl.disable( gl.DEPTH_TEST );
  15124. state.activeTexture( gl.TEXTURE1 );
  15125. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  15126. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15127. // update object positions
  15128. flare.positionScreen.copy( screenPosition );
  15129. if ( flare.customUpdateCallback ) {
  15130. flare.customUpdateCallback( flare );
  15131. } else {
  15132. flare.updateLensFlares();
  15133. }
  15134. // render flares
  15135. gl.uniform1i( uniforms.renderType, 2 );
  15136. state.setBlend( true );
  15137. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  15138. var sprite = flare.lensFlares[ j ];
  15139. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  15140. screenPosition.x = sprite.x;
  15141. screenPosition.y = sprite.y;
  15142. screenPosition.z = sprite.z;
  15143. size = sprite.size * sprite.scale / viewportHeight;
  15144. scale.x = size * invAspect;
  15145. scale.y = size;
  15146. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  15147. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  15148. gl.uniform1f( uniforms.rotation, sprite.rotation );
  15149. gl.uniform1f( uniforms.opacity, sprite.opacity );
  15150. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  15151. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  15152. renderer.setTexture( sprite.texture, 1 );
  15153. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15154. }
  15155. }
  15156. }
  15157. }
  15158. // restore gl
  15159. gl.enable( gl.CULL_FACE );
  15160. gl.enable( gl.DEPTH_TEST );
  15161. gl.depthMask( true );
  15162. renderer.resetGLState();
  15163. };
  15164. function createProgram ( shader ) {
  15165. var program = gl.createProgram();
  15166. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15167. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15168. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  15169. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  15170. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  15171. gl.compileShader( fragmentShader );
  15172. gl.compileShader( vertexShader );
  15173. gl.attachShader( program, fragmentShader );
  15174. gl.attachShader( program, vertexShader );
  15175. gl.linkProgram( program );
  15176. return program;
  15177. }
  15178. };
  15179. // File:src/renderers/webgl/plugins/SpritePlugin.js
  15180. /**
  15181. * @author mikael emtinger / http://gomo.se/
  15182. * @author alteredq / http://alteredqualia.com/
  15183. */
  15184. THREE.SpritePlugin = function ( renderer, sprites ) {
  15185. var gl = renderer.context;
  15186. var state = renderer.state;
  15187. var vertexBuffer, elementBuffer;
  15188. var program, attributes, uniforms;
  15189. var texture;
  15190. // decompose matrixWorld
  15191. var spritePosition = new THREE.Vector3();
  15192. var spriteRotation = new THREE.Quaternion();
  15193. var spriteScale = new THREE.Vector3();
  15194. var init = function () {
  15195. var vertices = new Float32Array( [
  15196. - 0.5, - 0.5, 0, 0,
  15197. 0.5, - 0.5, 1, 0,
  15198. 0.5, 0.5, 1, 1,
  15199. - 0.5, 0.5, 0, 1
  15200. ] );
  15201. var faces = new Uint16Array( [
  15202. 0, 1, 2,
  15203. 0, 2, 3
  15204. ] );
  15205. vertexBuffer = gl.createBuffer();
  15206. elementBuffer = gl.createBuffer();
  15207. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15208. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  15209. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15210. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  15211. program = createProgram();
  15212. attributes = {
  15213. position: gl.getAttribLocation ( program, 'position' ),
  15214. uv: gl.getAttribLocation ( program, 'uv' )
  15215. };
  15216. uniforms = {
  15217. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  15218. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  15219. rotation: gl.getUniformLocation( program, 'rotation' ),
  15220. scale: gl.getUniformLocation( program, 'scale' ),
  15221. color: gl.getUniformLocation( program, 'color' ),
  15222. map: gl.getUniformLocation( program, 'map' ),
  15223. opacity: gl.getUniformLocation( program, 'opacity' ),
  15224. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  15225. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  15226. fogType: gl.getUniformLocation( program, 'fogType' ),
  15227. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  15228. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  15229. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  15230. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  15231. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  15232. };
  15233. var canvas = document.createElement( 'canvas' );
  15234. canvas.width = 8;
  15235. canvas.height = 8;
  15236. var context = canvas.getContext( '2d' );
  15237. context.fillStyle = 'white';
  15238. context.fillRect( 0, 0, 8, 8 );
  15239. texture = new THREE.Texture( canvas );
  15240. texture.needsUpdate = true;
  15241. };
  15242. this.render = function ( scene, camera ) {
  15243. if ( sprites.length === 0 ) return;
  15244. // setup gl
  15245. if ( program === undefined ) {
  15246. init();
  15247. }
  15248. gl.useProgram( program );
  15249. state.initAttributes();
  15250. state.enableAttribute( attributes.position );
  15251. state.enableAttribute( attributes.uv );
  15252. state.disableUnusedAttributes();
  15253. gl.disable( gl.CULL_FACE );
  15254. state.setBlend( true );
  15255. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  15256. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  15257. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  15258. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  15259. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  15260. state.activeTexture( gl.TEXTURE0 );
  15261. gl.uniform1i( uniforms.map, 0 );
  15262. var oldFogType = 0;
  15263. var sceneFogType = 0;
  15264. var fog = scene.fog;
  15265. if ( fog ) {
  15266. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  15267. if ( fog instanceof THREE.Fog ) {
  15268. gl.uniform1f( uniforms.fogNear, fog.near );
  15269. gl.uniform1f( uniforms.fogFar, fog.far );
  15270. gl.uniform1i( uniforms.fogType, 1 );
  15271. oldFogType = 1;
  15272. sceneFogType = 1;
  15273. } else if ( fog instanceof THREE.FogExp2 ) {
  15274. gl.uniform1f( uniforms.fogDensity, fog.density );
  15275. gl.uniform1i( uniforms.fogType, 2 );
  15276. oldFogType = 2;
  15277. sceneFogType = 2;
  15278. }
  15279. } else {
  15280. gl.uniform1i( uniforms.fogType, 0 );
  15281. oldFogType = 0;
  15282. sceneFogType = 0;
  15283. }
  15284. // update positions and sort
  15285. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15286. var sprite = sprites[ i ];
  15287. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  15288. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  15289. }
  15290. sprites.sort( painterSortStable );
  15291. // render all sprites
  15292. var scale = [];
  15293. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  15294. var sprite = sprites[ i ];
  15295. var material = sprite.material;
  15296. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  15297. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  15298. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  15299. scale[ 0 ] = spriteScale.x;
  15300. scale[ 1 ] = spriteScale.y;
  15301. var fogType = 0;
  15302. if ( scene.fog && material.fog ) {
  15303. fogType = sceneFogType;
  15304. }
  15305. if ( oldFogType !== fogType ) {
  15306. gl.uniform1i( uniforms.fogType, fogType );
  15307. oldFogType = fogType;
  15308. }
  15309. if ( material.map !== null ) {
  15310. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  15311. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  15312. } else {
  15313. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  15314. gl.uniform2f( uniforms.uvScale, 1, 1 );
  15315. }
  15316. gl.uniform1f( uniforms.opacity, material.opacity );
  15317. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  15318. gl.uniform1f( uniforms.rotation, material.rotation );
  15319. gl.uniform2fv( uniforms.scale, scale );
  15320. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  15321. state.setDepthTest( material.depthTest );
  15322. state.setDepthWrite( material.depthWrite );
  15323. if ( material.map && material.map.image && material.map.image.width ) {
  15324. renderer.setTexture( material.map, 0 );
  15325. } else {
  15326. renderer.setTexture( texture, 0 );
  15327. }
  15328. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  15329. }
  15330. // restore gl
  15331. gl.enable( gl.CULL_FACE );
  15332. renderer.resetGLState();
  15333. };
  15334. function createProgram () {
  15335. var program = gl.createProgram();
  15336. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  15337. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  15338. gl.shaderSource( vertexShader, [
  15339. 'precision ' + renderer.getPrecision() + ' float;',
  15340. 'uniform mat4 modelViewMatrix;',
  15341. 'uniform mat4 projectionMatrix;',
  15342. 'uniform float rotation;',
  15343. 'uniform vec2 scale;',
  15344. 'uniform vec2 uvOffset;',
  15345. 'uniform vec2 uvScale;',
  15346. 'attribute vec2 position;',
  15347. 'attribute vec2 uv;',
  15348. 'varying vec2 vUV;',
  15349. 'void main() {',
  15350. 'vUV = uvOffset + uv * uvScale;',
  15351. 'vec2 alignedPosition = position * scale;',
  15352. 'vec2 rotatedPosition;',
  15353. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  15354. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  15355. 'vec4 finalPosition;',
  15356. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  15357. 'finalPosition.xy += rotatedPosition;',
  15358. 'finalPosition = projectionMatrix * finalPosition;',
  15359. 'gl_Position = finalPosition;',
  15360. '}'
  15361. ].join( '\n' ) );
  15362. gl.shaderSource( fragmentShader, [
  15363. 'precision ' + renderer.getPrecision() + ' float;',
  15364. 'uniform vec3 color;',
  15365. 'uniform sampler2D map;',
  15366. 'uniform float opacity;',
  15367. 'uniform int fogType;',
  15368. 'uniform vec3 fogColor;',
  15369. 'uniform float fogDensity;',
  15370. 'uniform float fogNear;',
  15371. 'uniform float fogFar;',
  15372. 'uniform float alphaTest;',
  15373. 'varying vec2 vUV;',
  15374. 'void main() {',
  15375. 'vec4 texture = texture2D( map, vUV );',
  15376. 'if ( texture.a < alphaTest ) discard;',
  15377. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  15378. 'if ( fogType > 0 ) {',
  15379. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  15380. 'float fogFactor = 0.0;',
  15381. 'if ( fogType == 1 ) {',
  15382. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  15383. '} else {',
  15384. 'const float LOG2 = 1.442695;',
  15385. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  15386. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  15387. '}',
  15388. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  15389. '}',
  15390. '}'
  15391. ].join( '\n' ) );
  15392. gl.compileShader( vertexShader );
  15393. gl.compileShader( fragmentShader );
  15394. gl.attachShader( program, vertexShader );
  15395. gl.attachShader( program, fragmentShader );
  15396. gl.linkProgram( program );
  15397. return program;
  15398. }
  15399. function painterSortStable ( a, b ) {
  15400. if ( a.z !== b.z ) {
  15401. return b.z - a.z;
  15402. } else {
  15403. return b.id - a.id;
  15404. }
  15405. }
  15406. };
  15407. // File:src/extras/GeometryUtils.js
  15408. /**
  15409. * @author mrdoob / http://mrdoob.com/
  15410. */
  15411. THREE.GeometryUtils = {
  15412. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  15413. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  15414. var matrix;
  15415. if ( geometry2 instanceof THREE.Mesh ) {
  15416. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  15417. matrix = geometry2.matrix;
  15418. geometry2 = geometry2.geometry;
  15419. }
  15420. geometry1.merge( geometry2, matrix, materialIndexOffset );
  15421. },
  15422. center: function ( geometry ) {
  15423. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  15424. return geometry.center();
  15425. }
  15426. };
  15427. // File:src/extras/ImageUtils.js
  15428. /**
  15429. * @author alteredq / http://alteredqualia.com/
  15430. * @author mrdoob / http://mrdoob.com/
  15431. * @author Daosheng Mu / https://github.com/DaoshengMu/
  15432. */
  15433. THREE.ImageUtils = {
  15434. crossOrigin: undefined,
  15435. loadTexture: function ( url, mapping, onLoad, onError ) {
  15436. var loader = new THREE.ImageLoader();
  15437. loader.crossOrigin = this.crossOrigin;
  15438. var texture = new THREE.Texture( undefined, mapping );
  15439. loader.load( url, function ( image ) {
  15440. texture.image = image;
  15441. texture.needsUpdate = true;
  15442. if ( onLoad ) onLoad( texture );
  15443. }, undefined, function ( event ) {
  15444. if ( onError ) onError( event );
  15445. } );
  15446. texture.sourceFile = url;
  15447. return texture;
  15448. },
  15449. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15450. var images = [];
  15451. var loader = new THREE.ImageLoader();
  15452. loader.crossOrigin = this.crossOrigin;
  15453. var texture = new THREE.CubeTexture( images, mapping );
  15454. // no flipping needed for cube textures
  15455. texture.flipY = false;
  15456. var loaded = 0;
  15457. var loadTexture = function ( i ) {
  15458. loader.load( array[ i ], function ( image ) {
  15459. texture.images[ i ] = image;
  15460. loaded += 1;
  15461. if ( loaded === 6 ) {
  15462. texture.needsUpdate = true;
  15463. if ( onLoad ) onLoad( texture );
  15464. }
  15465. }, undefined, onError );
  15466. };
  15467. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15468. loadTexture( i );
  15469. }
  15470. return texture;
  15471. },
  15472. loadCompressedTexture: function () {
  15473. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' )
  15474. },
  15475. loadCompressedTextureCube: function () {
  15476. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' )
  15477. },
  15478. getNormalMap: function ( image, depth ) {
  15479. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15480. var cross = function ( a, b ) {
  15481. 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 ] ];
  15482. };
  15483. var subtract = function ( a, b ) {
  15484. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15485. };
  15486. var normalize = function ( a ) {
  15487. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15488. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15489. };
  15490. depth = depth | 1;
  15491. var width = image.width;
  15492. var height = image.height;
  15493. var canvas = document.createElement( 'canvas' );
  15494. canvas.width = width;
  15495. canvas.height = height;
  15496. var context = canvas.getContext( '2d' );
  15497. context.drawImage( image, 0, 0 );
  15498. var data = context.getImageData( 0, 0, width, height ).data;
  15499. var imageData = context.createImageData( width, height );
  15500. var output = imageData.data;
  15501. for ( var x = 0; x < width; x ++ ) {
  15502. for ( var y = 0; y < height; y ++ ) {
  15503. var ly = y - 1 < 0 ? 0 : y - 1;
  15504. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15505. var lx = x - 1 < 0 ? 0 : x - 1;
  15506. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15507. var points = [];
  15508. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15509. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15510. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15511. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15512. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15513. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15514. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15515. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15516. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15517. var normals = [];
  15518. var num_points = points.length;
  15519. for ( var i = 0; i < num_points; i ++ ) {
  15520. var v1 = points[ i ];
  15521. var v2 = points[ ( i + 1 ) % num_points ];
  15522. v1 = subtract( v1, origin );
  15523. v2 = subtract( v2, origin );
  15524. normals.push( normalize( cross( v1, v2 ) ) );
  15525. }
  15526. var normal = [ 0, 0, 0 ];
  15527. for ( var i = 0; i < normals.length; i ++ ) {
  15528. normal[ 0 ] += normals[ i ][ 0 ];
  15529. normal[ 1 ] += normals[ i ][ 1 ];
  15530. normal[ 2 ] += normals[ i ][ 2 ];
  15531. }
  15532. normal[ 0 ] /= normals.length;
  15533. normal[ 1 ] /= normals.length;
  15534. normal[ 2 ] /= normals.length;
  15535. var idx = ( y * width + x ) * 4;
  15536. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15537. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15538. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15539. output[ idx + 3 ] = 255;
  15540. }
  15541. }
  15542. context.putImageData( imageData, 0, 0 );
  15543. return canvas;
  15544. },
  15545. generateDataTexture: function ( width, height, color ) {
  15546. var size = width * height;
  15547. var data = new Uint8Array( 3 * size );
  15548. var r = Math.floor( color.r * 255 );
  15549. var g = Math.floor( color.g * 255 );
  15550. var b = Math.floor( color.b * 255 );
  15551. for ( var i = 0; i < size; i ++ ) {
  15552. data[ i * 3 ] = r;
  15553. data[ i * 3 + 1 ] = g;
  15554. data[ i * 3 + 2 ] = b;
  15555. }
  15556. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15557. texture.needsUpdate = true;
  15558. return texture;
  15559. }
  15560. };
  15561. // File:src/extras/SceneUtils.js
  15562. /**
  15563. * @author alteredq / http://alteredqualia.com/
  15564. */
  15565. THREE.SceneUtils = {
  15566. createMultiMaterialObject: function ( geometry, materials ) {
  15567. var group = new THREE.Object3D();
  15568. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15569. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15570. }
  15571. return group;
  15572. },
  15573. detach: function ( child, parent, scene ) {
  15574. child.applyMatrix( parent.matrixWorld );
  15575. parent.remove( child );
  15576. scene.add( child );
  15577. },
  15578. attach: function ( child, scene, parent ) {
  15579. var matrixWorldInverse = new THREE.Matrix4();
  15580. matrixWorldInverse.getInverse( parent.matrixWorld );
  15581. child.applyMatrix( matrixWorldInverse );
  15582. scene.remove( child );
  15583. parent.add( child );
  15584. }
  15585. };
  15586. // File:src/extras/FontUtils.js
  15587. /**
  15588. * @author zz85 / http://www.lab4games.net/zz85/blog
  15589. * @author alteredq / http://alteredqualia.com/
  15590. *
  15591. * For Text operations in three.js (See TextGeometry)
  15592. *
  15593. * It uses techniques used in:
  15594. *
  15595. * Triangulation ported from AS3
  15596. * Simple Polygon Triangulation
  15597. * http://actionsnippet.com/?p=1462
  15598. *
  15599. * A Method to triangulate shapes with holes
  15600. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15601. *
  15602. */
  15603. THREE.FontUtils = {
  15604. faces: {},
  15605. // Just for now. face[weight][style]
  15606. face: 'helvetiker',
  15607. weight: 'normal',
  15608. style: 'normal',
  15609. size: 150,
  15610. divisions: 10,
  15611. getFace: function () {
  15612. try {
  15613. return this.faces[ this.face.toLowerCase() ][ this.weight ][ this.style ];
  15614. } catch (e) {
  15615. throw "The font " + this.face + " with " + this.weight + " weight and " + this.style + " style is missing."
  15616. }
  15617. },
  15618. loadFace: function ( data ) {
  15619. var family = data.familyName.toLowerCase();
  15620. var ThreeFont = this;
  15621. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15622. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15623. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15624. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15625. return data;
  15626. },
  15627. drawText: function ( text ) {
  15628. // RenderText
  15629. var i,
  15630. face = this.getFace(),
  15631. scale = this.size / face.resolution,
  15632. offset = 0,
  15633. chars = String( text ).split( '' ),
  15634. length = chars.length;
  15635. var fontPaths = [];
  15636. for ( i = 0; i < length; i ++ ) {
  15637. var path = new THREE.Path();
  15638. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15639. offset += ret.offset;
  15640. fontPaths.push( ret.path );
  15641. }
  15642. // get the width
  15643. var width = offset / 2;
  15644. //
  15645. // for ( p = 0; p < allPts.length; p++ ) {
  15646. //
  15647. // allPts[ p ].x -= width;
  15648. //
  15649. // }
  15650. //var extract = this.extractPoints( allPts, characterPts );
  15651. //extract.contour = allPts;
  15652. //extract.paths = fontPaths;
  15653. //extract.offset = width;
  15654. return { paths: fontPaths, offset: width };
  15655. },
  15656. extractGlyphPoints: function ( c, face, scale, offset, path ) {
  15657. var pts = [];
  15658. var i, i2, divisions,
  15659. outline, action, length,
  15660. scaleX, scaleY,
  15661. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15662. laste,
  15663. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15664. if ( ! glyph ) return;
  15665. if ( glyph.o ) {
  15666. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15667. length = outline.length;
  15668. scaleX = scale;
  15669. scaleY = scale;
  15670. for ( i = 0; i < length; ) {
  15671. action = outline[ i ++ ];
  15672. //console.log( action );
  15673. switch ( action ) {
  15674. case 'm':
  15675. // Move To
  15676. x = outline[ i ++ ] * scaleX + offset;
  15677. y = outline[ i ++ ] * scaleY;
  15678. path.moveTo( x, y );
  15679. break;
  15680. case 'l':
  15681. // Line To
  15682. x = outline[ i ++ ] * scaleX + offset;
  15683. y = outline[ i ++ ] * scaleY;
  15684. path.lineTo( x, y );
  15685. break;
  15686. case 'q':
  15687. // QuadraticCurveTo
  15688. cpx = outline[ i ++ ] * scaleX + offset;
  15689. cpy = outline[ i ++ ] * scaleY;
  15690. cpx1 = outline[ i ++ ] * scaleX + offset;
  15691. cpy1 = outline[ i ++ ] * scaleY;
  15692. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  15693. laste = pts[ pts.length - 1 ];
  15694. if ( laste ) {
  15695. cpx0 = laste.x;
  15696. cpy0 = laste.y;
  15697. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15698. var t = i2 / divisions;
  15699. THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15700. THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15701. }
  15702. }
  15703. break;
  15704. case 'b':
  15705. // Cubic Bezier Curve
  15706. cpx = outline[ i ++ ] * scaleX + offset;
  15707. cpy = outline[ i ++ ] * scaleY;
  15708. cpx1 = outline[ i ++ ] * scaleX + offset;
  15709. cpy1 = outline[ i ++ ] * scaleY;
  15710. cpx2 = outline[ i ++ ] * scaleX + offset;
  15711. cpy2 = outline[ i ++ ] * scaleY;
  15712. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  15713. laste = pts[ pts.length - 1 ];
  15714. if ( laste ) {
  15715. cpx0 = laste.x;
  15716. cpy0 = laste.y;
  15717. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15718. var t = i2 / divisions;
  15719. THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15720. THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15721. }
  15722. }
  15723. break;
  15724. }
  15725. }
  15726. }
  15727. return { offset: glyph.ha * scale, path:path };
  15728. }
  15729. };
  15730. THREE.FontUtils.generateShapes = function ( text, parameters ) {
  15731. // Parameters
  15732. parameters = parameters || {};
  15733. var size = parameters.size !== undefined ? parameters.size : 100;
  15734. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments : 4;
  15735. var font = parameters.font !== undefined ? parameters.font : 'helvetiker';
  15736. var weight = parameters.weight !== undefined ? parameters.weight : 'normal';
  15737. var style = parameters.style !== undefined ? parameters.style : 'normal';
  15738. THREE.FontUtils.size = size;
  15739. THREE.FontUtils.divisions = curveSegments;
  15740. THREE.FontUtils.face = font;
  15741. THREE.FontUtils.weight = weight;
  15742. THREE.FontUtils.style = style;
  15743. // Get a Font data json object
  15744. var data = THREE.FontUtils.drawText( text );
  15745. var paths = data.paths;
  15746. var shapes = [];
  15747. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15748. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15749. }
  15750. return shapes;
  15751. };
  15752. /**
  15753. * This code is a quick port of code written in C++ which was submitted to
  15754. * flipcode.com by John W. Ratcliff // July 22, 2000
  15755. * See original code and more information here:
  15756. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15757. *
  15758. * ported to actionscript by Zevan Rosser
  15759. * www.actionsnippet.com
  15760. *
  15761. * ported to javascript by Joshua Koo
  15762. * http://www.lab4games.net/zz85/blog
  15763. *
  15764. */
  15765. ( function ( namespace ) {
  15766. var EPSILON = 0.0000000001;
  15767. // takes in an contour array and returns
  15768. var process = function ( contour, indices ) {
  15769. var n = contour.length;
  15770. if ( n < 3 ) return null;
  15771. var result = [],
  15772. verts = [],
  15773. vertIndices = [];
  15774. /* we want a counter-clockwise polygon in verts */
  15775. var u, v, w;
  15776. if ( area( contour ) > 0.0 ) {
  15777. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  15778. } else {
  15779. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  15780. }
  15781. var nv = n;
  15782. /* remove nv - 2 vertices, creating 1 triangle every time */
  15783. var count = 2 * nv; /* error detection */
  15784. for ( v = nv - 1; nv > 2; ) {
  15785. /* if we loop, it is probably a non-simple polygon */
  15786. if ( ( count -- ) <= 0 ) {
  15787. //** Triangulate: ERROR - probable bad polygon!
  15788. //throw ( "Warning, unable to triangulate polygon!" );
  15789. //return null;
  15790. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15791. console.warn( 'THREE.FontUtils: Warning, unable to triangulate polygon! in Triangulate.process()' );
  15792. if ( indices ) return vertIndices;
  15793. return result;
  15794. }
  15795. /* three consecutive vertices in current polygon, <u,v,w> */
  15796. u = v; if ( nv <= u ) u = 0; /* previous */
  15797. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15798. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15799. if ( snip( contour, u, v, w, nv, verts ) ) {
  15800. var a, b, c, s, t;
  15801. /* true names of the vertices */
  15802. a = verts[ u ];
  15803. b = verts[ v ];
  15804. c = verts[ w ];
  15805. /* output Triangle */
  15806. result.push( [ contour[ a ],
  15807. contour[ b ],
  15808. contour[ c ] ] );
  15809. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15810. /* remove v from the remaining polygon */
  15811. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  15812. verts[ s ] = verts[ t ];
  15813. }
  15814. nv --;
  15815. /* reset error detection counter */
  15816. count = 2 * nv;
  15817. }
  15818. }
  15819. if ( indices ) return vertIndices;
  15820. return result;
  15821. };
  15822. // calculate area of the contour polygon
  15823. var area = function ( contour ) {
  15824. var n = contour.length;
  15825. var a = 0.0;
  15826. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  15827. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15828. }
  15829. return a * 0.5;
  15830. };
  15831. var snip = function ( contour, u, v, w, n, verts ) {
  15832. var p;
  15833. var ax, ay, bx, by;
  15834. var cx, cy, px, py;
  15835. ax = contour[ verts[ u ] ].x;
  15836. ay = contour[ verts[ u ] ].y;
  15837. bx = contour[ verts[ v ] ].x;
  15838. by = contour[ verts[ v ] ].y;
  15839. cx = contour[ verts[ w ] ].x;
  15840. cy = contour[ verts[ w ] ].y;
  15841. if ( EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  15842. var aX, aY, bX, bY, cX, cY;
  15843. var apx, apy, bpx, bpy, cpx, cpy;
  15844. var cCROSSap, bCROSScp, aCROSSbp;
  15845. aX = cx - bx; aY = cy - by;
  15846. bX = ax - cx; bY = ay - cy;
  15847. cX = bx - ax; cY = by - ay;
  15848. for ( p = 0; p < n; p ++ ) {
  15849. px = contour[ verts[ p ] ].x;
  15850. py = contour[ verts[ p ] ].y;
  15851. if ( ( ( px === ax ) && ( py === ay ) ) ||
  15852. ( ( px === bx ) && ( py === by ) ) ||
  15853. ( ( px === cx ) && ( py === cy ) ) ) continue;
  15854. apx = px - ax; apy = py - ay;
  15855. bpx = px - bx; bpy = py - by;
  15856. cpx = px - cx; cpy = py - cy;
  15857. // see if p is inside triangle abc
  15858. aCROSSbp = aX * bpy - aY * bpx;
  15859. cCROSSap = cX * apy - cY * apx;
  15860. bCROSScp = bX * cpy - bY * cpx;
  15861. if ( ( aCROSSbp >= - EPSILON ) && ( bCROSScp >= - EPSILON ) && ( cCROSSap >= - EPSILON ) ) return false;
  15862. }
  15863. return true;
  15864. };
  15865. namespace.Triangulate = process;
  15866. namespace.Triangulate.area = area;
  15867. return namespace;
  15868. } )( THREE.FontUtils );
  15869. // To use the typeface.js face files, hook up the API
  15870. THREE.typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  15871. if ( typeof self !== 'undefined' ) self._typeface_js = THREE.typeface_js;
  15872. // File:src/extras/audio/Audio.js
  15873. /**
  15874. * @author mrdoob / http://mrdoob.com/
  15875. */
  15876. THREE.Audio = function ( listener ) {
  15877. THREE.Object3D.call( this );
  15878. this.type = 'Audio';
  15879. this.context = listener.context;
  15880. this.source = this.context.createBufferSource();
  15881. this.source.onended = this.onEnded.bind(this);
  15882. this.gain = this.context.createGain();
  15883. this.gain.connect( this.context.destination );
  15884. this.panner = this.context.createPanner();
  15885. this.panner.connect( this.gain );
  15886. this.autoplay = false;
  15887. this.startTime = 0;
  15888. this.isPlaying = false;
  15889. };
  15890. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  15891. THREE.Audio.prototype.constructor = THREE.Audio;
  15892. THREE.Audio.prototype.load = function ( file ) {
  15893. var scope = this;
  15894. var request = new XMLHttpRequest();
  15895. request.open( 'GET', file, true );
  15896. request.responseType = 'arraybuffer';
  15897. request.onload = function ( e ) {
  15898. scope.context.decodeAudioData( this.response, function ( buffer ) {
  15899. scope.source.buffer = buffer;
  15900. if( scope.autoplay ) scope.play();
  15901. } );
  15902. };
  15903. request.send();
  15904. return this;
  15905. };
  15906. THREE.Audio.prototype.play = function () {
  15907. if ( this.isPlaying === true ) {
  15908. console.warn( 'THREE.Audio: Audio is already playing.' );
  15909. return;
  15910. }
  15911. var source = this.context.createBufferSource();
  15912. source.buffer = this.source.buffer;
  15913. source.loop = this.source.loop;
  15914. source.onended = this.source.onended;
  15915. source.connect( this.panner );
  15916. source.start( 0, this.startTime );
  15917. this.isPlaying = true;
  15918. this.source = source;
  15919. };
  15920. THREE.Audio.prototype.pause = function () {
  15921. this.source.stop();
  15922. this.startTime = this.context.currentTime;
  15923. };
  15924. THREE.Audio.prototype.stop = function () {
  15925. this.source.stop();
  15926. this.startTime = 0;
  15927. };
  15928. THREE.Audio.prototype.onEnded = function() {
  15929. this.isPlaying = false;
  15930. };
  15931. THREE.Audio.prototype.setLoop = function ( value ) {
  15932. this.source.loop = value;
  15933. };
  15934. THREE.Audio.prototype.setRefDistance = function ( value ) {
  15935. this.panner.refDistance = value;
  15936. };
  15937. THREE.Audio.prototype.setRolloffFactor = function ( value ) {
  15938. this.panner.rolloffFactor = value;
  15939. };
  15940. THREE.Audio.prototype.setVolume = function ( value ) {
  15941. this.gain.gain.value = value;
  15942. };
  15943. THREE.Audio.prototype.updateMatrixWorld = ( function () {
  15944. var position = new THREE.Vector3();
  15945. return function ( force ) {
  15946. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  15947. position.setFromMatrixPosition( this.matrixWorld );
  15948. this.panner.setPosition( position.x, position.y, position.z );
  15949. };
  15950. } )();
  15951. // File:src/extras/audio/AudioListener.js
  15952. /**
  15953. * @author mrdoob / http://mrdoob.com/
  15954. */
  15955. THREE.AudioListener = function () {
  15956. THREE.Object3D.call( this );
  15957. this.type = 'AudioListener';
  15958. this.context = new ( window.AudioContext || window.webkitAudioContext )();
  15959. };
  15960. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  15961. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  15962. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  15963. var position = new THREE.Vector3();
  15964. var quaternion = new THREE.Quaternion();
  15965. var scale = new THREE.Vector3();
  15966. var orientation = new THREE.Vector3();
  15967. return function ( force ) {
  15968. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  15969. var listener = this.context.listener;
  15970. var up = this.up;
  15971. this.matrixWorld.decompose( position, quaternion, scale );
  15972. orientation.set( 0, 0, -1 ).applyQuaternion( quaternion );
  15973. listener.setPosition( position.x, position.y, position.z );
  15974. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  15975. };
  15976. } )();
  15977. // File:src/extras/core/Curve.js
  15978. /**
  15979. * @author zz85 / http://www.lab4games.net/zz85/blog
  15980. * Extensible curve object
  15981. *
  15982. * Some common of Curve methods
  15983. * .getPoint(t), getTangent(t)
  15984. * .getPointAt(u), getTagentAt(u)
  15985. * .getPoints(), .getSpacedPoints()
  15986. * .getLength()
  15987. * .updateArcLengths()
  15988. *
  15989. * This following classes subclasses THREE.Curve:
  15990. *
  15991. * -- 2d classes --
  15992. * THREE.LineCurve
  15993. * THREE.QuadraticBezierCurve
  15994. * THREE.CubicBezierCurve
  15995. * THREE.SplineCurve
  15996. * THREE.ArcCurve
  15997. * THREE.EllipseCurve
  15998. *
  15999. * -- 3d classes --
  16000. * THREE.LineCurve3
  16001. * THREE.QuadraticBezierCurve3
  16002. * THREE.CubicBezierCurve3
  16003. * THREE.SplineCurve3
  16004. * THREE.ClosedSplineCurve3
  16005. *
  16006. * A series of curves can be represented as a THREE.CurvePath
  16007. *
  16008. **/
  16009. /**************************************************************
  16010. * Abstract Curve base class
  16011. **************************************************************/
  16012. THREE.Curve = function () {
  16013. };
  16014. // Virtual base class method to overwrite and implement in subclasses
  16015. // - t [0 .. 1]
  16016. THREE.Curve.prototype.getPoint = function ( t ) {
  16017. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  16018. return null;
  16019. };
  16020. // Get point at relative position in curve according to arc length
  16021. // - u [0 .. 1]
  16022. THREE.Curve.prototype.getPointAt = function ( u ) {
  16023. var t = this.getUtoTmapping( u );
  16024. return this.getPoint( t );
  16025. };
  16026. // Get sequence of points using getPoint( t )
  16027. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16028. if ( ! divisions ) divisions = 5;
  16029. var d, pts = [];
  16030. for ( d = 0; d <= divisions; d ++ ) {
  16031. pts.push( this.getPoint( d / divisions ) );
  16032. }
  16033. return pts;
  16034. };
  16035. // Get sequence of points using getPointAt( u )
  16036. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16037. if ( ! divisions ) divisions = 5;
  16038. var d, pts = [];
  16039. for ( d = 0; d <= divisions; d ++ ) {
  16040. pts.push( this.getPointAt( d / divisions ) );
  16041. }
  16042. return pts;
  16043. };
  16044. // Get total curve arc length
  16045. THREE.Curve.prototype.getLength = function () {
  16046. var lengths = this.getLengths();
  16047. return lengths[ lengths.length - 1 ];
  16048. };
  16049. // Get list of cumulative segment lengths
  16050. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16051. if ( ! divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions) : 200;
  16052. if ( this.cacheArcLengths
  16053. && ( this.cacheArcLengths.length === divisions + 1 )
  16054. && ! this.needsUpdate) {
  16055. //console.log( "cached", this.cacheArcLengths );
  16056. return this.cacheArcLengths;
  16057. }
  16058. this.needsUpdate = false;
  16059. var cache = [];
  16060. var current, last = this.getPoint( 0 );
  16061. var p, sum = 0;
  16062. cache.push( 0 );
  16063. for ( p = 1; p <= divisions; p ++ ) {
  16064. current = this.getPoint ( p / divisions );
  16065. sum += current.distanceTo( last );
  16066. cache.push( sum );
  16067. last = current;
  16068. }
  16069. this.cacheArcLengths = cache;
  16070. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16071. };
  16072. THREE.Curve.prototype.updateArcLengths = function() {
  16073. this.needsUpdate = true;
  16074. this.getLengths();
  16075. };
  16076. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  16077. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16078. var arcLengths = this.getLengths();
  16079. var i = 0, il = arcLengths.length;
  16080. var targetArcLength; // The targeted u distance value to get
  16081. if ( distance ) {
  16082. targetArcLength = distance;
  16083. } else {
  16084. targetArcLength = u * arcLengths[ il - 1 ];
  16085. }
  16086. //var time = Date.now();
  16087. // binary search for the index with largest value smaller than target u distance
  16088. var low = 0, high = il - 1, comparison;
  16089. while ( low <= high ) {
  16090. 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
  16091. comparison = arcLengths[ i ] - targetArcLength;
  16092. if ( comparison < 0 ) {
  16093. low = i + 1;
  16094. } else if ( comparison > 0 ) {
  16095. high = i - 1;
  16096. } else {
  16097. high = i;
  16098. break;
  16099. // DONE
  16100. }
  16101. }
  16102. i = high;
  16103. //console.log('b' , i, low, high, Date.now()- time);
  16104. if ( arcLengths[ i ] === targetArcLength ) {
  16105. var t = i / ( il - 1 );
  16106. return t;
  16107. }
  16108. // we could get finer grain at lengths, or use simple interpolation between two points
  16109. var lengthBefore = arcLengths[ i ];
  16110. var lengthAfter = arcLengths[ i + 1 ];
  16111. var segmentLength = lengthAfter - lengthBefore;
  16112. // determine where we are between the 'before' and 'after' points
  16113. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16114. // add that fractional amount to t
  16115. var t = ( i + segmentFraction ) / ( il - 1 );
  16116. return t;
  16117. };
  16118. // Returns a unit vector tangent at t
  16119. // In case any sub curve does not implement its tangent derivation,
  16120. // 2 points a small delta apart will be used to find its gradient
  16121. // which seems to give a reasonable approximation
  16122. THREE.Curve.prototype.getTangent = function( t ) {
  16123. var delta = 0.0001;
  16124. var t1 = t - delta;
  16125. var t2 = t + delta;
  16126. // Capping in case of danger
  16127. if ( t1 < 0 ) t1 = 0;
  16128. if ( t2 > 1 ) t2 = 1;
  16129. var pt1 = this.getPoint( t1 );
  16130. var pt2 = this.getPoint( t2 );
  16131. var vec = pt2.clone().sub(pt1);
  16132. return vec.normalize();
  16133. };
  16134. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16135. var t = this.getUtoTmapping( u );
  16136. return this.getTangent( t );
  16137. };
  16138. /**************************************************************
  16139. * Utils
  16140. **************************************************************/
  16141. THREE.Curve.Utils = {
  16142. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16143. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16144. },
  16145. // Puay Bing, thanks for helping with this derivative!
  16146. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16147. return - 3 * p0 * (1 - t) * (1 - t) +
  16148. 3 * p1 * (1 - t) * (1 - t) - 6 * t * p1 * (1 - t) +
  16149. 6 * t * p2 * (1 - t) - 3 * t * t * p2 +
  16150. 3 * t * t * p3;
  16151. },
  16152. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16153. // To check if my formulas are correct
  16154. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16155. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16156. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  16157. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16158. return h00 + h10 + h01 + h11;
  16159. },
  16160. // Catmull-Rom
  16161. interpolate: function( p0, p1, p2, p3, t ) {
  16162. var v0 = ( p2 - p0 ) * 0.5;
  16163. var v1 = ( p3 - p1 ) * 0.5;
  16164. var t2 = t * t;
  16165. var t3 = t * t2;
  16166. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16167. }
  16168. };
  16169. // TODO: Transformation for Curves?
  16170. /**************************************************************
  16171. * 3D Curves
  16172. **************************************************************/
  16173. // A Factory method for creating new curve subclasses
  16174. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16175. constructor.prototype = Object.create( THREE.Curve.prototype );
  16176. constructor.prototype.constructor = constructor;
  16177. constructor.prototype.getPoint = getPointFunc;
  16178. return constructor;
  16179. };
  16180. // File:src/extras/core/CurvePath.js
  16181. /**
  16182. * @author zz85 / http://www.lab4games.net/zz85/blog
  16183. *
  16184. **/
  16185. /**************************************************************
  16186. * Curved Path - a curve path is simply a array of connected
  16187. * curves, but retains the api of a curve
  16188. **************************************************************/
  16189. THREE.CurvePath = function () {
  16190. this.curves = [];
  16191. this.bends = [];
  16192. this.autoClose = false; // Automatically closes the path
  16193. };
  16194. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16195. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  16196. THREE.CurvePath.prototype.add = function ( curve ) {
  16197. this.curves.push( curve );
  16198. };
  16199. THREE.CurvePath.prototype.checkConnection = function() {
  16200. // TODO
  16201. // If the ending of curve is not connected to the starting
  16202. // or the next curve, then, this is not a real path
  16203. };
  16204. THREE.CurvePath.prototype.closePath = function() {
  16205. // TODO Test
  16206. // and verify for vector3 (needs to implement equals)
  16207. // Add a line curve if start and end of lines are not connected
  16208. var startPoint = this.curves[0].getPoint(0);
  16209. var endPoint = this.curves[this.curves.length - 1].getPoint(1);
  16210. if (! startPoint.equals(endPoint)) {
  16211. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16212. }
  16213. };
  16214. // To get accurate point with reference to
  16215. // entire path distance at time t,
  16216. // following has to be done:
  16217. // 1. Length of each sub path have to be known
  16218. // 2. Locate and identify type of curve
  16219. // 3. Get t for the curve
  16220. // 4. Return curve.getPointAt(t')
  16221. THREE.CurvePath.prototype.getPoint = function( t ) {
  16222. var d = t * this.getLength();
  16223. var curveLengths = this.getCurveLengths();
  16224. var i = 0, diff, curve;
  16225. // To think about boundaries points.
  16226. while ( i < curveLengths.length ) {
  16227. if ( curveLengths[ i ] >= d ) {
  16228. diff = curveLengths[ i ] - d;
  16229. curve = this.curves[ i ];
  16230. var u = 1 - diff / curve.getLength();
  16231. return curve.getPointAt( u );
  16232. }
  16233. i ++;
  16234. }
  16235. return null;
  16236. // loop where sum != 0, sum > d , sum+1 <d
  16237. };
  16238. /*
  16239. THREE.CurvePath.prototype.getTangent = function( t ) {
  16240. };*/
  16241. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16242. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16243. // getPoint() depends on getLength
  16244. THREE.CurvePath.prototype.getLength = function() {
  16245. var lens = this.getCurveLengths();
  16246. return lens[ lens.length - 1 ];
  16247. };
  16248. // Compute lengths and cache them
  16249. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16250. THREE.CurvePath.prototype.getCurveLengths = function() {
  16251. // We use cache values if curves and cache array are same length
  16252. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  16253. return this.cacheLengths;
  16254. }
  16255. // Get length of sub-curve
  16256. // Push sums into cached array
  16257. var lengths = [], sums = 0;
  16258. var i, il = this.curves.length;
  16259. for ( i = 0; i < il; i ++ ) {
  16260. sums += this.curves[ i ].getLength();
  16261. lengths.push( sums );
  16262. }
  16263. this.cacheLengths = lengths;
  16264. return lengths;
  16265. };
  16266. // Returns min and max coordinates
  16267. THREE.CurvePath.prototype.getBoundingBox = function () {
  16268. var points = this.getPoints();
  16269. var maxX, maxY, maxZ;
  16270. var minX, minY, minZ;
  16271. maxX = maxY = Number.NEGATIVE_INFINITY;
  16272. minX = minY = Number.POSITIVE_INFINITY;
  16273. var p, i, il, sum;
  16274. var v3 = points[0] instanceof THREE.Vector3;
  16275. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16276. for ( i = 0, il = points.length; i < il; i ++ ) {
  16277. p = points[ i ];
  16278. if ( p.x > maxX ) maxX = p.x;
  16279. else if ( p.x < minX ) minX = p.x;
  16280. if ( p.y > maxY ) maxY = p.y;
  16281. else if ( p.y < minY ) minY = p.y;
  16282. if ( v3 ) {
  16283. if ( p.z > maxZ ) maxZ = p.z;
  16284. else if ( p.z < minZ ) minZ = p.z;
  16285. }
  16286. sum.add( p );
  16287. }
  16288. var ret = {
  16289. minX: minX,
  16290. minY: minY,
  16291. maxX: maxX,
  16292. maxY: maxY
  16293. };
  16294. if ( v3 ) {
  16295. ret.maxZ = maxZ;
  16296. ret.minZ = minZ;
  16297. }
  16298. return ret;
  16299. };
  16300. /**************************************************************
  16301. * Create Geometries Helpers
  16302. **************************************************************/
  16303. /// Generate geometry from path points (for Line or Points objects)
  16304. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16305. var pts = this.getPoints( divisions, true );
  16306. return this.createGeometry( pts );
  16307. };
  16308. // Generate geometry from equidistant sampling along the path
  16309. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16310. var pts = this.getSpacedPoints( divisions, true );
  16311. return this.createGeometry( pts );
  16312. };
  16313. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16314. var geometry = new THREE.Geometry();
  16315. for ( var i = 0; i < points.length; i ++ ) {
  16316. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16317. }
  16318. return geometry;
  16319. };
  16320. /**************************************************************
  16321. * Bend / Wrap Helper Methods
  16322. **************************************************************/
  16323. // Wrap path / Bend modifiers?
  16324. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16325. this.bends.push( bendpath );
  16326. };
  16327. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16328. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16329. var i, il;
  16330. if ( ! bends ) {
  16331. bends = this.bends;
  16332. }
  16333. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16334. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16335. }
  16336. return oldPts;
  16337. };
  16338. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16339. var oldPts = this.getSpacedPoints( segments );
  16340. var i, il;
  16341. if ( ! bends ) {
  16342. bends = this.bends;
  16343. }
  16344. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16345. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16346. }
  16347. return oldPts;
  16348. };
  16349. // This returns getPoints() bend/wrapped around the contour of a path.
  16350. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16351. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16352. var bounds = this.getBoundingBox();
  16353. var i, il, p, oldX, oldY, xNorm;
  16354. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16355. p = oldPts[ i ];
  16356. oldX = p.x;
  16357. oldY = p.y;
  16358. xNorm = oldX / bounds.maxX;
  16359. // If using actual distance, for length > path, requires line extrusions
  16360. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16361. xNorm = path.getUtoTmapping( xNorm, oldX );
  16362. // check for out of bounds?
  16363. var pathPt = path.getPoint( xNorm );
  16364. var normal = path.getTangent( xNorm );
  16365. normal.set( - normal.y, normal.x ).multiplyScalar( oldY );
  16366. p.x = pathPt.x + normal.x;
  16367. p.y = pathPt.y + normal.y;
  16368. }
  16369. return oldPts;
  16370. };
  16371. // File:src/extras/core/Gyroscope.js
  16372. /**
  16373. * @author alteredq / http://alteredqualia.com/
  16374. */
  16375. THREE.Gyroscope = function () {
  16376. THREE.Object3D.call( this );
  16377. };
  16378. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16379. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  16380. THREE.Gyroscope.prototype.updateMatrixWorld = ( function () {
  16381. var translationObject = new THREE.Vector3();
  16382. var quaternionObject = new THREE.Quaternion();
  16383. var scaleObject = new THREE.Vector3();
  16384. var translationWorld = new THREE.Vector3();
  16385. var quaternionWorld = new THREE.Quaternion();
  16386. var scaleWorld = new THREE.Vector3();
  16387. return function ( force ) {
  16388. this.matrixAutoUpdate && this.updateMatrix();
  16389. // update matrixWorld
  16390. if ( this.matrixWorldNeedsUpdate || force ) {
  16391. if ( this.parent ) {
  16392. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16393. this.matrixWorld.decompose( translationWorld, quaternionWorld, scaleWorld );
  16394. this.matrix.decompose( translationObject, quaternionObject, scaleObject );
  16395. this.matrixWorld.compose( translationWorld, quaternionObject, scaleWorld );
  16396. } else {
  16397. this.matrixWorld.copy( this.matrix );
  16398. }
  16399. this.matrixWorldNeedsUpdate = false;
  16400. force = true;
  16401. }
  16402. // update children
  16403. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16404. this.children[ i ].updateMatrixWorld( force );
  16405. }
  16406. };
  16407. }() );
  16408. // File:src/extras/core/Path.js
  16409. /**
  16410. * @author zz85 / http://www.lab4games.net/zz85/blog
  16411. * Creates free form 2d path using series of points, lines or curves.
  16412. *
  16413. **/
  16414. THREE.Path = function ( points ) {
  16415. THREE.CurvePath.call(this);
  16416. this.actions = [];
  16417. if ( points ) {
  16418. this.fromPoints( points );
  16419. }
  16420. };
  16421. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16422. THREE.Path.prototype.constructor = THREE.Path;
  16423. THREE.PathActions = {
  16424. MOVE_TO: 'moveTo',
  16425. LINE_TO: 'lineTo',
  16426. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16427. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16428. CSPLINE_THRU: 'splineThru', // Catmull-Rom spline
  16429. ARC: 'arc', // Circle
  16430. ELLIPSE: 'ellipse'
  16431. };
  16432. // TODO Clean up PATH API
  16433. // Create path using straight lines to connect all points
  16434. // - vectors: array of Vector2
  16435. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16436. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16437. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16438. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16439. }
  16440. };
  16441. // startPath() endPath()?
  16442. THREE.Path.prototype.moveTo = function ( x, y ) {
  16443. var args = Array.prototype.slice.call( arguments );
  16444. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16445. };
  16446. THREE.Path.prototype.lineTo = function ( x, y ) {
  16447. var args = Array.prototype.slice.call( arguments );
  16448. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16449. var x0 = lastargs[ lastargs.length - 2 ];
  16450. var y0 = lastargs[ lastargs.length - 1 ];
  16451. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16452. this.curves.push( curve );
  16453. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16454. };
  16455. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16456. var args = Array.prototype.slice.call( arguments );
  16457. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16458. var x0 = lastargs[ lastargs.length - 2 ];
  16459. var y0 = lastargs[ lastargs.length - 1 ];
  16460. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16461. new THREE.Vector2( aCPx, aCPy ),
  16462. new THREE.Vector2( aX, aY ) );
  16463. this.curves.push( curve );
  16464. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16465. };
  16466. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16467. aCP2x, aCP2y,
  16468. aX, aY ) {
  16469. var args = Array.prototype.slice.call( arguments );
  16470. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16471. var x0 = lastargs[ lastargs.length - 2 ];
  16472. var y0 = lastargs[ lastargs.length - 1 ];
  16473. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16474. new THREE.Vector2( aCP1x, aCP1y ),
  16475. new THREE.Vector2( aCP2x, aCP2y ),
  16476. new THREE.Vector2( aX, aY ) );
  16477. this.curves.push( curve );
  16478. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16479. };
  16480. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16481. var args = Array.prototype.slice.call( arguments );
  16482. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16483. var x0 = lastargs[ lastargs.length - 2 ];
  16484. var y0 = lastargs[ lastargs.length - 1 ];
  16485. //---
  16486. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16487. Array.prototype.push.apply( npts, pts );
  16488. var curve = new THREE.SplineCurve( npts );
  16489. this.curves.push( curve );
  16490. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16491. };
  16492. // FUTURE: Change the API or follow canvas API?
  16493. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16494. aStartAngle, aEndAngle, aClockwise ) {
  16495. var lastargs = this.actions[ this.actions.length - 1].args;
  16496. var x0 = lastargs[ lastargs.length - 2 ];
  16497. var y0 = lastargs[ lastargs.length - 1 ];
  16498. this.absarc(aX + x0, aY + y0, aRadius,
  16499. aStartAngle, aEndAngle, aClockwise );
  16500. };
  16501. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16502. aStartAngle, aEndAngle, aClockwise ) {
  16503. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16504. };
  16505. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16506. aStartAngle, aEndAngle, aClockwise ) {
  16507. var lastargs = this.actions[ this.actions.length - 1].args;
  16508. var x0 = lastargs[ lastargs.length - 2 ];
  16509. var y0 = lastargs[ lastargs.length - 1 ];
  16510. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16511. aStartAngle, aEndAngle, aClockwise );
  16512. };
  16513. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16514. aStartAngle, aEndAngle, aClockwise ) {
  16515. var args = Array.prototype.slice.call( arguments );
  16516. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16517. aStartAngle, aEndAngle, aClockwise );
  16518. this.curves.push( curve );
  16519. var lastPoint = curve.getPoint(1);
  16520. args.push(lastPoint.x);
  16521. args.push(lastPoint.y);
  16522. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16523. };
  16524. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16525. if ( ! divisions ) divisions = 40;
  16526. var points = [];
  16527. for ( var i = 0; i < divisions; i ++ ) {
  16528. points.push( this.getPoint( i / divisions ) );
  16529. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16530. }
  16531. // if ( closedPath ) {
  16532. //
  16533. // points.push( points[ 0 ] );
  16534. //
  16535. // }
  16536. return points;
  16537. };
  16538. /* Return an array of vectors based on contour of the path */
  16539. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16540. if (this.useSpacedPoints) {
  16541. return this.getSpacedPoints( divisions, closedPath );
  16542. }
  16543. divisions = divisions || 12;
  16544. var points = [];
  16545. var i, il, item, action, args;
  16546. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16547. laste, j,
  16548. t, tx, ty;
  16549. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16550. item = this.actions[ i ];
  16551. action = item.action;
  16552. args = item.args;
  16553. switch ( action ) {
  16554. case THREE.PathActions.MOVE_TO:
  16555. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16556. break;
  16557. case THREE.PathActions.LINE_TO:
  16558. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16559. break;
  16560. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16561. cpx = args[ 2 ];
  16562. cpy = args[ 3 ];
  16563. cpx1 = args[ 0 ];
  16564. cpy1 = args[ 1 ];
  16565. if ( points.length > 0 ) {
  16566. laste = points[ points.length - 1 ];
  16567. cpx0 = laste.x;
  16568. cpy0 = laste.y;
  16569. } else {
  16570. laste = this.actions[ i - 1 ].args;
  16571. cpx0 = laste[ laste.length - 2 ];
  16572. cpy0 = laste[ laste.length - 1 ];
  16573. }
  16574. for ( j = 1; j <= divisions; j ++ ) {
  16575. t = j / divisions;
  16576. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16577. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16578. points.push( new THREE.Vector2( tx, ty ) );
  16579. }
  16580. break;
  16581. case THREE.PathActions.BEZIER_CURVE_TO:
  16582. cpx = args[ 4 ];
  16583. cpy = args[ 5 ];
  16584. cpx1 = args[ 0 ];
  16585. cpy1 = args[ 1 ];
  16586. cpx2 = args[ 2 ];
  16587. cpy2 = args[ 3 ];
  16588. if ( points.length > 0 ) {
  16589. laste = points[ points.length - 1 ];
  16590. cpx0 = laste.x;
  16591. cpy0 = laste.y;
  16592. } else {
  16593. laste = this.actions[ i - 1 ].args;
  16594. cpx0 = laste[ laste.length - 2 ];
  16595. cpy0 = laste[ laste.length - 1 ];
  16596. }
  16597. for ( j = 1; j <= divisions; j ++ ) {
  16598. t = j / divisions;
  16599. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16600. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16601. points.push( new THREE.Vector2( tx, ty ) );
  16602. }
  16603. break;
  16604. case THREE.PathActions.CSPLINE_THRU:
  16605. laste = this.actions[ i - 1 ].args;
  16606. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16607. var spts = [ last ];
  16608. var n = divisions * args[ 0 ].length;
  16609. spts = spts.concat( args[ 0 ] );
  16610. var spline = new THREE.SplineCurve( spts );
  16611. for ( j = 1; j <= n; j ++ ) {
  16612. points.push( spline.getPointAt( j / n ) ) ;
  16613. }
  16614. break;
  16615. case THREE.PathActions.ARC:
  16616. var aX = args[ 0 ], aY = args[ 1 ],
  16617. aRadius = args[ 2 ],
  16618. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16619. aClockwise = !! args[ 5 ];
  16620. var deltaAngle = aEndAngle - aStartAngle;
  16621. var angle;
  16622. var tdivisions = divisions * 2;
  16623. for ( j = 1; j <= tdivisions; j ++ ) {
  16624. t = j / tdivisions;
  16625. if ( ! aClockwise ) {
  16626. t = 1 - t;
  16627. }
  16628. angle = aStartAngle + t * deltaAngle;
  16629. tx = aX + aRadius * Math.cos( angle );
  16630. ty = aY + aRadius * Math.sin( angle );
  16631. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16632. points.push( new THREE.Vector2( tx, ty ) );
  16633. }
  16634. //console.log(points);
  16635. break;
  16636. case THREE.PathActions.ELLIPSE:
  16637. var aX = args[ 0 ], aY = args[ 1 ],
  16638. xRadius = args[ 2 ],
  16639. yRadius = args[ 3 ],
  16640. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16641. aClockwise = !! args[ 6 ];
  16642. var deltaAngle = aEndAngle - aStartAngle;
  16643. var angle;
  16644. var tdivisions = divisions * 2;
  16645. for ( j = 1; j <= tdivisions; j ++ ) {
  16646. t = j / tdivisions;
  16647. if ( ! aClockwise ) {
  16648. t = 1 - t;
  16649. }
  16650. angle = aStartAngle + t * deltaAngle;
  16651. tx = aX + xRadius * Math.cos( angle );
  16652. ty = aY + yRadius * Math.sin( angle );
  16653. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16654. points.push( new THREE.Vector2( tx, ty ) );
  16655. }
  16656. //console.log(points);
  16657. break;
  16658. } // end switch
  16659. }
  16660. // Normalize to remove the closing point by default.
  16661. var lastPoint = points[ points.length - 1];
  16662. var EPSILON = 0.0000000001;
  16663. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16664. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16665. points.splice( points.length - 1, 1);
  16666. if ( closedPath ) {
  16667. points.push( points[ 0 ] );
  16668. }
  16669. return points;
  16670. };
  16671. //
  16672. // Breaks path into shapes
  16673. //
  16674. // Assumptions (if parameter isCCW==true the opposite holds):
  16675. // - solid shapes are defined clockwise (CW)
  16676. // - holes are defined counterclockwise (CCW)
  16677. //
  16678. // If parameter noHoles==true:
  16679. // - all subPaths are regarded as solid shapes
  16680. // - definition order CW/CCW has no relevance
  16681. //
  16682. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  16683. function extractSubpaths( inActions ) {
  16684. var i, il, item, action, args;
  16685. var subPaths = [], lastPath = new THREE.Path();
  16686. for ( i = 0, il = inActions.length; i < il; i ++ ) {
  16687. item = inActions[ i ];
  16688. args = item.args;
  16689. action = item.action;
  16690. if ( action === THREE.PathActions.MOVE_TO ) {
  16691. if ( lastPath.actions.length !== 0 ) {
  16692. subPaths.push( lastPath );
  16693. lastPath = new THREE.Path();
  16694. }
  16695. }
  16696. lastPath[ action ].apply( lastPath, args );
  16697. }
  16698. if ( lastPath.actions.length !== 0 ) {
  16699. subPaths.push( lastPath );
  16700. }
  16701. // console.log(subPaths);
  16702. return subPaths;
  16703. }
  16704. function toShapesNoHoles( inSubpaths ) {
  16705. var shapes = [];
  16706. for ( var i = 0, il = inSubpaths.length; i < il; i ++ ) {
  16707. var tmpPath = inSubpaths[ i ];
  16708. var tmpShape = new THREE.Shape();
  16709. tmpShape.actions = tmpPath.actions;
  16710. tmpShape.curves = tmpPath.curves;
  16711. shapes.push( tmpShape );
  16712. }
  16713. //console.log("shape", shapes);
  16714. return shapes;
  16715. }
  16716. function isPointInsidePolygon( inPt, inPolygon ) {
  16717. var EPSILON = 0.0000000001;
  16718. var polyLen = inPolygon.length;
  16719. // inPt on polygon contour => immediate success or
  16720. // toggling of inside/outside at every single! intersection point of an edge
  16721. // with the horizontal line through inPt, left of inPt
  16722. // not counting lowerY endpoints of edges and whole edges on that line
  16723. var inside = false;
  16724. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  16725. var edgeLowPt = inPolygon[ p ];
  16726. var edgeHighPt = inPolygon[ q ];
  16727. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  16728. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  16729. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  16730. if ( edgeDy < 0 ) {
  16731. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  16732. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  16733. }
  16734. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  16735. if ( inPt.y === edgeLowPt.y ) {
  16736. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  16737. // continue; // no intersection or edgeLowPt => doesn't count !!!
  16738. } else {
  16739. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  16740. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  16741. if ( perpEdge < 0 ) continue;
  16742. inside = ! inside; // true intersection left of inPt
  16743. }
  16744. } else { // parallel or collinear
  16745. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  16746. // edge lies on the same horizontal line as inPt
  16747. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  16748. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  16749. // continue;
  16750. }
  16751. }
  16752. return inside;
  16753. }
  16754. var subPaths = extractSubpaths( this.actions );
  16755. if ( subPaths.length === 0 ) return [];
  16756. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  16757. var solid, tmpPath, tmpShape, shapes = [];
  16758. if ( subPaths.length === 1) {
  16759. tmpPath = subPaths[0];
  16760. tmpShape = new THREE.Shape();
  16761. tmpShape.actions = tmpPath.actions;
  16762. tmpShape.curves = tmpPath.curves;
  16763. shapes.push( tmpShape );
  16764. return shapes;
  16765. }
  16766. var holesFirst = ! THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16767. holesFirst = isCCW ? ! holesFirst : holesFirst;
  16768. // console.log("Holes first", holesFirst);
  16769. var betterShapeHoles = [];
  16770. var newShapes = [];
  16771. var newShapeHoles = [];
  16772. var mainIdx = 0;
  16773. var tmpPoints;
  16774. newShapes[mainIdx] = undefined;
  16775. newShapeHoles[mainIdx] = [];
  16776. var i, il;
  16777. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16778. tmpPath = subPaths[ i ];
  16779. tmpPoints = tmpPath.getPoints();
  16780. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  16781. solid = isCCW ? ! solid : solid;
  16782. if ( solid ) {
  16783. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx ++;
  16784. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  16785. newShapes[mainIdx].s.actions = tmpPath.actions;
  16786. newShapes[mainIdx].s.curves = tmpPath.curves;
  16787. if ( holesFirst ) mainIdx ++;
  16788. newShapeHoles[mainIdx] = [];
  16789. //console.log('cw', i);
  16790. } else {
  16791. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  16792. //console.log('ccw', i);
  16793. }
  16794. }
  16795. // only Holes? -> probably all Shapes with wrong orientation
  16796. if ( ! newShapes[0] ) return toShapesNoHoles( subPaths );
  16797. if ( newShapes.length > 1 ) {
  16798. var ambiguous = false;
  16799. var toChange = [];
  16800. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  16801. betterShapeHoles[sIdx] = [];
  16802. }
  16803. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  16804. var sho = newShapeHoles[sIdx];
  16805. for (var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  16806. var ho = sho[hIdx];
  16807. var hole_unassigned = true;
  16808. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  16809. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  16810. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  16811. if ( hole_unassigned ) {
  16812. hole_unassigned = false;
  16813. betterShapeHoles[s2Idx].push( ho );
  16814. } else {
  16815. ambiguous = true;
  16816. }
  16817. }
  16818. }
  16819. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  16820. }
  16821. }
  16822. // console.log("ambiguous: ", ambiguous);
  16823. if ( toChange.length > 0 ) {
  16824. // console.log("to change: ", toChange);
  16825. if (! ambiguous) newShapeHoles = betterShapeHoles;
  16826. }
  16827. }
  16828. var tmpHoles, j, jl;
  16829. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  16830. tmpShape = newShapes[i].s;
  16831. shapes.push( tmpShape );
  16832. tmpHoles = newShapeHoles[i];
  16833. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  16834. tmpShape.holes.push( tmpHoles[j].h );
  16835. }
  16836. }
  16837. //console.log("shape", shapes);
  16838. return shapes;
  16839. };
  16840. // File:src/extras/core/Shape.js
  16841. /**
  16842. * @author zz85 / http://www.lab4games.net/zz85/blog
  16843. * Defines a 2d shape plane using paths.
  16844. **/
  16845. // STEP 1 Create a path.
  16846. // STEP 2 Turn path into shape.
  16847. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16848. // STEP 3a - Extract points from each shape, turn to vertices
  16849. // STEP 3b - Triangulate each shape, add faces.
  16850. THREE.Shape = function () {
  16851. THREE.Path.apply( this, arguments );
  16852. this.holes = [];
  16853. };
  16854. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16855. THREE.Shape.prototype.constructor = THREE.Shape;
  16856. // Convenience method to return ExtrudeGeometry
  16857. THREE.Shape.prototype.extrude = function ( options ) {
  16858. var extruded = new THREE.ExtrudeGeometry( this, options );
  16859. return extruded;
  16860. };
  16861. // Convenience method to return ShapeGeometry
  16862. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16863. var geometry = new THREE.ShapeGeometry( this, options );
  16864. return geometry;
  16865. };
  16866. // Get points of holes
  16867. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16868. var i, il = this.holes.length, holesPts = [];
  16869. for ( i = 0; i < il; i ++ ) {
  16870. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16871. }
  16872. return holesPts;
  16873. };
  16874. // Get points of holes (spaced by regular distance)
  16875. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16876. var i, il = this.holes.length, holesPts = [];
  16877. for ( i = 0; i < il; i ++ ) {
  16878. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16879. }
  16880. return holesPts;
  16881. };
  16882. // Get points of shape and holes (keypoints based on segments parameter)
  16883. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16884. return {
  16885. shape: this.getTransformedPoints( divisions ),
  16886. holes: this.getPointsHoles( divisions )
  16887. };
  16888. };
  16889. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16890. if (this.useSpacedPoints) {
  16891. return this.extractAllSpacedPoints(divisions);
  16892. }
  16893. return this.extractAllPoints(divisions);
  16894. };
  16895. //
  16896. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16897. //
  16898. // return {
  16899. //
  16900. // shape: this.transform( bend, divisions ),
  16901. // holes: this.getPointsHoles( divisions, bend )
  16902. //
  16903. // };
  16904. //
  16905. // };
  16906. // Get points of shape and holes (spaced by regular distance)
  16907. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16908. return {
  16909. shape: this.getTransformedSpacedPoints( divisions ),
  16910. holes: this.getSpacedPointsHoles( divisions )
  16911. };
  16912. };
  16913. /**************************************************************
  16914. * Utils
  16915. **************************************************************/
  16916. THREE.Shape.Utils = {
  16917. triangulateShape: function ( contour, holes ) {
  16918. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  16919. // inOtherPt needs to be collinear to the inSegment
  16920. if ( inSegPt1.x !== inSegPt2.x ) {
  16921. if ( inSegPt1.x < inSegPt2.x ) {
  16922. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  16923. } else {
  16924. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  16925. }
  16926. } else {
  16927. if ( inSegPt1.y < inSegPt2.y ) {
  16928. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  16929. } else {
  16930. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  16931. }
  16932. }
  16933. }
  16934. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  16935. var EPSILON = 0.0000000001;
  16936. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  16937. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  16938. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  16939. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  16940. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  16941. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  16942. if ( Math.abs(limit) > EPSILON ) { // not parallel
  16943. var perpSeg2;
  16944. if ( limit > 0 ) {
  16945. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  16946. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  16947. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  16948. } else {
  16949. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  16950. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  16951. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  16952. }
  16953. // i.e. to reduce rounding errors
  16954. // intersection at endpoint of segment#1?
  16955. if ( perpSeg2 === 0 ) {
  16956. if ( ( inExcludeAdjacentSegs ) &&
  16957. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  16958. return [ inSeg1Pt1 ];
  16959. }
  16960. if ( perpSeg2 === limit ) {
  16961. if ( ( inExcludeAdjacentSegs ) &&
  16962. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  16963. return [ inSeg1Pt2 ];
  16964. }
  16965. // intersection at endpoint of segment#2?
  16966. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  16967. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  16968. // return real intersection point
  16969. var factorSeg1 = perpSeg2 / limit;
  16970. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  16971. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  16972. } else { // parallel or collinear
  16973. if ( ( perpSeg1 !== 0 ) ||
  16974. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  16975. // they are collinear or degenerate
  16976. var seg1Pt = ( (seg1dx === 0) && (seg1dy === 0) ); // segment1 is just a point?
  16977. var seg2Pt = ( (seg2dx === 0) && (seg2dy === 0) ); // segment2 is just a point?
  16978. // both segments are points
  16979. if ( seg1Pt && seg2Pt ) {
  16980. if ( (inSeg1Pt1.x !== inSeg2Pt1.x) ||
  16981. (inSeg1Pt1.y !== inSeg2Pt1.y) ) return []; // they are distinct points
  16982. return [ inSeg1Pt1 ]; // they are the same point
  16983. }
  16984. // segment#1 is a single point
  16985. if ( seg1Pt ) {
  16986. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  16987. return [ inSeg1Pt1 ];
  16988. }
  16989. // segment#2 is a single point
  16990. if ( seg2Pt ) {
  16991. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  16992. return [ inSeg2Pt1 ];
  16993. }
  16994. // they are collinear segments, which might overlap
  16995. var seg1min, seg1max, seg1minVal, seg1maxVal;
  16996. var seg2min, seg2max, seg2minVal, seg2maxVal;
  16997. if (seg1dx !== 0) { // the segments are NOT on a vertical line
  16998. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  16999. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17000. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17001. } else {
  17002. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17003. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17004. }
  17005. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17006. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17007. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17008. } else {
  17009. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17010. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17011. }
  17012. } else { // the segments are on a vertical line
  17013. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17014. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17015. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17016. } else {
  17017. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17018. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17019. }
  17020. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17021. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17022. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17023. } else {
  17024. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17025. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17026. }
  17027. }
  17028. if ( seg1minVal <= seg2minVal ) {
  17029. if ( seg1maxVal < seg2minVal ) return [];
  17030. if ( seg1maxVal === seg2minVal ) {
  17031. if ( inExcludeAdjacentSegs ) return [];
  17032. return [ seg2min ];
  17033. }
  17034. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17035. return [ seg2min, seg2max ];
  17036. } else {
  17037. if ( seg1minVal > seg2maxVal ) return [];
  17038. if ( seg1minVal === seg2maxVal ) {
  17039. if ( inExcludeAdjacentSegs ) return [];
  17040. return [ seg1min ];
  17041. }
  17042. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17043. return [ seg1min, seg2max ];
  17044. }
  17045. }
  17046. }
  17047. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17048. // The order of legs is important
  17049. var EPSILON = 0.0000000001;
  17050. // translation of all points, so that Vertex is at (0,0)
  17051. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17052. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17053. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17054. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17055. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17056. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17057. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17058. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17059. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17060. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17061. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17062. } else { // main angle > 180 deg.
  17063. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17064. }
  17065. } else { // angle == 180 deg.
  17066. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17067. return ( from2otherAngle > 0 );
  17068. }
  17069. }
  17070. function removeHoles( contour, holes ) {
  17071. var shape = contour.concat(); // work on this shape
  17072. var hole;
  17073. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17074. // Check if hole point lies within angle around shape point
  17075. var lastShapeIdx = shape.length - 1;
  17076. var prevShapeIdx = inShapeIdx - 1;
  17077. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17078. var nextShapeIdx = inShapeIdx + 1;
  17079. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17080. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17081. if (! insideAngle ) {
  17082. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17083. return false;
  17084. }
  17085. // Check if shape point lies within angle around hole point
  17086. var lastHoleIdx = hole.length - 1;
  17087. var prevHoleIdx = inHoleIdx - 1;
  17088. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17089. var nextHoleIdx = inHoleIdx + 1;
  17090. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17091. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17092. if (! insideAngle ) {
  17093. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17094. return false;
  17095. }
  17096. return true;
  17097. }
  17098. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17099. // checks for intersections with shape edges
  17100. var sIdx, nextIdx, intersection;
  17101. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  17102. nextIdx = sIdx + 1; nextIdx %= shape.length;
  17103. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17104. if ( intersection.length > 0 ) return true;
  17105. }
  17106. return false;
  17107. }
  17108. var indepHoles = [];
  17109. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17110. // checks for intersections with hole edges
  17111. var ihIdx, chkHole,
  17112. hIdx, nextIdx, intersection;
  17113. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  17114. chkHole = holes[indepHoles[ihIdx]];
  17115. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  17116. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  17117. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17118. if ( intersection.length > 0 ) return true;
  17119. }
  17120. }
  17121. return false;
  17122. }
  17123. var holeIndex, shapeIndex,
  17124. shapePt, holePt,
  17125. holeIdx, cutKey, failedCuts = [],
  17126. tmpShape1, tmpShape2,
  17127. tmpHole1, tmpHole2;
  17128. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17129. indepHoles.push( h );
  17130. }
  17131. var minShapeIndex = 0;
  17132. var counter = indepHoles.length * 2;
  17133. while ( indepHoles.length > 0 ) {
  17134. counter --;
  17135. if ( counter < 0 ) {
  17136. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17137. break;
  17138. }
  17139. // search for shape-vertex and hole-vertex,
  17140. // which can be connected without intersections
  17141. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  17142. shapePt = shape[ shapeIndex ];
  17143. holeIndex = - 1;
  17144. // search for hole which can be reached without intersections
  17145. for ( var h = 0; h < indepHoles.length; h ++ ) {
  17146. holeIdx = indepHoles[h];
  17147. // prevent multiple checks
  17148. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17149. if ( failedCuts[cutKey] !== undefined ) continue;
  17150. hole = holes[holeIdx];
  17151. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  17152. holePt = hole[ h2 ];
  17153. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17154. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17155. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17156. holeIndex = h2;
  17157. indepHoles.splice(h, 1);
  17158. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  17159. tmpShape2 = shape.slice( shapeIndex );
  17160. tmpHole1 = hole.slice( holeIndex );
  17161. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  17162. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17163. minShapeIndex = shapeIndex;
  17164. // Debug only, to show the selected cuts
  17165. // glob_CutLines.push( [ shapePt, holePt ] );
  17166. break;
  17167. }
  17168. if ( holeIndex >= 0 ) break; // hole-vertex found
  17169. failedCuts[cutKey] = true; // remember failure
  17170. }
  17171. if ( holeIndex >= 0 ) break; // hole-vertex found
  17172. }
  17173. }
  17174. return shape; /* shape with no holes */
  17175. }
  17176. var i, il, f, face,
  17177. key, index,
  17178. allPointsMap = {};
  17179. // 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.
  17180. var allpoints = contour.concat();
  17181. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  17182. Array.prototype.push.apply( allpoints, holes[h] );
  17183. }
  17184. //console.log( "allpoints",allpoints, allpoints.length );
  17185. // prepare all points map
  17186. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17187. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17188. if ( allPointsMap[ key ] !== undefined ) {
  17189. console.warn( "THREE.Shape: Duplicate point", key );
  17190. }
  17191. allPointsMap[ key ] = i;
  17192. }
  17193. // remove holes by cutting paths to holes and adding them to the shape
  17194. var shapeWithoutHoles = removeHoles( contour, holes );
  17195. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17196. //console.log( "triangles",triangles, triangles.length );
  17197. // check all face vertices against all points map
  17198. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17199. face = triangles[ i ];
  17200. for ( f = 0; f < 3; f ++ ) {
  17201. key = face[ f ].x + ":" + face[ f ].y;
  17202. index = allPointsMap[ key ];
  17203. if ( index !== undefined ) {
  17204. face[ f ] = index;
  17205. }
  17206. }
  17207. }
  17208. return triangles.concat();
  17209. },
  17210. isClockWise: function ( pts ) {
  17211. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17212. },
  17213. // Bezier Curves formulas obtained from
  17214. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17215. // Quad Bezier Functions
  17216. b2p0: function ( t, p ) {
  17217. var k = 1 - t;
  17218. return k * k * p;
  17219. },
  17220. b2p1: function ( t, p ) {
  17221. return 2 * ( 1 - t ) * t * p;
  17222. },
  17223. b2p2: function ( t, p ) {
  17224. return t * t * p;
  17225. },
  17226. b2: function ( t, p0, p1, p2 ) {
  17227. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17228. },
  17229. // Cubic Bezier Functions
  17230. b3p0: function ( t, p ) {
  17231. var k = 1 - t;
  17232. return k * k * k * p;
  17233. },
  17234. b3p1: function ( t, p ) {
  17235. var k = 1 - t;
  17236. return 3 * k * k * t * p;
  17237. },
  17238. b3p2: function ( t, p ) {
  17239. var k = 1 - t;
  17240. return 3 * k * t * t * p;
  17241. },
  17242. b3p3: function ( t, p ) {
  17243. return t * t * t * p;
  17244. },
  17245. b3: function ( t, p0, p1, p2, p3 ) {
  17246. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17247. }
  17248. };
  17249. // File:src/extras/curves/LineCurve.js
  17250. /**************************************************************
  17251. * Line
  17252. **************************************************************/
  17253. THREE.LineCurve = function ( v1, v2 ) {
  17254. this.v1 = v1;
  17255. this.v2 = v2;
  17256. };
  17257. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17258. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  17259. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17260. var point = this.v2.clone().sub(this.v1);
  17261. point.multiplyScalar( t ).add( this.v1 );
  17262. return point;
  17263. };
  17264. // Line curve is linear, so we can overwrite default getPointAt
  17265. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17266. return this.getPoint( u );
  17267. };
  17268. THREE.LineCurve.prototype.getTangent = function( t ) {
  17269. var tangent = this.v2.clone().sub(this.v1);
  17270. return tangent.normalize();
  17271. };
  17272. // File:src/extras/curves/QuadraticBezierCurve.js
  17273. /**************************************************************
  17274. * Quadratic Bezier curve
  17275. **************************************************************/
  17276. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17277. this.v0 = v0;
  17278. this.v1 = v1;
  17279. this.v2 = v2;
  17280. };
  17281. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17282. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  17283. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17284. var vector = new THREE.Vector2();
  17285. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17286. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17287. return vector;
  17288. };
  17289. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17290. var vector = new THREE.Vector2();
  17291. vector.x = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17292. vector.y = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17293. // returns unit vector
  17294. return vector.normalize();
  17295. };
  17296. // File:src/extras/curves/CubicBezierCurve.js
  17297. /**************************************************************
  17298. * Cubic Bezier curve
  17299. **************************************************************/
  17300. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17301. this.v0 = v0;
  17302. this.v1 = v1;
  17303. this.v2 = v2;
  17304. this.v3 = v3;
  17305. };
  17306. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17307. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  17308. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17309. var tx, ty;
  17310. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17311. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17312. return new THREE.Vector2( tx, ty );
  17313. };
  17314. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17315. var tx, ty;
  17316. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17317. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17318. var tangent = new THREE.Vector2( tx, ty );
  17319. tangent.normalize();
  17320. return tangent;
  17321. };
  17322. // File:src/extras/curves/SplineCurve.js
  17323. /**************************************************************
  17324. * Spline curve
  17325. **************************************************************/
  17326. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17327. this.points = ( points == undefined ) ? [] : points;
  17328. };
  17329. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17330. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  17331. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17332. var points = this.points;
  17333. var point = ( points.length - 1 ) * t;
  17334. var intPoint = Math.floor( point );
  17335. var weight = point - intPoint;
  17336. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  17337. var point1 = points[ intPoint ];
  17338. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17339. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17340. var vector = new THREE.Vector2();
  17341. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17342. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17343. return vector;
  17344. };
  17345. // File:src/extras/curves/EllipseCurve.js
  17346. /**************************************************************
  17347. * Ellipse curve
  17348. **************************************************************/
  17349. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17350. this.aX = aX;
  17351. this.aY = aY;
  17352. this.xRadius = xRadius;
  17353. this.yRadius = yRadius;
  17354. this.aStartAngle = aStartAngle;
  17355. this.aEndAngle = aEndAngle;
  17356. this.aClockwise = aClockwise;
  17357. };
  17358. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17359. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  17360. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17361. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17362. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17363. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17364. var angle;
  17365. if ( this.aClockwise === true ) {
  17366. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17367. } else {
  17368. angle = this.aStartAngle + t * deltaAngle;
  17369. }
  17370. var vector = new THREE.Vector2();
  17371. vector.x = this.aX + this.xRadius * Math.cos( angle );
  17372. vector.y = this.aY + this.yRadius * Math.sin( angle );
  17373. return vector;
  17374. };
  17375. // File:src/extras/curves/ArcCurve.js
  17376. /**************************************************************
  17377. * Arc curve
  17378. **************************************************************/
  17379. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17380. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17381. };
  17382. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17383. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  17384. // File:src/extras/curves/LineCurve3.js
  17385. /**************************************************************
  17386. * Line3D
  17387. **************************************************************/
  17388. THREE.LineCurve3 = THREE.Curve.create(
  17389. function ( v1, v2 ) {
  17390. this.v1 = v1;
  17391. this.v2 = v2;
  17392. },
  17393. function ( t ) {
  17394. var vector = new THREE.Vector3();
  17395. vector.subVectors( this.v2, this.v1 ); // diff
  17396. vector.multiplyScalar( t );
  17397. vector.add( this.v1 );
  17398. return vector;
  17399. }
  17400. );
  17401. // File:src/extras/curves/QuadraticBezierCurve3.js
  17402. /**************************************************************
  17403. * Quadratic Bezier 3D curve
  17404. **************************************************************/
  17405. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17406. function ( v0, v1, v2 ) {
  17407. this.v0 = v0;
  17408. this.v1 = v1;
  17409. this.v2 = v2;
  17410. },
  17411. function ( t ) {
  17412. var vector = new THREE.Vector3();
  17413. vector.x = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17414. vector.y = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17415. vector.z = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17416. return vector;
  17417. }
  17418. );
  17419. // File:src/extras/curves/CubicBezierCurve3.js
  17420. /**************************************************************
  17421. * Cubic Bezier 3D curve
  17422. **************************************************************/
  17423. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17424. function ( v0, v1, v2, v3 ) {
  17425. this.v0 = v0;
  17426. this.v1 = v1;
  17427. this.v2 = v2;
  17428. this.v3 = v3;
  17429. },
  17430. function ( t ) {
  17431. var vector = new THREE.Vector3();
  17432. vector.x = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17433. vector.y = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17434. vector.z = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17435. return vector;
  17436. }
  17437. );
  17438. // File:src/extras/curves/SplineCurve3.js
  17439. /**************************************************************
  17440. * Spline 3D curve
  17441. **************************************************************/
  17442. THREE.SplineCurve3 = THREE.Curve.create(
  17443. function ( points /* array of Vector3 */) {
  17444. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  17445. this.points = ( points == undefined ) ? [] : points;
  17446. },
  17447. function ( t ) {
  17448. var points = this.points;
  17449. var point = ( points.length - 1 ) * t;
  17450. var intPoint = Math.floor( point );
  17451. var weight = point - intPoint;
  17452. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  17453. var point1 = points[ intPoint ];
  17454. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  17455. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  17456. var vector = new THREE.Vector3();
  17457. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17458. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17459. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17460. return vector;
  17461. }
  17462. );
  17463. // File:src/extras/curves/CatmullRomCurve3.js
  17464. /**
  17465. * @author zz85 https://github.com/zz85
  17466. *
  17467. * Centripetal CatmullRom Curve - which is useful for avoiding
  17468. * cusps and self-intersections in non-uniform catmull rom curves.
  17469. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  17470. *
  17471. * curve.type accepts centripetal(default), chordal and catmullrom
  17472. * curve.tension is used for catmullrom which defaults to 0.5
  17473. */
  17474. THREE.CatmullRomCurve3 = ( function() {
  17475. var
  17476. tmp = new THREE.Vector3(),
  17477. px = new CubicPoly(),
  17478. py = new CubicPoly(),
  17479. pz = new CubicPoly();
  17480. /*
  17481. Based on an optimized c++ solution in
  17482. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  17483. - http://ideone.com/NoEbVM
  17484. This CubicPoly class could be used for reusing some variables and calculations,
  17485. but for three.js curve use, it could be possible inlined and flatten into a single function call
  17486. which can be placed in CurveUtils.
  17487. */
  17488. function CubicPoly() {
  17489. }
  17490. /*
  17491. * Compute coefficients for a cubic polynomial
  17492. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  17493. * such that
  17494. * p(0) = x0, p(1) = x1
  17495. * and
  17496. * p'(0) = t0, p'(1) = t1.
  17497. */
  17498. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  17499. this.c0 = x0;
  17500. this.c1 = t0;
  17501. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  17502. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  17503. };
  17504. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  17505. // compute tangents when parameterized in [t1,t2]
  17506. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  17507. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  17508. // rescale tangents for parametrization in [0,1]
  17509. t1 *= dt1;
  17510. t2 *= dt1;
  17511. // initCubicPoly
  17512. this.init( x1, x2, t1, t2 );
  17513. };
  17514. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  17515. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  17516. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  17517. };
  17518. CubicPoly.prototype.calc = function( t ) {
  17519. var t2 = t * t;
  17520. var t3 = t2 * t;
  17521. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  17522. };
  17523. // Subclass Three.js curve
  17524. return THREE.Curve.create(
  17525. function ( p /* array of Vector3 */ ) {
  17526. this.points = p || [];
  17527. },
  17528. function ( t ) {
  17529. var points = this.points,
  17530. point, intPoint, weight, l;
  17531. l = points.length;
  17532. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  17533. point = ( l - 1 ) * t;
  17534. intPoint = Math.floor( point );
  17535. weight = point - intPoint;
  17536. if ( weight === 0 && intPoint === l - 1 ) {
  17537. intPoint = l - 2;
  17538. weight = 1;
  17539. }
  17540. var p0, p1, p2, p3;
  17541. if ( intPoint === 0 ) {
  17542. // extrapolate first point
  17543. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  17544. p0 = tmp;
  17545. } else {
  17546. p0 = points[ intPoint - 1 ];
  17547. }
  17548. p1 = points[ intPoint ];
  17549. p2 = points[ intPoint + 1 ];
  17550. if ( intPoint + 2 < l ) {
  17551. p3 = points[ intPoint + 2 ]
  17552. } else {
  17553. // extrapolate last point
  17554. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 2 ] );
  17555. p3 = tmp;
  17556. }
  17557. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  17558. // init Centripetal / Chordal Catmull-Rom
  17559. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  17560. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  17561. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  17562. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  17563. // safety check for repeated points
  17564. if ( dt1 < 1e-4 ) dt1 = 1.0;
  17565. if ( dt0 < 1e-4 ) dt0 = dt1;
  17566. if ( dt2 < 1e-4 ) dt2 = dt1;
  17567. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  17568. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  17569. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  17570. } else if ( this.type === 'catmullrom' ) {
  17571. var tension = this.tension !== undefined ? this.tension : 0.5;
  17572. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  17573. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  17574. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  17575. }
  17576. var v = new THREE.Vector3(
  17577. px.calc( weight ),
  17578. py.calc( weight ),
  17579. pz.calc( weight )
  17580. );
  17581. return v;
  17582. }
  17583. );
  17584. } )();
  17585. // File:src/extras/curves/ClosedSplineCurve3.js
  17586. /**************************************************************
  17587. * Closed Spline 3D curve
  17588. **************************************************************/
  17589. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17590. function ( points /* array of Vector3 */) {
  17591. this.points = ( points == undefined ) ? [] : points;
  17592. },
  17593. function ( t ) {
  17594. var points = this.points;
  17595. var point = ( points.length - 0 ) * t; // This needs to be from 0-length +1
  17596. var intPoint = Math.floor( point );
  17597. var weight = point - intPoint;
  17598. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17599. var point0 = points[ ( intPoint - 1 ) % points.length ];
  17600. var point1 = points[ ( intPoint ) % points.length ];
  17601. var point2 = points[ ( intPoint + 1 ) % points.length ];
  17602. var point3 = points[ ( intPoint + 2 ) % points.length ];
  17603. var vector = new THREE.Vector3();
  17604. vector.x = THREE.Curve.Utils.interpolate( point0.x, point1.x, point2.x, point3.x, weight );
  17605. vector.y = THREE.Curve.Utils.interpolate( point0.y, point1.y, point2.y, point3.y, weight );
  17606. vector.z = THREE.Curve.Utils.interpolate( point0.z, point1.z, point2.z, point3.z, weight );
  17607. return vector;
  17608. }
  17609. );
  17610. // File:src/extras/animation/AnimationHandler.js
  17611. /**
  17612. * @author mikael emtinger / http://gomo.se/
  17613. */
  17614. THREE.AnimationHandler = {
  17615. LINEAR: 0,
  17616. CATMULLROM: 1,
  17617. CATMULLROM_FORWARD: 2,
  17618. //
  17619. add: function () { console.warn( 'THREE.AnimationHandler.add() has been deprecated.' ); },
  17620. get: function () { console.warn( 'THREE.AnimationHandler.get() has been deprecated.' ); },
  17621. remove: function () { console.warn( 'THREE.AnimationHandler.remove() has been deprecated.' ); },
  17622. //
  17623. animations: [],
  17624. init: function ( data ) {
  17625. if ( data.initialized === true ) return data;
  17626. // loop through all keys
  17627. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  17628. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17629. // remove minus times
  17630. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  17631. data.hierarchy[ h ].keys[ k ].time = 0;
  17632. }
  17633. // create quaternions
  17634. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17635. ! ( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17636. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17637. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  17638. }
  17639. }
  17640. // prepare morph target keys
  17641. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17642. // get all used
  17643. var usedMorphTargets = {};
  17644. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17645. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17646. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17647. usedMorphTargets[ morphTargetName ] = - 1;
  17648. }
  17649. }
  17650. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17651. // set all used on all frames
  17652. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17653. var influences = {};
  17654. for ( var morphTargetName in usedMorphTargets ) {
  17655. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17656. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17657. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17658. break;
  17659. }
  17660. }
  17661. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17662. influences[ morphTargetName ] = 0;
  17663. }
  17664. }
  17665. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17666. }
  17667. }
  17668. // remove all keys that are on the same time
  17669. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17670. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17671. data.hierarchy[ h ].keys.splice( k, 1 );
  17672. k --;
  17673. }
  17674. }
  17675. // set index
  17676. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17677. data.hierarchy[ h ].keys[ k ].index = k;
  17678. }
  17679. }
  17680. data.initialized = true;
  17681. return data;
  17682. },
  17683. parse: function ( root ) {
  17684. var parseRecurseHierarchy = function ( root, hierarchy ) {
  17685. hierarchy.push( root );
  17686. for ( var c = 0; c < root.children.length; c ++ )
  17687. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17688. };
  17689. // setup hierarchy
  17690. var hierarchy = [];
  17691. if ( root instanceof THREE.SkinnedMesh ) {
  17692. for ( var b = 0; b < root.skeleton.bones.length; b ++ ) {
  17693. hierarchy.push( root.skeleton.bones[ b ] );
  17694. }
  17695. } else {
  17696. parseRecurseHierarchy( root, hierarchy );
  17697. }
  17698. return hierarchy;
  17699. },
  17700. play: function ( animation ) {
  17701. if ( this.animations.indexOf( animation ) === - 1 ) {
  17702. this.animations.push( animation );
  17703. }
  17704. },
  17705. stop: function ( animation ) {
  17706. var index = this.animations.indexOf( animation );
  17707. if ( index !== - 1 ) {
  17708. this.animations.splice( index, 1 );
  17709. }
  17710. },
  17711. update: function ( deltaTimeMS ) {
  17712. for ( var i = 0; i < this.animations.length; i ++ ) {
  17713. this.animations[ i ].resetBlendWeights( );
  17714. }
  17715. for ( var i = 0; i < this.animations.length; i ++ ) {
  17716. this.animations[ i ].update( deltaTimeMS );
  17717. }
  17718. }
  17719. };
  17720. // File:src/extras/animation/Animation.js
  17721. /**
  17722. * @author mikael emtinger / http://gomo.se/
  17723. * @author mrdoob / http://mrdoob.com/
  17724. * @author alteredq / http://alteredqualia.com/
  17725. */
  17726. THREE.Animation = function ( root, data ) {
  17727. this.root = root;
  17728. this.data = THREE.AnimationHandler.init( data );
  17729. this.hierarchy = THREE.AnimationHandler.parse( root );
  17730. this.currentTime = 0;
  17731. this.timeScale = 1;
  17732. this.isPlaying = false;
  17733. this.loop = true;
  17734. this.weight = 0;
  17735. this.interpolationType = THREE.AnimationHandler.LINEAR;
  17736. };
  17737. THREE.Animation.prototype = {
  17738. constructor: THREE.Animation,
  17739. keyTypes: [ "pos", "rot", "scl" ],
  17740. play: function ( startTime, weight ) {
  17741. this.currentTime = startTime !== undefined ? startTime : 0;
  17742. this.weight = weight !== undefined ? weight : 1;
  17743. this.isPlaying = true;
  17744. this.reset();
  17745. THREE.AnimationHandler.play( this );
  17746. },
  17747. stop: function() {
  17748. this.isPlaying = false;
  17749. THREE.AnimationHandler.stop( this );
  17750. },
  17751. reset: function () {
  17752. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17753. var object = this.hierarchy[ h ];
  17754. if ( object.animationCache === undefined ) {
  17755. object.animationCache = {
  17756. animations: {},
  17757. blending: {
  17758. positionWeight: 0.0,
  17759. quaternionWeight: 0.0,
  17760. scaleWeight: 0.0
  17761. }
  17762. };
  17763. }
  17764. var name = this.data.name;
  17765. var animations = object.animationCache.animations;
  17766. var animationCache = animations[ name ];
  17767. if ( animationCache === undefined ) {
  17768. animationCache = {
  17769. prevKey: { pos: 0, rot: 0, scl: 0 },
  17770. nextKey: { pos: 0, rot: 0, scl: 0 },
  17771. originalMatrix: object.matrix
  17772. };
  17773. animations[ name ] = animationCache;
  17774. }
  17775. // Get keys to match our current time
  17776. for ( var t = 0; t < 3; t ++ ) {
  17777. var type = this.keyTypes[ t ];
  17778. var prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17779. var nextKey = this.getNextKeyWith( type, h, 1 );
  17780. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17781. prevKey = nextKey;
  17782. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17783. }
  17784. animationCache.prevKey[ type ] = prevKey;
  17785. animationCache.nextKey[ type ] = nextKey;
  17786. }
  17787. }
  17788. },
  17789. resetBlendWeights: function () {
  17790. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17791. var object = this.hierarchy[ h ];
  17792. var animationCache = object.animationCache;
  17793. if ( animationCache !== undefined ) {
  17794. var blending = animationCache.blending;
  17795. blending.positionWeight = 0.0;
  17796. blending.quaternionWeight = 0.0;
  17797. blending.scaleWeight = 0.0;
  17798. }
  17799. }
  17800. },
  17801. update: ( function() {
  17802. var points = [];
  17803. var target = new THREE.Vector3();
  17804. var newVector = new THREE.Vector3();
  17805. var newQuat = new THREE.Quaternion();
  17806. // Catmull-Rom spline
  17807. var interpolateCatmullRom = function ( points, scale ) {
  17808. var c = [], v3 = [],
  17809. point, intPoint, weight, w2, w3,
  17810. pa, pb, pc, pd;
  17811. point = ( points.length - 1 ) * scale;
  17812. intPoint = Math.floor( point );
  17813. weight = point - intPoint;
  17814. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17815. c[ 1 ] = intPoint;
  17816. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17817. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17818. pa = points[ c[ 0 ] ];
  17819. pb = points[ c[ 1 ] ];
  17820. pc = points[ c[ 2 ] ];
  17821. pd = points[ c[ 3 ] ];
  17822. w2 = weight * weight;
  17823. w3 = weight * w2;
  17824. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17825. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17826. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17827. return v3;
  17828. };
  17829. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17830. var v0 = ( p2 - p0 ) * 0.5,
  17831. v1 = ( p3 - p1 ) * 0.5;
  17832. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17833. };
  17834. return function ( delta ) {
  17835. if ( this.isPlaying === false ) return;
  17836. this.currentTime += delta * this.timeScale;
  17837. if ( this.weight === 0 )
  17838. return;
  17839. //
  17840. var duration = this.data.length;
  17841. if ( this.currentTime > duration || this.currentTime < 0 ) {
  17842. if ( this.loop ) {
  17843. this.currentTime %= duration;
  17844. if ( this.currentTime < 0 )
  17845. this.currentTime += duration;
  17846. this.reset();
  17847. } else {
  17848. this.stop();
  17849. }
  17850. }
  17851. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17852. var object = this.hierarchy[ h ];
  17853. var animationCache = object.animationCache.animations[this.data.name];
  17854. var blending = object.animationCache.blending;
  17855. // loop through pos/rot/scl
  17856. for ( var t = 0; t < 3; t ++ ) {
  17857. // get keys
  17858. var type = this.keyTypes[ t ];
  17859. var prevKey = animationCache.prevKey[ type ];
  17860. var nextKey = animationCache.nextKey[ type ];
  17861. if ( ( this.timeScale > 0 && nextKey.time <= this.currentTime ) ||
  17862. ( this.timeScale < 0 && prevKey.time >= this.currentTime ) ) {
  17863. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17864. nextKey = this.getNextKeyWith( type, h, 1 );
  17865. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  17866. prevKey = nextKey;
  17867. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17868. }
  17869. animationCache.prevKey[ type ] = prevKey;
  17870. animationCache.nextKey[ type ] = nextKey;
  17871. }
  17872. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17873. var prevXYZ = prevKey[ type ];
  17874. var nextXYZ = nextKey[ type ];
  17875. if ( scale < 0 ) scale = 0;
  17876. if ( scale > 1 ) scale = 1;
  17877. // interpolate
  17878. if ( type === "pos" ) {
  17879. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17880. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17881. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17882. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17883. // blend
  17884. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  17885. object.position.lerp( newVector, proportionalWeight );
  17886. blending.positionWeight += this.weight;
  17887. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17888. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17889. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17890. points[ 1 ] = prevXYZ;
  17891. points[ 2 ] = nextXYZ;
  17892. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17893. scale = scale * 0.33 + 0.33;
  17894. var currentPoint = interpolateCatmullRom( points, scale );
  17895. var proportionalWeight = this.weight / ( this.weight + blending.positionWeight );
  17896. blending.positionWeight += this.weight;
  17897. // blend
  17898. var vector = object.position;
  17899. vector.x = vector.x + ( currentPoint[ 0 ] - vector.x ) * proportionalWeight;
  17900. vector.y = vector.y + ( currentPoint[ 1 ] - vector.y ) * proportionalWeight;
  17901. vector.z = vector.z + ( currentPoint[ 2 ] - vector.z ) * proportionalWeight;
  17902. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17903. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  17904. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17905. target.sub( vector );
  17906. target.y = 0;
  17907. target.normalize();
  17908. var angle = Math.atan2( target.x, target.z );
  17909. object.rotation.set( 0, angle, 0 );
  17910. }
  17911. }
  17912. } else if ( type === "rot" ) {
  17913. THREE.Quaternion.slerp( prevXYZ, nextXYZ, newQuat, scale );
  17914. // Avoid paying the cost of an additional slerp if we don't have to
  17915. if ( blending.quaternionWeight === 0 ) {
  17916. object.quaternion.copy(newQuat);
  17917. blending.quaternionWeight = this.weight;
  17918. } else {
  17919. var proportionalWeight = this.weight / ( this.weight + blending.quaternionWeight );
  17920. THREE.Quaternion.slerp( object.quaternion, newQuat, object.quaternion, proportionalWeight );
  17921. blending.quaternionWeight += this.weight;
  17922. }
  17923. } else if ( type === "scl" ) {
  17924. newVector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17925. newVector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17926. newVector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17927. var proportionalWeight = this.weight / ( this.weight + blending.scaleWeight );
  17928. object.scale.lerp( newVector, proportionalWeight );
  17929. blending.scaleWeight += this.weight;
  17930. }
  17931. }
  17932. }
  17933. return true;
  17934. };
  17935. } )(),
  17936. getNextKeyWith: function ( type, h, key ) {
  17937. var keys = this.data.hierarchy[ h ].keys;
  17938. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17939. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17940. key = key < keys.length - 1 ? key : keys.length - 1;
  17941. } else {
  17942. key = key % keys.length;
  17943. }
  17944. for ( ; key < keys.length; key ++ ) {
  17945. if ( keys[ key ][ type ] !== undefined ) {
  17946. return keys[ key ];
  17947. }
  17948. }
  17949. return this.data.hierarchy[ h ].keys[ 0 ];
  17950. },
  17951. getPrevKeyWith: function ( type, h, key ) {
  17952. var keys = this.data.hierarchy[ h ].keys;
  17953. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17954. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17955. key = key > 0 ? key : 0;
  17956. } else {
  17957. key = key >= 0 ? key : key + keys.length;
  17958. }
  17959. for ( ; key >= 0; key -- ) {
  17960. if ( keys[ key ][ type ] !== undefined ) {
  17961. return keys[ key ];
  17962. }
  17963. }
  17964. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17965. }
  17966. };
  17967. // File:src/extras/animation/KeyFrameAnimation.js
  17968. /**
  17969. * @author mikael emtinger / http://gomo.se/
  17970. * @author mrdoob / http://mrdoob.com/
  17971. * @author alteredq / http://alteredqualia.com/
  17972. * @author khang duong
  17973. * @author erik kitson
  17974. */
  17975. THREE.KeyFrameAnimation = function ( data ) {
  17976. this.root = data.node;
  17977. this.data = THREE.AnimationHandler.init( data );
  17978. this.hierarchy = THREE.AnimationHandler.parse( this.root );
  17979. this.currentTime = 0;
  17980. this.timeScale = 0.001;
  17981. this.isPlaying = false;
  17982. this.isPaused = true;
  17983. this.loop = true;
  17984. // initialize to first keyframes
  17985. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17986. var keys = this.data.hierarchy[h].keys,
  17987. sids = this.data.hierarchy[h].sids,
  17988. obj = this.hierarchy[h];
  17989. if ( keys.length && sids ) {
  17990. for ( var s = 0; s < sids.length; s ++ ) {
  17991. var sid = sids[ s ],
  17992. next = this.getNextKeyWith( sid, h, 0 );
  17993. if ( next ) {
  17994. next.apply( sid );
  17995. }
  17996. }
  17997. obj.matrixAutoUpdate = false;
  17998. this.data.hierarchy[h].node.updateMatrix();
  17999. obj.matrixWorldNeedsUpdate = true;
  18000. }
  18001. }
  18002. };
  18003. THREE.KeyFrameAnimation.prototype = {
  18004. constructor: THREE.KeyFrameAnimation,
  18005. play: function ( startTime ) {
  18006. this.currentTime = startTime !== undefined ? startTime : 0;
  18007. if ( this.isPlaying === false ) {
  18008. this.isPlaying = true;
  18009. // reset key cache
  18010. var h, hl = this.hierarchy.length,
  18011. object,
  18012. node;
  18013. for ( h = 0; h < hl; h ++ ) {
  18014. object = this.hierarchy[ h ];
  18015. node = this.data.hierarchy[ h ];
  18016. if ( node.animationCache === undefined ) {
  18017. node.animationCache = {};
  18018. node.animationCache.prevKey = null;
  18019. node.animationCache.nextKey = null;
  18020. node.animationCache.originalMatrix = object.matrix;
  18021. }
  18022. var keys = this.data.hierarchy[h].keys;
  18023. if (keys.length) {
  18024. node.animationCache.prevKey = keys[ 0 ];
  18025. node.animationCache.nextKey = keys[ 1 ];
  18026. this.startTime = Math.min( keys[0].time, this.startTime );
  18027. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18028. }
  18029. }
  18030. this.update( 0 );
  18031. }
  18032. this.isPaused = false;
  18033. THREE.AnimationHandler.play( this );
  18034. },
  18035. stop: function () {
  18036. this.isPlaying = false;
  18037. this.isPaused = false;
  18038. THREE.AnimationHandler.stop( this );
  18039. // reset JIT matrix and remove cache
  18040. for ( var h = 0; h < this.data.hierarchy.length; h ++ ) {
  18041. var obj = this.hierarchy[ h ];
  18042. var node = this.data.hierarchy[ h ];
  18043. if ( node.animationCache !== undefined ) {
  18044. var original = node.animationCache.originalMatrix;
  18045. original.copy( obj.matrix );
  18046. obj.matrix = original;
  18047. delete node.animationCache;
  18048. }
  18049. }
  18050. },
  18051. update: function ( delta ) {
  18052. if ( this.isPlaying === false ) return;
  18053. this.currentTime += delta * this.timeScale;
  18054. //
  18055. var duration = this.data.length;
  18056. if ( this.loop === true && this.currentTime > duration ) {
  18057. this.currentTime %= duration;
  18058. }
  18059. this.currentTime = Math.min( this.currentTime, duration );
  18060. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18061. var object = this.hierarchy[ h ];
  18062. var node = this.data.hierarchy[ h ];
  18063. var keys = node.keys,
  18064. animationCache = node.animationCache;
  18065. if ( keys.length ) {
  18066. var prevKey = animationCache.prevKey;
  18067. var nextKey = animationCache.nextKey;
  18068. if ( nextKey.time <= this.currentTime ) {
  18069. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  18070. prevKey = nextKey;
  18071. nextKey = keys[ prevKey.index + 1 ];
  18072. }
  18073. animationCache.prevKey = prevKey;
  18074. animationCache.nextKey = nextKey;
  18075. }
  18076. if ( nextKey.time >= this.currentTime ) {
  18077. prevKey.interpolate( nextKey, this.currentTime );
  18078. } else {
  18079. prevKey.interpolate( nextKey, nextKey.time );
  18080. }
  18081. this.data.hierarchy[ h ].node.updateMatrix();
  18082. object.matrixWorldNeedsUpdate = true;
  18083. }
  18084. }
  18085. },
  18086. getNextKeyWith: function ( sid, h, key ) {
  18087. var keys = this.data.hierarchy[ h ].keys;
  18088. key = key % keys.length;
  18089. for ( ; key < keys.length; key ++ ) {
  18090. if ( keys[ key ].hasTarget( sid ) ) {
  18091. return keys[ key ];
  18092. }
  18093. }
  18094. return keys[ 0 ];
  18095. },
  18096. getPrevKeyWith: function ( sid, h, key ) {
  18097. var keys = this.data.hierarchy[ h ].keys;
  18098. key = key >= 0 ? key : key + keys.length;
  18099. for ( ; key >= 0; key -- ) {
  18100. if ( keys[ key ].hasTarget( sid ) ) {
  18101. return keys[ key ];
  18102. }
  18103. }
  18104. return keys[ keys.length - 1 ];
  18105. }
  18106. };
  18107. // File:src/extras/animation/MorphAnimation.js
  18108. /**
  18109. * @author mrdoob / http://mrdoob.com
  18110. * @author willy-vvu / http://willy-vvu.github.io
  18111. */
  18112. THREE.MorphAnimation = function ( mesh ) {
  18113. this.mesh = mesh;
  18114. this.frames = mesh.morphTargetInfluences.length;
  18115. this.currentTime = 0;
  18116. this.duration = 1000;
  18117. this.loop = true;
  18118. this.lastFrame = 0;
  18119. this.currentFrame = 0;
  18120. this.isPlaying = false;
  18121. };
  18122. THREE.MorphAnimation.prototype = {
  18123. constructor: THREE.MorphAnimation,
  18124. play: function () {
  18125. this.isPlaying = true;
  18126. },
  18127. pause: function () {
  18128. this.isPlaying = false;
  18129. },
  18130. update: function ( delta ) {
  18131. if ( this.isPlaying === false ) return;
  18132. this.currentTime += delta;
  18133. if ( this.loop === true && this.currentTime > this.duration ) {
  18134. this.currentTime %= this.duration;
  18135. }
  18136. this.currentTime = Math.min( this.currentTime, this.duration );
  18137. var interpolation = this.duration / this.frames;
  18138. var frame = Math.floor( this.currentTime / interpolation );
  18139. var influences = this.mesh.morphTargetInfluences;
  18140. if ( frame !== this.currentFrame ) {
  18141. influences[ this.lastFrame ] = 0;
  18142. influences[ this.currentFrame ] = 1;
  18143. influences[ frame ] = 0;
  18144. this.lastFrame = this.currentFrame;
  18145. this.currentFrame = frame;
  18146. }
  18147. influences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  18148. influences[ this.lastFrame ] = 1 - influences[ frame ];
  18149. }
  18150. };
  18151. // File:src/extras/geometries/BoxGeometry.js
  18152. /**
  18153. * @author mrdoob / http://mrdoob.com/
  18154. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18155. */
  18156. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18157. THREE.Geometry.call( this );
  18158. this.type = 'BoxGeometry';
  18159. this.parameters = {
  18160. width: width,
  18161. height: height,
  18162. depth: depth,
  18163. widthSegments: widthSegments,
  18164. heightSegments: heightSegments,
  18165. depthSegments: depthSegments
  18166. };
  18167. this.widthSegments = widthSegments || 1;
  18168. this.heightSegments = heightSegments || 1;
  18169. this.depthSegments = depthSegments || 1;
  18170. var scope = this;
  18171. var width_half = width / 2;
  18172. var height_half = height / 2;
  18173. var depth_half = depth / 2;
  18174. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half ); // px
  18175. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half ); // nx
  18176. buildPlane( 'x', 'z', 1, 1, width, depth, height_half ); // py
  18177. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half ); // ny
  18178. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half ); // pz
  18179. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half ); // nz
  18180. function buildPlane( u, v, udir, vdir, width, height, depth ) {
  18181. var w, ix, iy,
  18182. gridX = scope.widthSegments,
  18183. gridY = scope.heightSegments,
  18184. width_half = width / 2,
  18185. height_half = height / 2,
  18186. offset = scope.vertices.length;
  18187. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18188. w = 'z';
  18189. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18190. w = 'y';
  18191. gridY = scope.depthSegments;
  18192. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18193. w = 'x';
  18194. gridX = scope.depthSegments;
  18195. }
  18196. var gridX1 = gridX + 1,
  18197. gridY1 = gridY + 1,
  18198. segment_width = width / gridX,
  18199. segment_height = height / gridY,
  18200. normal = new THREE.Vector3();
  18201. normal[ w ] = depth > 0 ? 1 : - 1;
  18202. for ( iy = 0; iy < gridY1; iy ++ ) {
  18203. for ( ix = 0; ix < gridX1; ix ++ ) {
  18204. var vector = new THREE.Vector3();
  18205. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18206. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18207. vector[ w ] = depth;
  18208. scope.vertices.push( vector );
  18209. }
  18210. }
  18211. for ( iy = 0; iy < gridY; iy ++ ) {
  18212. for ( ix = 0; ix < gridX; ix ++ ) {
  18213. var a = ix + gridX1 * iy;
  18214. var b = ix + gridX1 * ( iy + 1 );
  18215. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18216. var d = ( ix + 1 ) + gridX1 * iy;
  18217. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18218. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18219. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18220. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18221. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18222. face.normal.copy( normal );
  18223. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18224. scope.faces.push( face );
  18225. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18226. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18227. face.normal.copy( normal );
  18228. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18229. scope.faces.push( face );
  18230. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18231. }
  18232. }
  18233. }
  18234. this.mergeVertices();
  18235. };
  18236. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18237. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  18238. THREE.CubeGeometry = THREE.BoxGeometry; // backwards compatibility
  18239. // File:src/extras/geometries/CircleGeometry.js
  18240. /**
  18241. * @author hughes
  18242. */
  18243. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18244. THREE.Geometry.call( this );
  18245. this.type = 'CircleGeometry';
  18246. this.parameters = {
  18247. radius: radius,
  18248. segments: segments,
  18249. thetaStart: thetaStart,
  18250. thetaLength: thetaLength
  18251. };
  18252. radius = radius || 50;
  18253. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18254. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18255. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18256. var i, uvs = [],
  18257. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18258. this.vertices.push(center);
  18259. uvs.push( centerUV );
  18260. for ( i = 0; i <= segments; i ++ ) {
  18261. var vertex = new THREE.Vector3();
  18262. var segment = thetaStart + i / segments * thetaLength;
  18263. vertex.x = radius * Math.cos( segment );
  18264. vertex.y = radius * Math.sin( segment );
  18265. this.vertices.push( vertex );
  18266. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18267. }
  18268. var n = new THREE.Vector3( 0, 0, 1 );
  18269. for ( i = 1; i <= segments; i ++ ) {
  18270. this.faces.push( new THREE.Face3( i, i + 1, 0, [ n.clone(), n.clone(), n.clone() ] ) );
  18271. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18272. }
  18273. this.computeFaceNormals();
  18274. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18275. };
  18276. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18277. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  18278. // File:src/extras/geometries/CircleBufferGeometry.js
  18279. /**
  18280. * @author benaadams / https://twitter.com/ben_a_adams
  18281. */
  18282. THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18283. THREE.BufferGeometry.call( this );
  18284. this.type = 'CircleBufferGeometry';
  18285. this.parameters = {
  18286. radius: radius,
  18287. segments: segments,
  18288. thetaStart: thetaStart,
  18289. thetaLength: thetaLength
  18290. };
  18291. radius = radius || 50;
  18292. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18293. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18294. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18295. var vertices = segments + 2;
  18296. var positions = new Float32Array( vertices * 3 );
  18297. var normals = new Float32Array( vertices * 3 );
  18298. var uvs = new Float32Array( vertices * 2 );
  18299. // center data is already zero, but need to set a few extras
  18300. normals[3] = 1.0;
  18301. uvs[0] = 0.5;
  18302. uvs[1] = 0.5;
  18303. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s++, i += 3, ii += 2 ) {
  18304. var segment = thetaStart + s / segments * thetaLength;
  18305. positions[i] = radius * Math.cos( segment );
  18306. positions[i + 1] = radius * Math.sin( segment );
  18307. normals[i + 2] = 1; // normal z
  18308. uvs[ii] = ( positions[i] / radius + 1 ) / 2;
  18309. uvs[ii + 1] = ( positions[i + 1] / radius + 1 ) / 2;
  18310. }
  18311. var indices = [];
  18312. for ( var i = 1; i <= segments; i ++ ) {
  18313. indices.push( i );
  18314. indices.push( i + 1 );
  18315. indices.push( 0 );
  18316. }
  18317. this.addAttribute( 'index', new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  18318. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  18319. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  18320. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  18321. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18322. };
  18323. THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  18324. THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry;
  18325. // File:src/extras/geometries/CylinderGeometry.js
  18326. /**
  18327. * @author mrdoob / http://mrdoob.com/
  18328. */
  18329. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  18330. THREE.Geometry.call( this );
  18331. this.type = 'CylinderGeometry';
  18332. this.parameters = {
  18333. radiusTop: radiusTop,
  18334. radiusBottom: radiusBottom,
  18335. height: height,
  18336. radialSegments: radialSegments,
  18337. heightSegments: heightSegments,
  18338. openEnded: openEnded,
  18339. thetaStart: thetaStart,
  18340. thetaLength: thetaLength
  18341. };
  18342. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18343. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18344. height = height !== undefined ? height : 100;
  18345. radialSegments = radialSegments || 8;
  18346. heightSegments = heightSegments || 1;
  18347. openEnded = openEnded !== undefined ? openEnded : false;
  18348. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18349. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  18350. var heightHalf = height / 2;
  18351. var x, y, vertices = [], uvs = [];
  18352. for ( y = 0; y <= heightSegments; y ++ ) {
  18353. var verticesRow = [];
  18354. var uvsRow = [];
  18355. var v = y / heightSegments;
  18356. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18357. for ( x = 0; x <= radialSegments; x ++ ) {
  18358. var u = x / radialSegments;
  18359. var vertex = new THREE.Vector3();
  18360. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  18361. vertex.y = - v * height + heightHalf;
  18362. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  18363. this.vertices.push( vertex );
  18364. verticesRow.push( this.vertices.length - 1 );
  18365. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18366. }
  18367. vertices.push( verticesRow );
  18368. uvs.push( uvsRow );
  18369. }
  18370. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18371. var na, nb;
  18372. for ( x = 0; x < radialSegments; x ++ ) {
  18373. if ( radiusTop !== 0 ) {
  18374. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18375. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18376. } else {
  18377. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18378. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18379. }
  18380. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18381. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18382. for ( y = 0; y < heightSegments; y ++ ) {
  18383. var v1 = vertices[ y ][ x ];
  18384. var v2 = vertices[ y + 1 ][ x ];
  18385. var v3 = vertices[ y + 1 ][ x + 1 ];
  18386. var v4 = vertices[ y ][ x + 1 ];
  18387. var n1 = na.clone();
  18388. var n2 = na.clone();
  18389. var n3 = nb.clone();
  18390. var n4 = nb.clone();
  18391. var uv1 = uvs[ y ][ x ].clone();
  18392. var uv2 = uvs[ y + 1 ][ x ].clone();
  18393. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18394. var uv4 = uvs[ y ][ x + 1 ].clone();
  18395. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18396. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18397. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18398. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18399. }
  18400. }
  18401. // top cap
  18402. if ( openEnded === false && radiusTop > 0 ) {
  18403. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18404. for ( x = 0; x < radialSegments; x ++ ) {
  18405. var v1 = vertices[ 0 ][ x ];
  18406. var v2 = vertices[ 0 ][ x + 1 ];
  18407. var v3 = this.vertices.length - 1;
  18408. var n1 = new THREE.Vector3( 0, 1, 0 );
  18409. var n2 = new THREE.Vector3( 0, 1, 0 );
  18410. var n3 = new THREE.Vector3( 0, 1, 0 );
  18411. var uv1 = uvs[ 0 ][ x ].clone();
  18412. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18413. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18414. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18415. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18416. }
  18417. }
  18418. // bottom cap
  18419. if ( openEnded === false && radiusBottom > 0 ) {
  18420. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18421. for ( x = 0; x < radialSegments; x ++ ) {
  18422. var v1 = vertices[ heightSegments ][ x + 1 ];
  18423. var v2 = vertices[ heightSegments ][ x ];
  18424. var v3 = this.vertices.length - 1;
  18425. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18426. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18427. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18428. var uv1 = uvs[ heightSegments ][ x + 1 ].clone();
  18429. var uv2 = uvs[ heightSegments ][ x ].clone();
  18430. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18431. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18432. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18433. }
  18434. }
  18435. this.computeFaceNormals();
  18436. };
  18437. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18438. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  18439. // File:src/extras/geometries/EdgesGeometry.js
  18440. /**
  18441. * @author WestLangley / http://github.com/WestLangley
  18442. */
  18443. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  18444. THREE.BufferGeometry.call( this );
  18445. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  18446. var thresholdDot = Math.cos( THREE.Math.degToRad( thresholdAngle ) );
  18447. var edge = [ 0, 0 ], hash = {};
  18448. var sortFunction = function ( a, b ) { return a - b };
  18449. var keys = [ 'a', 'b', 'c' ];
  18450. var geometry2;
  18451. if ( geometry instanceof THREE.BufferGeometry ) {
  18452. geometry2 = new THREE.Geometry();
  18453. geometry2.fromBufferGeometry( geometry );
  18454. } else {
  18455. geometry2 = geometry.clone();
  18456. }
  18457. geometry2.mergeVertices();
  18458. geometry2.computeFaceNormals();
  18459. var vertices = geometry2.vertices;
  18460. var faces = geometry2.faces;
  18461. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18462. var face = faces[ i ];
  18463. for ( var j = 0; j < 3; j ++ ) {
  18464. edge[ 0 ] = face[ keys[ j ] ];
  18465. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  18466. edge.sort( sortFunction );
  18467. var key = edge.toString();
  18468. if ( hash[ key ] === undefined ) {
  18469. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  18470. } else {
  18471. hash[ key ].face2 = i;
  18472. }
  18473. }
  18474. }
  18475. var coords = [];
  18476. for ( var key in hash ) {
  18477. var h = hash[ key ];
  18478. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  18479. var vertex = vertices[ h.vert1 ];
  18480. coords.push( vertex.x );
  18481. coords.push( vertex.y );
  18482. coords.push( vertex.z );
  18483. vertex = vertices[ h.vert2 ];
  18484. coords.push( vertex.x );
  18485. coords.push( vertex.y );
  18486. coords.push( vertex.z );
  18487. }
  18488. }
  18489. this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
  18490. };
  18491. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  18492. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  18493. // File:src/extras/geometries/ExtrudeGeometry.js
  18494. /**
  18495. * @author zz85 / http://www.lab4games.net/zz85/blog
  18496. *
  18497. * Creates extruded geometry from a path shape.
  18498. *
  18499. * parameters = {
  18500. *
  18501. * curveSegments: <int>, // number of points on the curves
  18502. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  18503. * amount: <int>, // Depth to extrude the shape
  18504. *
  18505. * bevelEnabled: <bool>, // turn on bevel
  18506. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18507. * bevelSize: <float>, // how far from shape outline is bevel
  18508. * bevelSegments: <int>, // number of bevel layers
  18509. *
  18510. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18511. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18512. *
  18513. * uvGenerator: <Object> // object that provides UV generator functions
  18514. *
  18515. * }
  18516. **/
  18517. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18518. if ( typeof( shapes ) === "undefined" ) {
  18519. shapes = [];
  18520. return;
  18521. }
  18522. THREE.Geometry.call( this );
  18523. this.type = 'ExtrudeGeometry';
  18524. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  18525. this.addShapeList( shapes, options );
  18526. this.computeFaceNormals();
  18527. // can't really use automatic vertex normals
  18528. // as then front and back sides get smoothed too
  18529. // should do separate smoothing just for sides
  18530. //this.computeVertexNormals();
  18531. //console.log( "took", ( Date.now() - startTime ) );
  18532. };
  18533. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18534. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  18535. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18536. var sl = shapes.length;
  18537. for ( var s = 0; s < sl; s ++ ) {
  18538. var shape = shapes[ s ];
  18539. this.addShape( shape, options );
  18540. }
  18541. };
  18542. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18543. var amount = options.amount !== undefined ? options.amount : 100;
  18544. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18545. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18546. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18547. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18548. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18549. var steps = options.steps !== undefined ? options.steps : 1;
  18550. var extrudePath = options.extrudePath;
  18551. var extrudePts, extrudeByPath = false;
  18552. // Use default WorldUVGenerator if no UV generators are specified.
  18553. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18554. var splineTube, binormal, normal, position2;
  18555. if ( extrudePath ) {
  18556. extrudePts = extrudePath.getSpacedPoints( steps );
  18557. extrudeByPath = true;
  18558. bevelEnabled = false; // bevels not supported for path extrusion
  18559. // SETUP TNB variables
  18560. // Reuse TNB from TubeGeomtry for now.
  18561. // TODO1 - have a .isClosed in spline?
  18562. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18563. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18564. binormal = new THREE.Vector3();
  18565. normal = new THREE.Vector3();
  18566. position2 = new THREE.Vector3();
  18567. }
  18568. // Safeguards if bevels are not enabled
  18569. if ( ! bevelEnabled ) {
  18570. bevelSegments = 0;
  18571. bevelThickness = 0;
  18572. bevelSize = 0;
  18573. }
  18574. // Variables initialization
  18575. var ahole, h, hl; // looping of holes
  18576. var scope = this;
  18577. var shapesOffset = this.vertices.length;
  18578. var shapePoints = shape.extractPoints( curveSegments );
  18579. var vertices = shapePoints.shape;
  18580. var holes = shapePoints.holes;
  18581. var reverse = ! THREE.Shape.Utils.isClockWise( vertices ) ;
  18582. if ( reverse ) {
  18583. vertices = vertices.reverse();
  18584. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18585. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18586. ahole = holes[ h ];
  18587. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18588. holes[ h ] = ahole.reverse();
  18589. }
  18590. }
  18591. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18592. }
  18593. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18594. /* Vertices */
  18595. var contour = vertices; // vertices has all points but contour has only points of circumference
  18596. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18597. ahole = holes[ h ];
  18598. vertices = vertices.concat( ahole );
  18599. }
  18600. function scalePt2 ( pt, vec, size ) {
  18601. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  18602. return vec.clone().multiplyScalar( size ).add( pt );
  18603. }
  18604. var b, bs, t, z,
  18605. vert, vlen = vertices.length,
  18606. face, flen = faces.length;
  18607. // Find directions for point movement
  18608. function getBevelVec( inPt, inPrev, inNext ) {
  18609. var EPSILON = 0.0000000001;
  18610. // computes for inPt the corresponding point inPt' on a new contour
  18611. // shifted by 1 unit (length of normalized vector) to the left
  18612. // if we walk along contour clockwise, this new contour is outside the old one
  18613. //
  18614. // inPt' is the intersection of the two lines parallel to the two
  18615. // adjacent edges of inPt at a distance of 1 unit on the left side.
  18616. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  18617. // good reading for geometry algorithms (here: line-line intersection)
  18618. // http://geomalgorithms.com/a05-_intersect-1.html
  18619. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  18620. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  18621. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  18622. // check for collinear edges
  18623. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18624. if ( Math.abs( collinear0 ) > EPSILON ) { // not collinear
  18625. // length of vectors for normalizing
  18626. var v_prev_len = Math.sqrt( v_prev_lensq );
  18627. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  18628. // shift adjacent points by unit vectors to the left
  18629. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  18630. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  18631. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  18632. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  18633. // scaling factor for v_prev to intersection point
  18634. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  18635. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  18636. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  18637. // vector from inPt to intersection point
  18638. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  18639. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  18640. // Don't normalize!, otherwise sharp corners become ugly
  18641. // but prevent crazy spikes
  18642. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  18643. if ( v_trans_lensq <= 2 ) {
  18644. return new THREE.Vector2( v_trans_x, v_trans_y );
  18645. } else {
  18646. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  18647. }
  18648. } else { // handle special case of collinear edges
  18649. var direction_eq = false; // assumes: opposite
  18650. if ( v_prev_x > EPSILON ) {
  18651. if ( v_next_x > EPSILON ) { direction_eq = true; }
  18652. } else {
  18653. if ( v_prev_x < - EPSILON ) {
  18654. if ( v_next_x < - EPSILON ) { direction_eq = true; }
  18655. } else {
  18656. if ( Math.sign(v_prev_y) === Math.sign(v_next_y) ) { direction_eq = true; }
  18657. }
  18658. }
  18659. if ( direction_eq ) {
  18660. // console.log("Warning: lines are a straight sequence");
  18661. v_trans_x = - v_prev_y;
  18662. v_trans_y = v_prev_x;
  18663. shrink_by = Math.sqrt( v_prev_lensq );
  18664. } else {
  18665. // console.log("Warning: lines are a straight spike");
  18666. v_trans_x = v_prev_x;
  18667. v_trans_y = v_prev_y;
  18668. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  18669. }
  18670. }
  18671. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  18672. }
  18673. var contourMovements = [];
  18674. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18675. if ( j === il ) j = 0;
  18676. if ( k === il ) k = 0;
  18677. // (j)---(i)---(k)
  18678. // console.log('i,j,k', i, j , k)
  18679. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18680. }
  18681. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18682. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18683. ahole = holes[ h ];
  18684. oneHoleMovements = [];
  18685. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18686. if ( j === il ) j = 0;
  18687. if ( k === il ) k = 0;
  18688. // (j)---(i)---(k)
  18689. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18690. }
  18691. holesMovements.push( oneHoleMovements );
  18692. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18693. }
  18694. // Loop bevelSegments, 1 for the front, 1 for the back
  18695. for ( b = 0; b < bevelSegments; b ++ ) {
  18696. //for ( b = bevelSegments; b > 0; b -- ) {
  18697. t = b / bevelSegments;
  18698. z = bevelThickness * ( 1 - t );
  18699. //z = bevelThickness * t;
  18700. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ) ; // curved
  18701. //bs = bevelSize * t ; // linear
  18702. // contract shape
  18703. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18704. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18705. v( vert.x, vert.y, - z );
  18706. }
  18707. // expand holes
  18708. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18709. ahole = holes[ h ];
  18710. oneHoleMovements = holesMovements[ h ];
  18711. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18712. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18713. v( vert.x, vert.y, - z );
  18714. }
  18715. }
  18716. }
  18717. bs = bevelSize;
  18718. // Back facing vertices
  18719. for ( i = 0; i < vlen; i ++ ) {
  18720. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18721. if ( ! extrudeByPath ) {
  18722. v( vert.x, vert.y, 0 );
  18723. } else {
  18724. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18725. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18726. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18727. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18728. v( position2.x, position2.y, position2.z );
  18729. }
  18730. }
  18731. // Add stepped vertices...
  18732. // Including front facing vertices
  18733. var s;
  18734. for ( s = 1; s <= steps; s ++ ) {
  18735. for ( i = 0; i < vlen; i ++ ) {
  18736. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18737. if ( ! extrudeByPath ) {
  18738. v( vert.x, vert.y, amount / steps * s );
  18739. } else {
  18740. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18741. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18742. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18743. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18744. v( position2.x, position2.y, position2.z );
  18745. }
  18746. }
  18747. }
  18748. // Add bevel segments planes
  18749. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18750. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18751. t = b / bevelSegments;
  18752. z = bevelThickness * ( 1 - t );
  18753. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18754. bs = bevelSize * Math.sin ( t * Math.PI / 2 ) ;
  18755. // contract shape
  18756. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18757. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18758. v( vert.x, vert.y, amount + z );
  18759. }
  18760. // expand holes
  18761. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18762. ahole = holes[ h ];
  18763. oneHoleMovements = holesMovements[ h ];
  18764. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18765. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18766. if ( ! extrudeByPath ) {
  18767. v( vert.x, vert.y, amount + z );
  18768. } else {
  18769. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18770. }
  18771. }
  18772. }
  18773. }
  18774. /* Faces */
  18775. // Top and bottom faces
  18776. buildLidFaces();
  18777. // Sides faces
  18778. buildSideFaces();
  18779. ///// Internal functions
  18780. function buildLidFaces() {
  18781. if ( bevelEnabled ) {
  18782. var layer = 0 ; // steps + 1
  18783. var offset = vlen * layer;
  18784. // Bottom faces
  18785. for ( i = 0; i < flen; i ++ ) {
  18786. face = faces[ i ];
  18787. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  18788. }
  18789. layer = steps + bevelSegments * 2;
  18790. offset = vlen * layer;
  18791. // Top faces
  18792. for ( i = 0; i < flen; i ++ ) {
  18793. face = faces[ i ];
  18794. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  18795. }
  18796. } else {
  18797. // Bottom faces
  18798. for ( i = 0; i < flen; i ++ ) {
  18799. face = faces[ i ];
  18800. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  18801. }
  18802. // Top faces
  18803. for ( i = 0; i < flen; i ++ ) {
  18804. face = faces[ i ];
  18805. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  18806. }
  18807. }
  18808. }
  18809. // Create faces for the z-sides of the shape
  18810. function buildSideFaces() {
  18811. var layeroffset = 0;
  18812. sidewalls( contour, layeroffset );
  18813. layeroffset += contour.length;
  18814. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18815. ahole = holes[ h ];
  18816. sidewalls( ahole, layeroffset );
  18817. //, true
  18818. layeroffset += ahole.length;
  18819. }
  18820. }
  18821. function sidewalls( contour, layeroffset ) {
  18822. var j, k;
  18823. i = contour.length;
  18824. while ( -- i >= 0 ) {
  18825. j = i;
  18826. k = i - 1;
  18827. if ( k < 0 ) k = contour.length - 1;
  18828. //console.log('b', i,j, i-1, k,vertices.length);
  18829. var s = 0, sl = steps + bevelSegments * 2;
  18830. for ( s = 0; s < sl; s ++ ) {
  18831. var slen1 = vlen * s;
  18832. var slen2 = vlen * ( s + 1 );
  18833. var a = layeroffset + j + slen1,
  18834. b = layeroffset + k + slen1,
  18835. c = layeroffset + k + slen2,
  18836. d = layeroffset + j + slen2;
  18837. f4( a, b, c, d, contour, s, sl, j, k );
  18838. }
  18839. }
  18840. }
  18841. function v( x, y, z ) {
  18842. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18843. }
  18844. function f3( a, b, c ) {
  18845. a += shapesOffset;
  18846. b += shapesOffset;
  18847. c += shapesOffset;
  18848. scope.faces.push( new THREE.Face3( a, b, c ) );
  18849. var uvs = uvgen.generateTopUV( scope, a, b, c );
  18850. scope.faceVertexUvs[ 0 ].push( uvs );
  18851. }
  18852. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18853. a += shapesOffset;
  18854. b += shapesOffset;
  18855. c += shapesOffset;
  18856. d += shapesOffset;
  18857. scope.faces.push( new THREE.Face3( a, b, d ) );
  18858. scope.faces.push( new THREE.Face3( b, c, d ) );
  18859. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  18860. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  18861. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  18862. }
  18863. };
  18864. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18865. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  18866. var vertices = geometry.vertices;
  18867. var a = vertices[ indexA ];
  18868. var b = vertices[ indexB ];
  18869. var c = vertices[ indexC ];
  18870. return [
  18871. new THREE.Vector2( a.x, a.y ),
  18872. new THREE.Vector2( b.x, b.y ),
  18873. new THREE.Vector2( c.x, c.y )
  18874. ];
  18875. },
  18876. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  18877. var vertices = geometry.vertices;
  18878. var a = vertices[ indexA ];
  18879. var b = vertices[ indexB ];
  18880. var c = vertices[ indexC ];
  18881. var d = vertices[ indexD ];
  18882. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  18883. return [
  18884. new THREE.Vector2( a.x, 1 - a.z ),
  18885. new THREE.Vector2( b.x, 1 - b.z ),
  18886. new THREE.Vector2( c.x, 1 - c.z ),
  18887. new THREE.Vector2( d.x, 1 - d.z )
  18888. ];
  18889. } else {
  18890. return [
  18891. new THREE.Vector2( a.y, 1 - a.z ),
  18892. new THREE.Vector2( b.y, 1 - b.z ),
  18893. new THREE.Vector2( c.y, 1 - c.z ),
  18894. new THREE.Vector2( d.y, 1 - d.z )
  18895. ];
  18896. }
  18897. }
  18898. };
  18899. // File:src/extras/geometries/ShapeGeometry.js
  18900. /**
  18901. * @author jonobr1 / http://jonobr1.com
  18902. *
  18903. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18904. * ExtrudeGeometry.
  18905. *
  18906. * parameters = {
  18907. *
  18908. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18909. *
  18910. * material: <int> // material index for front and back faces
  18911. * uvGenerator: <Object> // object that provides UV generator functions
  18912. *
  18913. * }
  18914. **/
  18915. THREE.ShapeGeometry = function ( shapes, options ) {
  18916. THREE.Geometry.call( this );
  18917. this.type = 'ShapeGeometry';
  18918. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  18919. this.addShapeList( shapes, options );
  18920. this.computeFaceNormals();
  18921. };
  18922. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18923. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  18924. /**
  18925. * Add an array of shapes to THREE.ShapeGeometry.
  18926. */
  18927. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18928. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  18929. this.addShape( shapes[ i ], options );
  18930. }
  18931. return this;
  18932. };
  18933. /**
  18934. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18935. */
  18936. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18937. if ( options === undefined ) options = {};
  18938. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18939. var material = options.material;
  18940. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18941. //
  18942. var i, l, hole;
  18943. var shapesOffset = this.vertices.length;
  18944. var shapePoints = shape.extractPoints( curveSegments );
  18945. var vertices = shapePoints.shape;
  18946. var holes = shapePoints.holes;
  18947. var reverse = ! THREE.Shape.Utils.isClockWise( vertices );
  18948. if ( reverse ) {
  18949. vertices = vertices.reverse();
  18950. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18951. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18952. hole = holes[ i ];
  18953. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18954. holes[ i ] = hole.reverse();
  18955. }
  18956. }
  18957. reverse = false;
  18958. }
  18959. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18960. // Vertices
  18961. var contour = vertices;
  18962. for ( i = 0, l = holes.length; i < l; i ++ ) {
  18963. hole = holes[ i ];
  18964. vertices = vertices.concat( hole );
  18965. }
  18966. //
  18967. var vert, vlen = vertices.length;
  18968. var face, flen = faces.length;
  18969. for ( i = 0; i < vlen; i ++ ) {
  18970. vert = vertices[ i ];
  18971. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18972. }
  18973. for ( i = 0; i < flen; i ++ ) {
  18974. face = faces[ i ];
  18975. var a = face[ 0 ] + shapesOffset;
  18976. var b = face[ 1 ] + shapesOffset;
  18977. var c = face[ 2 ] + shapesOffset;
  18978. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18979. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  18980. }
  18981. };
  18982. // File:src/extras/geometries/LatheGeometry.js
  18983. /**
  18984. * @author astrodud / http://astrodud.isgreat.org/
  18985. * @author zz85 / https://github.com/zz85
  18986. * @author bhouston / http://exocortex.com
  18987. */
  18988. // points - to create a closed torus, one must use a set of points
  18989. // like so: [ a, b, c, d, a ], see first is the same as last.
  18990. // segments - the number of circumference segments to create
  18991. // phiStart - the starting radian
  18992. // phiLength - the radian (0 to 2*PI) range of the lathed section
  18993. // 2*pi is a closed lathe, less than 2PI is a portion.
  18994. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  18995. THREE.Geometry.call( this );
  18996. this.type = 'LatheGeometry';
  18997. this.parameters = {
  18998. points: points,
  18999. segments: segments,
  19000. phiStart: phiStart,
  19001. phiLength: phiLength
  19002. };
  19003. segments = segments || 12;
  19004. phiStart = phiStart || 0;
  19005. phiLength = phiLength || 2 * Math.PI;
  19006. var inversePointLength = 1.0 / ( points.length - 1 );
  19007. var inverseSegments = 1.0 / segments;
  19008. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19009. var phi = phiStart + i * inverseSegments * phiLength;
  19010. var c = Math.cos( phi ),
  19011. s = Math.sin( phi );
  19012. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19013. var pt = points[ j ];
  19014. var vertex = new THREE.Vector3();
  19015. vertex.x = c * pt.x - s * pt.y;
  19016. vertex.y = s * pt.x + c * pt.y;
  19017. vertex.z = pt.z;
  19018. this.vertices.push( vertex );
  19019. }
  19020. }
  19021. var np = points.length;
  19022. for ( var i = 0, il = segments; i < il; i ++ ) {
  19023. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19024. var base = j + np * i;
  19025. var a = base;
  19026. var b = base + np;
  19027. var c = base + 1 + np;
  19028. var d = base + 1;
  19029. var u0 = i * inverseSegments;
  19030. var v0 = j * inversePointLength;
  19031. var u1 = u0 + inverseSegments;
  19032. var v1 = v0 + inversePointLength;
  19033. this.faces.push( new THREE.Face3( a, b, d ) );
  19034. this.faceVertexUvs[ 0 ].push( [
  19035. new THREE.Vector2( u0, v0 ),
  19036. new THREE.Vector2( u1, v0 ),
  19037. new THREE.Vector2( u0, v1 )
  19038. ] );
  19039. this.faces.push( new THREE.Face3( b, c, d ) );
  19040. this.faceVertexUvs[ 0 ].push( [
  19041. new THREE.Vector2( u1, v0 ),
  19042. new THREE.Vector2( u1, v1 ),
  19043. new THREE.Vector2( u0, v1 )
  19044. ] );
  19045. }
  19046. }
  19047. this.mergeVertices();
  19048. this.computeFaceNormals();
  19049. this.computeVertexNormals();
  19050. };
  19051. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19052. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  19053. // File:src/extras/geometries/PlaneGeometry.js
  19054. /**
  19055. * @author mrdoob / http://mrdoob.com/
  19056. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19057. */
  19058. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19059. THREE.Geometry.call( this );
  19060. this.type = 'PlaneGeometry';
  19061. this.parameters = {
  19062. width: width,
  19063. height: height,
  19064. widthSegments: widthSegments,
  19065. heightSegments: heightSegments
  19066. };
  19067. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  19068. };
  19069. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19070. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  19071. // File:src/extras/geometries/PlaneBufferGeometry.js
  19072. /**
  19073. * @author mrdoob / http://mrdoob.com/
  19074. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19075. */
  19076. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  19077. THREE.BufferGeometry.call( this );
  19078. this.type = 'PlaneBufferGeometry';
  19079. this.parameters = {
  19080. width: width,
  19081. height: height,
  19082. widthSegments: widthSegments,
  19083. heightSegments: heightSegments
  19084. };
  19085. var width_half = width / 2;
  19086. var height_half = height / 2;
  19087. var gridX = Math.floor( widthSegments ) || 1;
  19088. var gridY = Math.floor( heightSegments ) || 1;
  19089. var gridX1 = gridX + 1;
  19090. var gridY1 = gridY + 1;
  19091. var segment_width = width / gridX;
  19092. var segment_height = height / gridY;
  19093. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  19094. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  19095. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  19096. var offset = 0;
  19097. var offset2 = 0;
  19098. for ( var iy = 0; iy < gridY1; iy ++ ) {
  19099. var y = iy * segment_height - height_half;
  19100. for ( var ix = 0; ix < gridX1; ix ++ ) {
  19101. var x = ix * segment_width - width_half;
  19102. vertices[ offset ] = x;
  19103. vertices[ offset + 1 ] = - y;
  19104. normals[ offset + 2 ] = 1;
  19105. uvs[ offset2 ] = ix / gridX;
  19106. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  19107. offset += 3;
  19108. offset2 += 2;
  19109. }
  19110. }
  19111. offset = 0;
  19112. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  19113. for ( var iy = 0; iy < gridY; iy ++ ) {
  19114. for ( var ix = 0; ix < gridX; ix ++ ) {
  19115. var a = ix + gridX1 * iy;
  19116. var b = ix + gridX1 * ( iy + 1 );
  19117. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19118. var d = ( ix + 1 ) + gridX1 * iy;
  19119. indices[ offset ] = a;
  19120. indices[ offset + 1 ] = b;
  19121. indices[ offset + 2 ] = d;
  19122. indices[ offset + 3 ] = b;
  19123. indices[ offset + 4 ] = c;
  19124. indices[ offset + 5 ] = d;
  19125. offset += 6;
  19126. }
  19127. }
  19128. this.addAttribute( 'index', new THREE.BufferAttribute( indices, 1 ) );
  19129. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  19130. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  19131. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  19132. };
  19133. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19134. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  19135. // File:src/extras/geometries/RingGeometry.js
  19136. /**
  19137. * @author Kaleb Murphy
  19138. */
  19139. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19140. THREE.Geometry.call( this );
  19141. this.type = 'RingGeometry';
  19142. this.parameters = {
  19143. innerRadius: innerRadius,
  19144. outerRadius: outerRadius,
  19145. thetaSegments: thetaSegments,
  19146. phiSegments: phiSegments,
  19147. thetaStart: thetaStart,
  19148. thetaLength: thetaLength
  19149. };
  19150. innerRadius = innerRadius || 0;
  19151. outerRadius = outerRadius || 50;
  19152. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19153. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19154. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19155. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 8;
  19156. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19157. for ( i = 0; i < phiSegments + 1; i ++ ) { // concentric circles inside ring
  19158. for ( o = 0; o < thetaSegments + 1; o ++ ) { // number of segments per circle
  19159. var vertex = new THREE.Vector3();
  19160. var segment = thetaStart + o / thetaSegments * thetaLength;
  19161. vertex.x = radius * Math.cos( segment );
  19162. vertex.y = radius * Math.sin( segment );
  19163. this.vertices.push( vertex );
  19164. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19165. }
  19166. radius += radiusStep;
  19167. }
  19168. var n = new THREE.Vector3( 0, 0, 1 );
  19169. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19170. var thetaSegment = i * (thetaSegments + 1);
  19171. for ( o = 0; o < thetaSegments ; o ++ ) { // number of segments per circle
  19172. var segment = o + thetaSegment;
  19173. var v1 = segment;
  19174. var v2 = segment + thetaSegments + 1;
  19175. var v3 = segment + thetaSegments + 2;
  19176. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19177. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19178. v1 = segment;
  19179. v2 = segment + thetaSegments + 2;
  19180. v3 = segment + 1;
  19181. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19182. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19183. }
  19184. }
  19185. this.computeFaceNormals();
  19186. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19187. };
  19188. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19189. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  19190. // File:src/extras/geometries/SphereGeometry.js
  19191. /**
  19192. * @author mrdoob / http://mrdoob.com/
  19193. */
  19194. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19195. console.log( 'THREE.SphereGeometry: Consider using THREE.SphereBufferGeometry for lower memory footprint.' );
  19196. THREE.Geometry.call( this );
  19197. this.type = 'SphereGeometry';
  19198. this.parameters = {
  19199. radius: radius,
  19200. widthSegments: widthSegments,
  19201. heightSegments: heightSegments,
  19202. phiStart: phiStart,
  19203. phiLength: phiLength,
  19204. thetaStart: thetaStart,
  19205. thetaLength: thetaLength
  19206. };
  19207. radius = radius || 50;
  19208. widthSegments = Math.max( 2, Math.floor( widthSegments ) || 8 );
  19209. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19210. phiStart = phiStart !== undefined ? phiStart : 0;
  19211. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19212. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19213. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19214. var x, y, vertices = [], uvs = [];
  19215. for ( y = 0; y <= heightSegments; y ++ ) {
  19216. var verticesRow = [];
  19217. var uvsRow = [];
  19218. for ( x = 0; x <= widthSegments; x ++ ) {
  19219. var u = x / widthSegments;
  19220. var v = y / heightSegments;
  19221. var vertex = new THREE.Vector3();
  19222. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19223. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19224. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19225. this.vertices.push( vertex );
  19226. verticesRow.push( this.vertices.length - 1 );
  19227. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19228. }
  19229. vertices.push( verticesRow );
  19230. uvs.push( uvsRow );
  19231. }
  19232. for ( y = 0; y < heightSegments; y ++ ) {
  19233. for ( x = 0; x < widthSegments; x ++ ) {
  19234. var v1 = vertices[ y ][ x + 1 ];
  19235. var v2 = vertices[ y ][ x ];
  19236. var v3 = vertices[ y + 1 ][ x ];
  19237. var v4 = vertices[ y + 1 ][ x + 1 ];
  19238. var n1 = this.vertices[ v1 ].clone().normalize();
  19239. var n2 = this.vertices[ v2 ].clone().normalize();
  19240. var n3 = this.vertices[ v3 ].clone().normalize();
  19241. var n4 = this.vertices[ v4 ].clone().normalize();
  19242. var uv1 = uvs[ y ][ x + 1 ].clone();
  19243. var uv2 = uvs[ y ][ x ].clone();
  19244. var uv3 = uvs[ y + 1 ][ x ].clone();
  19245. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19246. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  19247. uv1.x = ( uv1.x + uv2.x ) / 2;
  19248. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19249. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19250. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  19251. uv3.x = ( uv3.x + uv4.x ) / 2;
  19252. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19253. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19254. } else {
  19255. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19256. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19257. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19258. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19259. }
  19260. }
  19261. }
  19262. this.computeFaceNormals();
  19263. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19264. };
  19265. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19266. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  19267. // File:src/extras/geometries/SphereBufferGeometry.js
  19268. /**
  19269. * @author benaadams / https://twitter.com/ben_a_adams
  19270. * based on THREE.SphereGeometry
  19271. */
  19272. THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19273. THREE.BufferGeometry.call( this );
  19274. this.type = 'SphereBufferGeometry';
  19275. this.parameters = {
  19276. radius: radius,
  19277. widthSegments: widthSegments,
  19278. heightSegments: heightSegments,
  19279. phiStart: phiStart,
  19280. phiLength: phiLength,
  19281. thetaStart: thetaStart,
  19282. thetaLength: thetaLength
  19283. };
  19284. radius = radius || 50;
  19285. widthSegments = Math.max( 2, Math.floor( widthSegments ) || 8 );
  19286. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19287. phiStart = phiStart !== undefined ? phiStart : 0;
  19288. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19289. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19290. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19291. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  19292. var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  19293. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3);
  19294. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  19295. var index = 0, vertices = [], normal = new THREE.Vector3();
  19296. for ( var y = 0; y <= heightSegments; y ++ ) {
  19297. var verticesRow = [];
  19298. var v = y / heightSegments;
  19299. for ( var x = 0; x <= widthSegments; x ++ ) {
  19300. var u = x / widthSegments;
  19301. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19302. var py = radius * Math.cos( thetaStart + v * thetaLength );
  19303. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19304. normal.set( px, py, pz ).normalize();
  19305. positions.setXYZ( index, px, py, pz );
  19306. normals.setXYZ( index, normal.x, normal.y, normal.z );
  19307. uvs.setXY( index, u, 1 - v );
  19308. verticesRow.push( index );
  19309. index++;
  19310. }
  19311. vertices.push( verticesRow );
  19312. }
  19313. var indices = [];
  19314. for ( var y = 0; y < heightSegments; y ++ ) {
  19315. for ( var x = 0; x < widthSegments; x ++ ) {
  19316. var v1 = vertices[ y ][ x + 1 ];
  19317. var v2 = vertices[ y ][ x ];
  19318. var v3 = vertices[ y + 1 ][ x ];
  19319. var v4 = vertices[ y + 1 ][ x + 1 ];
  19320. if ( y !== 0 ) indices.push( v1, v2, v4 );
  19321. if ( y !== heightSegments - 1 ) indices.push( v2, v3, v4 );
  19322. }
  19323. }
  19324. this.addAttribute( 'index', new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  19325. this.addAttribute( 'position', positions );
  19326. this.addAttribute( 'normal', normals );
  19327. this.addAttribute( 'uv', uvs );
  19328. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19329. };
  19330. THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  19331. THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry;
  19332. // File:src/extras/geometries/TextGeometry.js
  19333. /**
  19334. * @author zz85 / http://www.lab4games.net/zz85/blog
  19335. * @author alteredq / http://alteredqualia.com/
  19336. *
  19337. * For creating 3D text geometry in three.js
  19338. *
  19339. * Text = 3D Text
  19340. *
  19341. * parameters = {
  19342. * size: <float>, // size of the text
  19343. * height: <float>, // thickness to extrude text
  19344. * curveSegments: <int>, // number of points on the curves
  19345. *
  19346. * font: <string>, // font name
  19347. * weight: <string>, // font weight (normal, bold)
  19348. * style: <string>, // font style (normal, italics)
  19349. *
  19350. * bevelEnabled: <bool>, // turn on bevel
  19351. * bevelThickness: <float>, // how deep into text bevel goes
  19352. * bevelSize: <float>, // how far from text outline is bevel
  19353. * }
  19354. *
  19355. */
  19356. /* Usage Examples
  19357. // TextGeometry wrapper
  19358. var text3d = new TextGeometry( text, options );
  19359. // Complete manner
  19360. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19361. var text3d = new ExtrudeGeometry( textShapes, options );
  19362. */
  19363. THREE.TextGeometry = function ( text, parameters ) {
  19364. parameters = parameters || {};
  19365. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19366. // translate parameters to ExtrudeGeometry API
  19367. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19368. // defaults
  19369. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19370. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19371. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19372. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19373. this.type = 'TextGeometry';
  19374. };
  19375. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19376. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  19377. // File:src/extras/geometries/TorusGeometry.js
  19378. /**
  19379. * @author oosmoxiecode
  19380. * @author mrdoob / http://mrdoob.com/
  19381. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19382. */
  19383. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19384. THREE.Geometry.call( this );
  19385. this.type = 'TorusGeometry';
  19386. this.parameters = {
  19387. radius: radius,
  19388. tube: tube,
  19389. radialSegments: radialSegments,
  19390. tubularSegments: tubularSegments,
  19391. arc: arc
  19392. };
  19393. radius = radius || 100;
  19394. tube = tube || 40;
  19395. radialSegments = radialSegments || 8;
  19396. tubularSegments = tubularSegments || 6;
  19397. arc = arc || Math.PI * 2;
  19398. var center = new THREE.Vector3(), uvs = [], normals = [];
  19399. for ( var j = 0; j <= radialSegments; j ++ ) {
  19400. for ( var i = 0; i <= tubularSegments; i ++ ) {
  19401. var u = i / tubularSegments * arc;
  19402. var v = j / radialSegments * Math.PI * 2;
  19403. center.x = radius * Math.cos( u );
  19404. center.y = radius * Math.sin( u );
  19405. var vertex = new THREE.Vector3();
  19406. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19407. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19408. vertex.z = tube * Math.sin( v );
  19409. this.vertices.push( vertex );
  19410. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  19411. normals.push( vertex.clone().sub( center ).normalize() );
  19412. }
  19413. }
  19414. for ( var j = 1; j <= radialSegments; j ++ ) {
  19415. for ( var i = 1; i <= tubularSegments; i ++ ) {
  19416. var a = ( tubularSegments + 1 ) * j + i - 1;
  19417. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19418. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19419. var d = ( tubularSegments + 1 ) * j + i;
  19420. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19421. this.faces.push( face );
  19422. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19423. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19424. this.faces.push( face );
  19425. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19426. }
  19427. }
  19428. this.computeFaceNormals();
  19429. };
  19430. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19431. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  19432. // File:src/extras/geometries/TorusKnotGeometry.js
  19433. /**
  19434. * @author oosmoxiecode
  19435. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19436. */
  19437. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19438. THREE.Geometry.call( this );
  19439. this.type = 'TorusKnotGeometry';
  19440. this.parameters = {
  19441. radius: radius,
  19442. tube: tube,
  19443. radialSegments: radialSegments,
  19444. tubularSegments: tubularSegments,
  19445. p: p,
  19446. q: q,
  19447. heightScale: heightScale
  19448. };
  19449. radius = radius || 100;
  19450. tube = tube || 40;
  19451. radialSegments = radialSegments || 64;
  19452. tubularSegments = tubularSegments || 8;
  19453. p = p || 2;
  19454. q = q || 3;
  19455. heightScale = heightScale || 1;
  19456. var grid = new Array( radialSegments );
  19457. var tang = new THREE.Vector3();
  19458. var n = new THREE.Vector3();
  19459. var bitan = new THREE.Vector3();
  19460. for ( var i = 0; i < radialSegments; ++ i ) {
  19461. grid[ i ] = new Array( tubularSegments );
  19462. var u = i / radialSegments * 2 * p * Math.PI;
  19463. var p1 = getPos( u, q, p, radius, heightScale );
  19464. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  19465. tang.subVectors( p2, p1 );
  19466. n.addVectors( p2, p1 );
  19467. bitan.crossVectors( tang, n );
  19468. n.crossVectors( bitan, tang );
  19469. bitan.normalize();
  19470. n.normalize();
  19471. for ( var j = 0; j < tubularSegments; ++ j ) {
  19472. var v = j / tubularSegments * 2 * Math.PI;
  19473. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19474. var cy = tube * Math.sin( v );
  19475. var pos = new THREE.Vector3();
  19476. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19477. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19478. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19479. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  19480. }
  19481. }
  19482. for ( var i = 0; i < radialSegments; ++ i ) {
  19483. for ( var j = 0; j < tubularSegments; ++ j ) {
  19484. var ip = ( i + 1 ) % radialSegments;
  19485. var jp = ( j + 1 ) % tubularSegments;
  19486. var a = grid[ i ][ j ];
  19487. var b = grid[ ip ][ j ];
  19488. var c = grid[ ip ][ jp ];
  19489. var d = grid[ i ][ jp ];
  19490. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  19491. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  19492. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  19493. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  19494. this.faces.push( new THREE.Face3( a, b, d ) );
  19495. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19496. this.faces.push( new THREE.Face3( b, c, d ) );
  19497. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19498. }
  19499. }
  19500. this.computeFaceNormals();
  19501. this.computeVertexNormals();
  19502. function getPos( u, in_q, in_p, radius, heightScale ) {
  19503. var cu = Math.cos( u );
  19504. var su = Math.sin( u );
  19505. var quOverP = in_q / in_p * u;
  19506. var cs = Math.cos( quOverP );
  19507. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19508. var ty = radius * ( 2 + cs ) * su * 0.5;
  19509. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19510. return new THREE.Vector3( tx, ty, tz );
  19511. }
  19512. };
  19513. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19514. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  19515. // File:src/extras/geometries/TubeGeometry.js
  19516. /**
  19517. * @author WestLangley / https://github.com/WestLangley
  19518. * @author zz85 / https://github.com/zz85
  19519. * @author miningold / https://github.com/miningold
  19520. * @author jonobr1 / https://github.com/jonobr1
  19521. *
  19522. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19523. *
  19524. * Creates a tube which extrudes along a 3d spline
  19525. *
  19526. * Uses parallel transport frames as described in
  19527. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19528. */
  19529. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  19530. THREE.Geometry.call( this );
  19531. this.type = 'TubeGeometry';
  19532. this.parameters = {
  19533. path: path,
  19534. segments: segments,
  19535. radius: radius,
  19536. radialSegments: radialSegments,
  19537. closed: closed
  19538. };
  19539. segments = segments || 64;
  19540. radius = radius || 1;
  19541. radialSegments = radialSegments || 8;
  19542. closed = closed || false;
  19543. taper = taper || THREE.TubeGeometry.NoTaper;
  19544. var grid = [];
  19545. var scope = this,
  19546. tangent,
  19547. normal,
  19548. binormal,
  19549. numpoints = segments + 1,
  19550. u, v, r,
  19551. cx, cy,
  19552. pos, pos2 = new THREE.Vector3(),
  19553. i, j,
  19554. ip, jp,
  19555. a, b, c, d,
  19556. uva, uvb, uvc, uvd;
  19557. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  19558. tangents = frames.tangents,
  19559. normals = frames.normals,
  19560. binormals = frames.binormals;
  19561. // proxy internals
  19562. this.tangents = tangents;
  19563. this.normals = normals;
  19564. this.binormals = binormals;
  19565. function vert( x, y, z ) {
  19566. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19567. }
  19568. // construct the grid
  19569. for ( i = 0; i < numpoints; i ++ ) {
  19570. grid[ i ] = [];
  19571. u = i / ( numpoints - 1 );
  19572. pos = path.getPointAt( u );
  19573. tangent = tangents[ i ];
  19574. normal = normals[ i ];
  19575. binormal = binormals[ i ];
  19576. r = radius * taper( u );
  19577. for ( j = 0; j < radialSegments; j ++ ) {
  19578. v = j / radialSegments * 2 * Math.PI;
  19579. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19580. cy = r * Math.sin( v );
  19581. pos2.copy( pos );
  19582. pos2.x += cx * normal.x + cy * binormal.x;
  19583. pos2.y += cx * normal.y + cy * binormal.y;
  19584. pos2.z += cx * normal.z + cy * binormal.z;
  19585. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19586. }
  19587. }
  19588. // construct the mesh
  19589. for ( i = 0; i < segments; i ++ ) {
  19590. for ( j = 0; j < radialSegments; j ++ ) {
  19591. ip = ( closed ) ? (i + 1) % segments : i + 1;
  19592. jp = (j + 1) % radialSegments;
  19593. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19594. b = grid[ ip ][ j ];
  19595. c = grid[ ip ][ jp ];
  19596. d = grid[ i ][ jp ];
  19597. uva = new THREE.Vector2( i / segments, j / radialSegments );
  19598. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  19599. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  19600. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  19601. this.faces.push( new THREE.Face3( a, b, d ) );
  19602. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19603. this.faces.push( new THREE.Face3( b, c, d ) );
  19604. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19605. }
  19606. }
  19607. this.computeFaceNormals();
  19608. this.computeVertexNormals();
  19609. };
  19610. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19611. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  19612. THREE.TubeGeometry.NoTaper = function ( u ) {
  19613. return 1;
  19614. };
  19615. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  19616. return Math.sin( Math.PI * u );
  19617. };
  19618. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19619. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  19620. var normal = new THREE.Vector3(),
  19621. tangents = [],
  19622. normals = [],
  19623. binormals = [],
  19624. vec = new THREE.Vector3(),
  19625. mat = new THREE.Matrix4(),
  19626. numpoints = segments + 1,
  19627. theta,
  19628. epsilon = 0.0001,
  19629. smallest,
  19630. tx, ty, tz,
  19631. i, u;
  19632. // expose internals
  19633. this.tangents = tangents;
  19634. this.normals = normals;
  19635. this.binormals = binormals;
  19636. // compute the tangent vectors for each segment on the path
  19637. for ( i = 0; i < numpoints; i ++ ) {
  19638. u = i / ( numpoints - 1 );
  19639. tangents[ i ] = path.getTangentAt( u );
  19640. tangents[ i ].normalize();
  19641. }
  19642. initialNormal3();
  19643. /*
  19644. function initialNormal1(lastBinormal) {
  19645. // fixed start binormal. Has dangers of 0 vectors
  19646. normals[ 0 ] = new THREE.Vector3();
  19647. binormals[ 0 ] = new THREE.Vector3();
  19648. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19649. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19650. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19651. }
  19652. function initialNormal2() {
  19653. // This uses the Frenet-Serret formula for deriving binormal
  19654. var t2 = path.getTangentAt( epsilon );
  19655. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19656. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19657. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19658. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19659. }
  19660. */
  19661. function initialNormal3() {
  19662. // select an initial normal vector perpendicular to the first tangent vector,
  19663. // and in the direction of the smallest tangent xyz component
  19664. normals[ 0 ] = new THREE.Vector3();
  19665. binormals[ 0 ] = new THREE.Vector3();
  19666. smallest = Number.MAX_VALUE;
  19667. tx = Math.abs( tangents[ 0 ].x );
  19668. ty = Math.abs( tangents[ 0 ].y );
  19669. tz = Math.abs( tangents[ 0 ].z );
  19670. if ( tx <= smallest ) {
  19671. smallest = tx;
  19672. normal.set( 1, 0, 0 );
  19673. }
  19674. if ( ty <= smallest ) {
  19675. smallest = ty;
  19676. normal.set( 0, 1, 0 );
  19677. }
  19678. if ( tz <= smallest ) {
  19679. normal.set( 0, 0, 1 );
  19680. }
  19681. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19682. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19683. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19684. }
  19685. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19686. for ( i = 1; i < numpoints; i ++ ) {
  19687. normals[ i ] = normals[ i - 1 ].clone();
  19688. binormals[ i ] = binormals[ i - 1 ].clone();
  19689. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  19690. if ( vec.length() > epsilon ) {
  19691. vec.normalize();
  19692. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  19693. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19694. }
  19695. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19696. }
  19697. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19698. if ( closed ) {
  19699. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  19700. theta /= ( numpoints - 1 );
  19701. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  19702. theta = - theta;
  19703. }
  19704. for ( i = 1; i < numpoints; i ++ ) {
  19705. // twist a little...
  19706. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19707. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19708. }
  19709. }
  19710. };
  19711. // File:src/extras/geometries/PolyhedronGeometry.js
  19712. /**
  19713. * @author clockworkgeek / https://github.com/clockworkgeek
  19714. * @author timothypratley / https://github.com/timothypratley
  19715. * @author WestLangley / http://github.com/WestLangley
  19716. */
  19717. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  19718. THREE.Geometry.call( this );
  19719. this.type = 'PolyhedronGeometry';
  19720. this.parameters = {
  19721. vertices: vertices,
  19722. indices: indices,
  19723. radius: radius,
  19724. detail: detail
  19725. };
  19726. radius = radius || 1;
  19727. detail = detail || 0;
  19728. var that = this;
  19729. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  19730. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  19731. }
  19732. var p = this.vertices;
  19733. var faces = [];
  19734. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  19735. var v1 = p[ indices[ i ] ];
  19736. var v2 = p[ indices[ i + 1 ] ];
  19737. var v3 = p[ indices[ i + 2 ] ];
  19738. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19739. }
  19740. var centroid = new THREE.Vector3();
  19741. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19742. subdivide( faces[ i ], detail );
  19743. }
  19744. // Handle case when face straddles the seam
  19745. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19746. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19747. var x0 = uvs[ 0 ].x;
  19748. var x1 = uvs[ 1 ].x;
  19749. var x2 = uvs[ 2 ].x;
  19750. var max = Math.max( x0, Math.max( x1, x2 ) );
  19751. var min = Math.min( x0, Math.min( x1, x2 ) );
  19752. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19753. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19754. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19755. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19756. }
  19757. }
  19758. // Apply radius
  19759. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19760. this.vertices[ i ].multiplyScalar( radius );
  19761. }
  19762. // Merge vertices
  19763. this.mergeVertices();
  19764. this.computeFaceNormals();
  19765. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19766. // Project vector onto sphere's surface
  19767. function prepare( vector ) {
  19768. var vertex = vector.normalize().clone();
  19769. vertex.index = that.vertices.push( vertex ) - 1;
  19770. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19771. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19772. var v = inclination( vector ) / Math.PI + 0.5;
  19773. vertex.uv = new THREE.Vector2( u, 1 - v );
  19774. return vertex;
  19775. }
  19776. // Approximate a curved face with recursively sub-divided triangles.
  19777. function make( v1, v2, v3 ) {
  19778. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19779. that.faces.push( face );
  19780. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19781. var azi = azimuth( centroid );
  19782. that.faceVertexUvs[ 0 ].push( [
  19783. correctUV( v1.uv, v1, azi ),
  19784. correctUV( v2.uv, v2, azi ),
  19785. correctUV( v3.uv, v3, azi )
  19786. ] );
  19787. }
  19788. // Analytically subdivide a face to the required detail level.
  19789. function subdivide( face, detail ) {
  19790. var cols = Math.pow(2, detail);
  19791. var a = prepare( that.vertices[ face.a ] );
  19792. var b = prepare( that.vertices[ face.b ] );
  19793. var c = prepare( that.vertices[ face.c ] );
  19794. var v = [];
  19795. // Construct all of the vertices for this subdivision.
  19796. for ( var i = 0 ; i <= cols; i ++ ) {
  19797. v[ i ] = [];
  19798. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19799. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19800. var rows = cols - i;
  19801. for ( var j = 0; j <= rows; j ++) {
  19802. if ( j === 0 && i === cols ) {
  19803. v[ i ][ j ] = aj;
  19804. } else {
  19805. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19806. }
  19807. }
  19808. }
  19809. // Construct all of the faces.
  19810. for ( var i = 0; i < cols ; i ++ ) {
  19811. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19812. var k = Math.floor( j / 2 );
  19813. if ( j % 2 === 0 ) {
  19814. make(
  19815. v[ i ][ k + 1],
  19816. v[ i + 1 ][ k ],
  19817. v[ i ][ k ]
  19818. );
  19819. } else {
  19820. make(
  19821. v[ i ][ k + 1 ],
  19822. v[ i + 1][ k + 1],
  19823. v[ i + 1 ][ k ]
  19824. );
  19825. }
  19826. }
  19827. }
  19828. }
  19829. // Angle around the Y axis, counter-clockwise when looking from above.
  19830. function azimuth( vector ) {
  19831. return Math.atan2( vector.z, - vector.x );
  19832. }
  19833. // Angle above the XZ plane.
  19834. function inclination( vector ) {
  19835. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19836. }
  19837. // Texture fixing helper. Spheres have some odd behaviours.
  19838. function correctUV( uv, vector, azimuth ) {
  19839. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19840. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19841. return uv.clone();
  19842. }
  19843. };
  19844. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19845. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  19846. // File:src/extras/geometries/DodecahedronGeometry.js
  19847. /**
  19848. * @author Abe Pazos / https://hamoid.com
  19849. */
  19850. THREE.DodecahedronGeometry = function ( radius, detail ) {
  19851. this.parameters = {
  19852. radius: radius,
  19853. detail: detail
  19854. };
  19855. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19856. var r = 1 / t;
  19857. var vertices = [
  19858. // (±1, ±1, ±1)
  19859. -1, -1, -1, -1, -1, 1,
  19860. -1, 1, -1, -1, 1, 1,
  19861. 1, -1, -1, 1, -1, 1,
  19862. 1, 1, -1, 1, 1, 1,
  19863. // (0, ±1/φ, ±φ)
  19864. 0, -r, -t, 0, -r, t,
  19865. 0, r, -t, 0, r, t,
  19866. // (±1/φ, ±φ, 0)
  19867. -r, -t, 0, -r, t, 0,
  19868. r, -t, 0, r, t, 0,
  19869. // (±φ, 0, ±1/φ)
  19870. -t, 0, -r, t, 0, -r,
  19871. -t, 0, r, t, 0, r
  19872. ];
  19873. var indices = [
  19874. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19875. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19876. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19877. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19878. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19879. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19880. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19881. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19882. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19883. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19884. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19885. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19886. ];
  19887. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19888. };
  19889. THREE.DodecahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19890. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  19891. // File:src/extras/geometries/IcosahedronGeometry.js
  19892. /**
  19893. * @author timothypratley / https://github.com/timothypratley
  19894. */
  19895. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19896. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19897. var vertices = [
  19898. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19899. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19900. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19901. ];
  19902. var indices = [
  19903. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19904. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19905. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19906. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19907. ];
  19908. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19909. this.type = 'IcosahedronGeometry';
  19910. this.parameters = {
  19911. radius: radius,
  19912. detail: detail
  19913. };
  19914. };
  19915. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19916. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  19917. // File:src/extras/geometries/OctahedronGeometry.js
  19918. /**
  19919. * @author timothypratley / https://github.com/timothypratley
  19920. */
  19921. THREE.OctahedronGeometry = function ( radius, detail ) {
  19922. this.parameters = {
  19923. radius: radius,
  19924. detail: detail
  19925. };
  19926. var vertices = [
  19927. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0,- 1, 0, 0, 0, 1, 0, 0,- 1
  19928. ];
  19929. var indices = [
  19930. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  19931. ];
  19932. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19933. this.type = 'OctahedronGeometry';
  19934. this.parameters = {
  19935. radius: radius,
  19936. detail: detail
  19937. };
  19938. };
  19939. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19940. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  19941. // File:src/extras/geometries/TetrahedronGeometry.js
  19942. /**
  19943. * @author timothypratley / https://github.com/timothypratley
  19944. */
  19945. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19946. var vertices = [
  19947. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19948. ];
  19949. var indices = [
  19950. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19951. ];
  19952. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  19953. this.type = 'TetrahedronGeometry';
  19954. this.parameters = {
  19955. radius: radius,
  19956. detail: detail
  19957. };
  19958. };
  19959. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19960. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  19961. // File:src/extras/geometries/ParametricGeometry.js
  19962. /**
  19963. * @author zz85 / https://github.com/zz85
  19964. * Parametric Surfaces Geometry
  19965. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19966. *
  19967. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  19968. *
  19969. */
  19970. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  19971. THREE.Geometry.call( this );
  19972. this.type = 'ParametricGeometry';
  19973. this.parameters = {
  19974. func: func,
  19975. slices: slices,
  19976. stacks: stacks
  19977. };
  19978. var verts = this.vertices;
  19979. var faces = this.faces;
  19980. var uvs = this.faceVertexUvs[ 0 ];
  19981. var i, j, p;
  19982. var u, v;
  19983. var sliceCount = slices + 1;
  19984. for ( i = 0; i <= stacks; i ++ ) {
  19985. v = i / stacks;
  19986. for ( j = 0; j <= slices; j ++ ) {
  19987. u = j / slices;
  19988. p = func( u, v );
  19989. verts.push( p );
  19990. }
  19991. }
  19992. var a, b, c, d;
  19993. var uva, uvb, uvc, uvd;
  19994. for ( i = 0; i < stacks; i ++ ) {
  19995. for ( j = 0; j < slices; j ++ ) {
  19996. a = i * sliceCount + j;
  19997. b = i * sliceCount + j + 1;
  19998. c = (i + 1) * sliceCount + j + 1;
  19999. d = (i + 1) * sliceCount + j;
  20000. uva = new THREE.Vector2( j / slices, i / stacks );
  20001. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20002. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20003. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20004. faces.push( new THREE.Face3( a, b, d ) );
  20005. uvs.push( [ uva, uvb, uvd ] );
  20006. faces.push( new THREE.Face3( b, c, d ) );
  20007. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20008. }
  20009. }
  20010. // console.log(this);
  20011. // magic bullet
  20012. // var diff = this.mergeVertices();
  20013. // console.log('removed ', diff, ' vertices by merging');
  20014. this.computeFaceNormals();
  20015. this.computeVertexNormals();
  20016. };
  20017. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20018. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  20019. // File:src/extras/geometries/WireframeGeometry.js
  20020. /**
  20021. * @author mrdoob / http://mrdoob.com/
  20022. */
  20023. THREE.WireframeGeometry = function ( geometry ) {
  20024. THREE.BufferGeometry.call( this );
  20025. var edge = [ 0, 0 ], hash = {};
  20026. var sortFunction = function ( a, b ) { return a - b };
  20027. var keys = [ 'a', 'b', 'c' ];
  20028. if ( geometry instanceof THREE.Geometry ) {
  20029. var vertices = geometry.vertices;
  20030. var faces = geometry.faces;
  20031. var numEdges = 0;
  20032. // allocate maximal size
  20033. var edges = new Uint32Array( 6 * faces.length );
  20034. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20035. var face = faces[ i ];
  20036. for ( var j = 0; j < 3; j ++ ) {
  20037. edge[ 0 ] = face[ keys[ j ] ];
  20038. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20039. edge.sort( sortFunction );
  20040. var key = edge.toString();
  20041. if ( hash[ key ] === undefined ) {
  20042. edges[ 2 * numEdges ] = edge[ 0 ];
  20043. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20044. hash[ key ] = true;
  20045. numEdges ++;
  20046. }
  20047. }
  20048. }
  20049. var coords = new Float32Array( numEdges * 2 * 3 );
  20050. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20051. for ( var j = 0; j < 2; j ++ ) {
  20052. var vertex = vertices[ edges [ 2 * i + j] ];
  20053. var index = 6 * i + 3 * j;
  20054. coords[ index + 0 ] = vertex.x;
  20055. coords[ index + 1 ] = vertex.y;
  20056. coords[ index + 2 ] = vertex.z;
  20057. }
  20058. }
  20059. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20060. } else if ( geometry instanceof THREE.BufferGeometry ) {
  20061. if ( geometry.attributes.index !== undefined ) { // Indexed BufferGeometry
  20062. var vertices = geometry.attributes.position;
  20063. var indices = geometry.attributes.index.array;
  20064. var drawcalls = geometry.drawcalls;
  20065. var numEdges = 0;
  20066. if ( drawcalls.length === 0 ) {
  20067. drawcalls = [ { count : indices.length, index : 0, start : 0 } ];
  20068. }
  20069. // allocate maximal size
  20070. var edges = new Uint32Array( 2 * indices.length );
  20071. for ( var o = 0, ol = drawcalls.length; o < ol; ++ o ) {
  20072. var start = drawcalls[ o ].start;
  20073. var count = drawcalls[ o ].count;
  20074. var index = drawcalls[ o ].index;
  20075. for ( var i = start, il = start + count; i < il; i += 3 ) {
  20076. for ( var j = 0; j < 3; j ++ ) {
  20077. edge[ 0 ] = index + indices[ i + j ];
  20078. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  20079. edge.sort( sortFunction );
  20080. var key = edge.toString();
  20081. if ( hash[ key ] === undefined ) {
  20082. edges[ 2 * numEdges ] = edge[ 0 ];
  20083. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20084. hash[ key ] = true;
  20085. numEdges ++;
  20086. }
  20087. }
  20088. }
  20089. }
  20090. var coords = new Float32Array( numEdges * 2 * 3 );
  20091. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20092. for ( var j = 0; j < 2; j ++ ) {
  20093. var index = 6 * i + 3 * j;
  20094. var index2 = edges[2 * i + j];
  20095. coords[ index + 0 ] = vertices.getX( index2 );
  20096. coords[ index + 1 ] = vertices.getY( index2 );
  20097. coords[ index + 2 ] = vertices.getZ( index2 );
  20098. }
  20099. }
  20100. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20101. } else { // non-indexed BufferGeometry
  20102. var vertices = geometry.attributes.position.array;
  20103. var numEdges = vertices.length / 3;
  20104. var numTris = numEdges / 3;
  20105. var coords = new Float32Array( numEdges * 2 * 3 );
  20106. for ( var i = 0, l = numTris; i < l; i ++ ) {
  20107. for ( var j = 0; j < 3; j ++ ) {
  20108. var index = 18 * i + 6 * j;
  20109. var index1 = 9 * i + 3 * j;
  20110. coords[ index + 0 ] = vertices[ index1 ];
  20111. coords[ index + 1 ] = vertices[ index1 + 1 ];
  20112. coords[ index + 2 ] = vertices[ index1 + 2 ];
  20113. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  20114. coords[ index + 3 ] = vertices[ index2 ];
  20115. coords[ index + 4 ] = vertices[ index2 + 1 ];
  20116. coords[ index + 5 ] = vertices[ index2 + 2 ];
  20117. }
  20118. }
  20119. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  20120. }
  20121. }
  20122. };
  20123. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  20124. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  20125. // File:src/extras/helpers/AxisHelper.js
  20126. /**
  20127. * @author sroucheray / http://sroucheray.org/
  20128. * @author mrdoob / http://mrdoob.com/
  20129. */
  20130. THREE.AxisHelper = function ( size ) {
  20131. size = size || 1;
  20132. var vertices = new Float32Array( [
  20133. 0, 0, 0, size, 0, 0,
  20134. 0, 0, 0, 0, size, 0,
  20135. 0, 0, 0, 0, 0, size
  20136. ] );
  20137. var colors = new Float32Array( [
  20138. 1, 0, 0, 1, 0.6, 0,
  20139. 0, 1, 0, 0.6, 1, 0,
  20140. 0, 0, 1, 0, 0.6, 1
  20141. ] );
  20142. var geometry = new THREE.BufferGeometry();
  20143. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  20144. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  20145. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20146. THREE.LineSegments.call( this, geometry, material );
  20147. };
  20148. THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20149. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  20150. // File:src/extras/helpers/ArrowHelper.js
  20151. /**
  20152. * @author WestLangley / http://github.com/WestLangley
  20153. * @author zz85 / http://github.com/zz85
  20154. * @author bhouston / http://exocortex.com
  20155. *
  20156. * Creates an arrow for visualizing directions
  20157. *
  20158. * Parameters:
  20159. * dir - Vector3
  20160. * origin - Vector3
  20161. * length - Number
  20162. * color - color in hex value
  20163. * headLength - Number
  20164. * headWidth - Number
  20165. */
  20166. THREE.ArrowHelper = ( function () {
  20167. var lineGeometry = new THREE.Geometry();
  20168. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  20169. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20170. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20171. return function ( dir, origin, length, color, headLength, headWidth ) {
  20172. // dir is assumed to be normalized
  20173. THREE.Object3D.call( this );
  20174. if ( color === undefined ) color = 0xffff00;
  20175. if ( length === undefined ) length = 1;
  20176. if ( headLength === undefined ) headLength = 0.2 * length;
  20177. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20178. this.position.copy( origin );
  20179. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  20180. this.line.matrixAutoUpdate = false;
  20181. this.add( this.line );
  20182. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  20183. this.cone.matrixAutoUpdate = false;
  20184. this.add( this.cone );
  20185. this.setDirection( dir );
  20186. this.setLength( length, headLength, headWidth );
  20187. }
  20188. }() );
  20189. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20190. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  20191. THREE.ArrowHelper.prototype.setDirection = ( function () {
  20192. var axis = new THREE.Vector3();
  20193. var radians;
  20194. return function ( dir ) {
  20195. // dir is assumed to be normalized
  20196. if ( dir.y > 0.99999 ) {
  20197. this.quaternion.set( 0, 0, 0, 1 );
  20198. } else if ( dir.y < - 0.99999 ) {
  20199. this.quaternion.set( 1, 0, 0, 0 );
  20200. } else {
  20201. axis.set( dir.z, 0, - dir.x ).normalize();
  20202. radians = Math.acos( dir.y );
  20203. this.quaternion.setFromAxisAngle( axis, radians );
  20204. }
  20205. };
  20206. }() );
  20207. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20208. if ( headLength === undefined ) headLength = 0.2 * length;
  20209. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20210. this.line.scale.set( 1, length - headLength, 1 );
  20211. this.line.updateMatrix();
  20212. this.cone.scale.set( headWidth, headLength, headWidth );
  20213. this.cone.position.y = length;
  20214. this.cone.updateMatrix();
  20215. };
  20216. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  20217. this.line.material.color.set( color );
  20218. this.cone.material.color.set( color );
  20219. };
  20220. // File:src/extras/helpers/BoxHelper.js
  20221. /**
  20222. * @author mrdoob / http://mrdoob.com/
  20223. */
  20224. THREE.BoxHelper = function ( object ) {
  20225. var geometry = new THREE.BufferGeometry();
  20226. geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( 72 ), 3 ) );
  20227. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ) );
  20228. if ( object !== undefined ) {
  20229. this.update( object );
  20230. }
  20231. };
  20232. THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20233. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  20234. THREE.BoxHelper.prototype.update = function ( object ) {
  20235. var geometry = object.geometry;
  20236. if ( geometry.boundingBox === null ) {
  20237. geometry.computeBoundingBox();
  20238. }
  20239. var min = geometry.boundingBox.min;
  20240. var max = geometry.boundingBox.max;
  20241. /*
  20242. 5____4
  20243. 1/___0/|
  20244. | 6__|_7
  20245. 2/___3/
  20246. 0: max.x, max.y, max.z
  20247. 1: min.x, max.y, max.z
  20248. 2: min.x, min.y, max.z
  20249. 3: max.x, min.y, max.z
  20250. 4: max.x, max.y, min.z
  20251. 5: min.x, max.y, min.z
  20252. 6: min.x, min.y, min.z
  20253. 7: max.x, min.y, min.z
  20254. */
  20255. var vertices = this.geometry.attributes.position.array;
  20256. vertices[ 0 ] = max.x; vertices[ 1 ] = max.y; vertices[ 2 ] = max.z;
  20257. vertices[ 3 ] = min.x; vertices[ 4 ] = max.y; vertices[ 5 ] = max.z;
  20258. vertices[ 6 ] = min.x; vertices[ 7 ] = max.y; vertices[ 8 ] = max.z;
  20259. vertices[ 9 ] = min.x; vertices[ 10 ] = min.y; vertices[ 11 ] = max.z;
  20260. vertices[ 12 ] = min.x; vertices[ 13 ] = min.y; vertices[ 14 ] = max.z;
  20261. vertices[ 15 ] = max.x; vertices[ 16 ] = min.y; vertices[ 17 ] = max.z;
  20262. vertices[ 18 ] = max.x; vertices[ 19 ] = min.y; vertices[ 20 ] = max.z;
  20263. vertices[ 21 ] = max.x; vertices[ 22 ] = max.y; vertices[ 23 ] = max.z;
  20264. //
  20265. vertices[ 24 ] = max.x; vertices[ 25 ] = max.y; vertices[ 26 ] = min.z;
  20266. vertices[ 27 ] = min.x; vertices[ 28 ] = max.y; vertices[ 29 ] = min.z;
  20267. vertices[ 30 ] = min.x; vertices[ 31 ] = max.y; vertices[ 32 ] = min.z;
  20268. vertices[ 33 ] = min.x; vertices[ 34 ] = min.y; vertices[ 35 ] = min.z;
  20269. vertices[ 36 ] = min.x; vertices[ 37 ] = min.y; vertices[ 38 ] = min.z;
  20270. vertices[ 39 ] = max.x; vertices[ 40 ] = min.y; vertices[ 41 ] = min.z;
  20271. vertices[ 42 ] = max.x; vertices[ 43 ] = min.y; vertices[ 44 ] = min.z;
  20272. vertices[ 45 ] = max.x; vertices[ 46 ] = max.y; vertices[ 47 ] = min.z;
  20273. //
  20274. vertices[ 48 ] = max.x; vertices[ 49 ] = max.y; vertices[ 50 ] = max.z;
  20275. vertices[ 51 ] = max.x; vertices[ 52 ] = max.y; vertices[ 53 ] = min.z;
  20276. vertices[ 54 ] = min.x; vertices[ 55 ] = max.y; vertices[ 56 ] = max.z;
  20277. vertices[ 57 ] = min.x; vertices[ 58 ] = max.y; vertices[ 59 ] = min.z;
  20278. vertices[ 60 ] = min.x; vertices[ 61 ] = min.y; vertices[ 62 ] = max.z;
  20279. vertices[ 63 ] = min.x; vertices[ 64 ] = min.y; vertices[ 65 ] = min.z;
  20280. vertices[ 66 ] = max.x; vertices[ 67 ] = min.y; vertices[ 68 ] = max.z;
  20281. vertices[ 69 ] = max.x; vertices[ 70 ] = min.y; vertices[ 71 ] = min.z;
  20282. this.geometry.attributes.position.needsUpdate = true;
  20283. this.geometry.computeBoundingSphere();
  20284. this.matrix = object.matrixWorld;
  20285. this.matrixAutoUpdate = false;
  20286. };
  20287. // File:src/extras/helpers/BoundingBoxHelper.js
  20288. /**
  20289. * @author WestLangley / http://github.com/WestLangley
  20290. */
  20291. // a helper to show the world-axis-aligned bounding box for an object
  20292. THREE.BoundingBoxHelper = function ( object, hex ) {
  20293. var color = ( hex !== undefined ) ? hex : 0x888888;
  20294. this.object = object;
  20295. this.box = new THREE.Box3();
  20296. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20297. };
  20298. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20299. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  20300. THREE.BoundingBoxHelper.prototype.update = function () {
  20301. this.box.setFromObject( this.object );
  20302. this.box.size( this.scale );
  20303. this.box.center( this.position );
  20304. };
  20305. // File:src/extras/helpers/CameraHelper.js
  20306. /**
  20307. * @author alteredq / http://alteredqualia.com/
  20308. *
  20309. * - shows frustum, line of sight and up of the camera
  20310. * - suitable for fast updates
  20311. * - based on frustum visualization in lightgl.js shadowmap example
  20312. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20313. */
  20314. THREE.CameraHelper = function ( camera ) {
  20315. var geometry = new THREE.Geometry();
  20316. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20317. var pointMap = {};
  20318. // colors
  20319. var hexFrustum = 0xffaa00;
  20320. var hexCone = 0xff0000;
  20321. var hexUp = 0x00aaff;
  20322. var hexTarget = 0xffffff;
  20323. var hexCross = 0x333333;
  20324. // near
  20325. addLine( "n1", "n2", hexFrustum );
  20326. addLine( "n2", "n4", hexFrustum );
  20327. addLine( "n4", "n3", hexFrustum );
  20328. addLine( "n3", "n1", hexFrustum );
  20329. // far
  20330. addLine( "f1", "f2", hexFrustum );
  20331. addLine( "f2", "f4", hexFrustum );
  20332. addLine( "f4", "f3", hexFrustum );
  20333. addLine( "f3", "f1", hexFrustum );
  20334. // sides
  20335. addLine( "n1", "f1", hexFrustum );
  20336. addLine( "n2", "f2", hexFrustum );
  20337. addLine( "n3", "f3", hexFrustum );
  20338. addLine( "n4", "f4", hexFrustum );
  20339. // cone
  20340. addLine( "p", "n1", hexCone );
  20341. addLine( "p", "n2", hexCone );
  20342. addLine( "p", "n3", hexCone );
  20343. addLine( "p", "n4", hexCone );
  20344. // up
  20345. addLine( "u1", "u2", hexUp );
  20346. addLine( "u2", "u3", hexUp );
  20347. addLine( "u3", "u1", hexUp );
  20348. // target
  20349. addLine( "c", "t", hexTarget );
  20350. addLine( "p", "c", hexCross );
  20351. // cross
  20352. addLine( "cn1", "cn2", hexCross );
  20353. addLine( "cn3", "cn4", hexCross );
  20354. addLine( "cf1", "cf2", hexCross );
  20355. addLine( "cf3", "cf4", hexCross );
  20356. function addLine( a, b, hex ) {
  20357. addPoint( a, hex );
  20358. addPoint( b, hex );
  20359. }
  20360. function addPoint( id, hex ) {
  20361. geometry.vertices.push( new THREE.Vector3() );
  20362. geometry.colors.push( new THREE.Color( hex ) );
  20363. if ( pointMap[ id ] === undefined ) {
  20364. pointMap[ id ] = [];
  20365. }
  20366. pointMap[ id ].push( geometry.vertices.length - 1 );
  20367. }
  20368. THREE.LineSegments.call( this, geometry, material );
  20369. this.camera = camera;
  20370. this.matrix = camera.matrixWorld;
  20371. this.matrixAutoUpdate = false;
  20372. this.pointMap = pointMap;
  20373. this.update();
  20374. };
  20375. THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20376. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  20377. THREE.CameraHelper.prototype.update = function () {
  20378. var geometry, pointMap;
  20379. var vector = new THREE.Vector3();
  20380. var camera = new THREE.Camera();
  20381. var setPoint = function ( point, x, y, z ) {
  20382. vector.set( x, y, z ).unproject( camera );
  20383. var points = pointMap[ point ];
  20384. if ( points !== undefined ) {
  20385. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20386. geometry.vertices[ points[ i ] ].copy( vector );
  20387. }
  20388. }
  20389. };
  20390. return function () {
  20391. geometry = this.geometry;
  20392. pointMap = this.pointMap;
  20393. var w = 1, h = 1;
  20394. // we need just camera projection matrix
  20395. // world matrix must be identity
  20396. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20397. // center / target
  20398. setPoint( "c", 0, 0, - 1 );
  20399. setPoint( "t", 0, 0, 1 );
  20400. // near
  20401. setPoint( "n1", - w, - h, - 1 );
  20402. setPoint( "n2", w, - h, - 1 );
  20403. setPoint( "n3", - w, h, - 1 );
  20404. setPoint( "n4", w, h, - 1 );
  20405. // far
  20406. setPoint( "f1", - w, - h, 1 );
  20407. setPoint( "f2", w, - h, 1 );
  20408. setPoint( "f3", - w, h, 1 );
  20409. setPoint( "f4", w, h, 1 );
  20410. // up
  20411. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  20412. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  20413. setPoint( "u3", 0, h * 2, - 1 );
  20414. // cross
  20415. setPoint( "cf1", - w, 0, 1 );
  20416. setPoint( "cf2", w, 0, 1 );
  20417. setPoint( "cf3", 0, - h, 1 );
  20418. setPoint( "cf4", 0, h, 1 );
  20419. setPoint( "cn1", - w, 0, - 1 );
  20420. setPoint( "cn2", w, 0, - 1 );
  20421. setPoint( "cn3", 0, - h, - 1 );
  20422. setPoint( "cn4", 0, h, - 1 );
  20423. geometry.verticesNeedUpdate = true;
  20424. };
  20425. }();
  20426. // File:src/extras/helpers/DirectionalLightHelper.js
  20427. /**
  20428. * @author alteredq / http://alteredqualia.com/
  20429. * @author mrdoob / http://mrdoob.com/
  20430. * @author WestLangley / http://github.com/WestLangley
  20431. */
  20432. THREE.DirectionalLightHelper = function ( light, size ) {
  20433. THREE.Object3D.call( this );
  20434. this.light = light;
  20435. this.light.updateMatrixWorld();
  20436. this.matrix = light.matrixWorld;
  20437. this.matrixAutoUpdate = false;
  20438. size = size || 1;
  20439. var geometry = new THREE.Geometry();
  20440. geometry.vertices.push(
  20441. new THREE.Vector3( - size, size, 0 ),
  20442. new THREE.Vector3( size, size, 0 ),
  20443. new THREE.Vector3( size, - size, 0 ),
  20444. new THREE.Vector3( - size, - size, 0 ),
  20445. new THREE.Vector3( - size, size, 0 )
  20446. );
  20447. var material = new THREE.LineBasicMaterial( { fog: false } );
  20448. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20449. this.lightPlane = new THREE.Line( geometry, material );
  20450. this.add( this.lightPlane );
  20451. geometry = new THREE.Geometry();
  20452. geometry.vertices.push(
  20453. new THREE.Vector3(),
  20454. new THREE.Vector3()
  20455. );
  20456. material = new THREE.LineBasicMaterial( { fog: false } );
  20457. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20458. this.targetLine = new THREE.Line( geometry, material );
  20459. this.add( this.targetLine );
  20460. this.update();
  20461. };
  20462. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20463. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  20464. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20465. this.lightPlane.geometry.dispose();
  20466. this.lightPlane.material.dispose();
  20467. this.targetLine.geometry.dispose();
  20468. this.targetLine.material.dispose();
  20469. };
  20470. THREE.DirectionalLightHelper.prototype.update = function () {
  20471. var v1 = new THREE.Vector3();
  20472. var v2 = new THREE.Vector3();
  20473. var v3 = new THREE.Vector3();
  20474. return function () {
  20475. v1.setFromMatrixPosition( this.light.matrixWorld );
  20476. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20477. v3.subVectors( v2, v1 );
  20478. this.lightPlane.lookAt( v3 );
  20479. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20480. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20481. this.targetLine.geometry.verticesNeedUpdate = true;
  20482. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20483. };
  20484. }();
  20485. // File:src/extras/helpers/EdgesHelper.js
  20486. /**
  20487. * @author WestLangley / http://github.com/WestLangley
  20488. * @param object THREE.Mesh whose geometry will be used
  20489. * @param hex line color
  20490. * @param thresholdAngle the minimum angle (in degrees),
  20491. * between the face normals of adjacent faces,
  20492. * that is required to render an edge. A value of 10 means
  20493. * an edge is only rendered if the angle is at least 10 degrees.
  20494. */
  20495. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  20496. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20497. THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) );
  20498. this.matrix = object.matrixWorld;
  20499. this.matrixAutoUpdate = false;
  20500. };
  20501. THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20502. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  20503. // File:src/extras/helpers/FaceNormalsHelper.js
  20504. /**
  20505. * @author mrdoob / http://mrdoob.com/
  20506. * @author WestLangley / http://github.com/WestLangley
  20507. */
  20508. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20509. this.object = object;
  20510. this.size = ( size !== undefined ) ? size : 1;
  20511. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20512. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20513. var geometry = new THREE.Geometry();
  20514. var faces = this.object.geometry.faces;
  20515. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20516. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20517. }
  20518. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  20519. this.matrixAutoUpdate = false;
  20520. this.normalMatrix = new THREE.Matrix3();
  20521. this.update();
  20522. };
  20523. THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20524. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  20525. THREE.FaceNormalsHelper.prototype.update = function () {
  20526. var vertices = this.geometry.vertices;
  20527. var object = this.object;
  20528. var objectVertices = object.geometry.vertices;
  20529. var objectFaces = object.geometry.faces;
  20530. var objectWorldMatrix = object.matrixWorld;
  20531. object.updateMatrixWorld( true );
  20532. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  20533. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  20534. var face = objectFaces[ i ];
  20535. vertices[ i2 ].copy( objectVertices[ face.a ] )
  20536. .add( objectVertices[ face.b ] )
  20537. .add( objectVertices[ face.c ] )
  20538. .divideScalar( 3 )
  20539. .applyMatrix4( objectWorldMatrix );
  20540. vertices[ i2 + 1 ].copy( face.normal )
  20541. .applyMatrix3( this.normalMatrix )
  20542. .normalize()
  20543. .multiplyScalar( this.size )
  20544. .add( vertices[ i2 ] );
  20545. }
  20546. this.geometry.verticesNeedUpdate = true;
  20547. return this;
  20548. };
  20549. // File:src/extras/helpers/GridHelper.js
  20550. /**
  20551. * @author mrdoob / http://mrdoob.com/
  20552. */
  20553. THREE.GridHelper = function ( size, step ) {
  20554. var geometry = new THREE.Geometry();
  20555. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20556. this.color1 = new THREE.Color( 0x444444 );
  20557. this.color2 = new THREE.Color( 0x888888 );
  20558. for ( var i = - size; i <= size; i += step ) {
  20559. geometry.vertices.push(
  20560. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20561. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20562. );
  20563. var color = i === 0 ? this.color1 : this.color2;
  20564. geometry.colors.push( color, color, color, color );
  20565. }
  20566. THREE.LineSegments.call( this, geometry, material );
  20567. };
  20568. THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20569. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  20570. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20571. this.color1.set( colorCenterLine );
  20572. this.color2.set( colorGrid );
  20573. this.geometry.colorsNeedUpdate = true;
  20574. };
  20575. // File:src/extras/helpers/HemisphereLightHelper.js
  20576. /**
  20577. * @author alteredq / http://alteredqualia.com/
  20578. * @author mrdoob / http://mrdoob.com/
  20579. */
  20580. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  20581. THREE.Object3D.call( this );
  20582. this.light = light;
  20583. this.light.updateMatrixWorld();
  20584. this.matrix = light.matrixWorld;
  20585. this.matrixAutoUpdate = false;
  20586. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20587. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20588. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20589. for ( var i = 0, il = 8; i < il; i ++ ) {
  20590. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20591. }
  20592. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20593. this.lightSphere = new THREE.Mesh( geometry, material );
  20594. this.add( this.lightSphere );
  20595. this.update();
  20596. };
  20597. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20598. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  20599. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20600. this.lightSphere.geometry.dispose();
  20601. this.lightSphere.material.dispose();
  20602. };
  20603. THREE.HemisphereLightHelper.prototype.update = function () {
  20604. var vector = new THREE.Vector3();
  20605. return function () {
  20606. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20607. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20608. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20609. this.lightSphere.geometry.colorsNeedUpdate = true;
  20610. }
  20611. }();
  20612. // File:src/extras/helpers/PointLightHelper.js
  20613. /**
  20614. * @author alteredq / http://alteredqualia.com/
  20615. * @author mrdoob / http://mrdoob.com/
  20616. */
  20617. THREE.PointLightHelper = function ( light, sphereSize ) {
  20618. this.light = light;
  20619. this.light.updateMatrixWorld();
  20620. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20621. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20622. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20623. THREE.Mesh.call( this, geometry, material );
  20624. this.matrix = this.light.matrixWorld;
  20625. this.matrixAutoUpdate = false;
  20626. /*
  20627. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20628. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20629. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20630. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20631. var d = light.distance;
  20632. if ( d === 0.0 ) {
  20633. this.lightDistance.visible = false;
  20634. } else {
  20635. this.lightDistance.scale.set( d, d, d );
  20636. }
  20637. this.add( this.lightDistance );
  20638. */
  20639. };
  20640. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20641. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  20642. THREE.PointLightHelper.prototype.dispose = function () {
  20643. this.geometry.dispose();
  20644. this.material.dispose();
  20645. };
  20646. THREE.PointLightHelper.prototype.update = function () {
  20647. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20648. /*
  20649. var d = this.light.distance;
  20650. if ( d === 0.0 ) {
  20651. this.lightDistance.visible = false;
  20652. } else {
  20653. this.lightDistance.visible = true;
  20654. this.lightDistance.scale.set( d, d, d );
  20655. }
  20656. */
  20657. };
  20658. // File:src/extras/helpers/SkeletonHelper.js
  20659. /**
  20660. * @author Sean Griffin / http://twitter.com/sgrif
  20661. * @author Michael Guerrero / http://realitymeltdown.com
  20662. * @author mrdoob / http://mrdoob.com/
  20663. * @author ikerr / http://verold.com
  20664. */
  20665. THREE.SkeletonHelper = function ( object ) {
  20666. this.bones = this.getBoneList( object );
  20667. var geometry = new THREE.Geometry();
  20668. for ( var i = 0; i < this.bones.length; i ++ ) {
  20669. var bone = this.bones[ i ];
  20670. if ( bone.parent instanceof THREE.Bone ) {
  20671. geometry.vertices.push( new THREE.Vector3() );
  20672. geometry.vertices.push( new THREE.Vector3() );
  20673. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  20674. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  20675. }
  20676. }
  20677. geometry.dynamic = true;
  20678. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  20679. THREE.LineSegments.call( this, geometry, material );
  20680. this.root = object;
  20681. this.matrix = object.matrixWorld;
  20682. this.matrixAutoUpdate = false;
  20683. this.update();
  20684. };
  20685. THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20686. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  20687. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  20688. var boneList = [];
  20689. if ( object instanceof THREE.Bone ) {
  20690. boneList.push( object );
  20691. }
  20692. for ( var i = 0; i < object.children.length; i ++ ) {
  20693. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  20694. }
  20695. return boneList;
  20696. };
  20697. THREE.SkeletonHelper.prototype.update = function () {
  20698. var geometry = this.geometry;
  20699. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  20700. var boneMatrix = new THREE.Matrix4();
  20701. var j = 0;
  20702. for ( var i = 0; i < this.bones.length; i ++ ) {
  20703. var bone = this.bones[ i ];
  20704. if ( bone.parent instanceof THREE.Bone ) {
  20705. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  20706. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  20707. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  20708. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  20709. j += 2;
  20710. }
  20711. }
  20712. geometry.verticesNeedUpdate = true;
  20713. geometry.computeBoundingSphere();
  20714. };
  20715. // File:src/extras/helpers/SpotLightHelper.js
  20716. /**
  20717. * @author alteredq / http://alteredqualia.com/
  20718. * @author mrdoob / http://mrdoob.com/
  20719. * @author WestLangley / http://github.com/WestLangley
  20720. */
  20721. THREE.SpotLightHelper = function ( light ) {
  20722. THREE.Object3D.call( this );
  20723. this.light = light;
  20724. this.light.updateMatrixWorld();
  20725. this.matrix = light.matrixWorld;
  20726. this.matrixAutoUpdate = false;
  20727. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20728. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20729. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20730. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20731. this.cone = new THREE.Mesh( geometry, material );
  20732. this.add( this.cone );
  20733. this.update();
  20734. };
  20735. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20736. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  20737. THREE.SpotLightHelper.prototype.dispose = function () {
  20738. this.cone.geometry.dispose();
  20739. this.cone.material.dispose();
  20740. };
  20741. THREE.SpotLightHelper.prototype.update = function () {
  20742. var vector = new THREE.Vector3();
  20743. var vector2 = new THREE.Vector3();
  20744. return function () {
  20745. var coneLength = this.light.distance ? this.light.distance : 10000;
  20746. var coneWidth = coneLength * Math.tan( this.light.angle );
  20747. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20748. vector.setFromMatrixPosition( this.light.matrixWorld );
  20749. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20750. this.cone.lookAt( vector2.sub( vector ) );
  20751. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20752. };
  20753. }();
  20754. // File:src/extras/helpers/VertexNormalsHelper.js
  20755. /**
  20756. * @author mrdoob / http://mrdoob.com/
  20757. * @author WestLangley / http://github.com/WestLangley
  20758. */
  20759. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20760. this.object = object;
  20761. this.size = ( size !== undefined ) ? size : 1;
  20762. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20763. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20764. var geometry = new THREE.Geometry();
  20765. var faces = object.geometry.faces;
  20766. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20767. var face = faces[ i ];
  20768. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20769. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  20770. }
  20771. }
  20772. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  20773. this.matrixAutoUpdate = false;
  20774. this.normalMatrix = new THREE.Matrix3();
  20775. this.update();
  20776. };
  20777. THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20778. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  20779. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20780. var v1 = new THREE.Vector3();
  20781. return function( object ) {
  20782. var keys = [ 'a', 'b', 'c', 'd' ];
  20783. this.object.updateMatrixWorld( true );
  20784. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20785. var vertices = this.geometry.vertices;
  20786. var verts = this.object.geometry.vertices;
  20787. var faces = this.object.geometry.faces;
  20788. var worldMatrix = this.object.matrixWorld;
  20789. var idx = 0;
  20790. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20791. var face = faces[ i ];
  20792. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20793. var vertexId = face[ keys[ j ] ];
  20794. var vertex = verts[ vertexId ];
  20795. var normal = face.vertexNormals[ j ];
  20796. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20797. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20798. v1.add( vertices[ idx ] );
  20799. idx = idx + 1;
  20800. vertices[ idx ].copy( v1 );
  20801. idx = idx + 1;
  20802. }
  20803. }
  20804. this.geometry.verticesNeedUpdate = true;
  20805. return this;
  20806. }
  20807. }());
  20808. // File:src/extras/helpers/VertexTangentsHelper.js
  20809. /**
  20810. * @author mrdoob / http://mrdoob.com/
  20811. * @author WestLangley / http://github.com/WestLangley
  20812. */
  20813. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20814. this.object = object;
  20815. this.size = ( size !== undefined ) ? size : 1;
  20816. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  20817. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20818. var geometry = new THREE.Geometry();
  20819. var faces = object.geometry.faces;
  20820. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20821. var face = faces[ i ];
  20822. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20823. geometry.vertices.push( new THREE.Vector3() );
  20824. geometry.vertices.push( new THREE.Vector3() );
  20825. }
  20826. }
  20827. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  20828. this.matrixAutoUpdate = false;
  20829. this.update();
  20830. };
  20831. THREE.VertexTangentsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20832. THREE.VertexTangentsHelper.prototype.constructor = THREE.VertexTangentsHelper;
  20833. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20834. var v1 = new THREE.Vector3();
  20835. return function( object ) {
  20836. var keys = [ 'a', 'b', 'c', 'd' ];
  20837. this.object.updateMatrixWorld( true );
  20838. var vertices = this.geometry.vertices;
  20839. var verts = this.object.geometry.vertices;
  20840. var faces = this.object.geometry.faces;
  20841. var worldMatrix = this.object.matrixWorld;
  20842. var idx = 0;
  20843. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20844. var face = faces[ i ];
  20845. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20846. var vertexId = face[ keys[ j ] ];
  20847. var vertex = verts[ vertexId ];
  20848. var tangent = face.vertexTangents[ j ];
  20849. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20850. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20851. v1.add( vertices[ idx ] );
  20852. idx = idx + 1;
  20853. vertices[ idx ].copy( v1 );
  20854. idx = idx + 1;
  20855. }
  20856. }
  20857. this.geometry.verticesNeedUpdate = true;
  20858. return this;
  20859. }
  20860. }());
  20861. // File:src/extras/helpers/WireframeHelper.js
  20862. /**
  20863. * @author mrdoob / http://mrdoob.com/
  20864. */
  20865. THREE.WireframeHelper = function ( object, hex ) {
  20866. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20867. THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) );
  20868. this.matrix = object.matrixWorld;
  20869. this.matrixAutoUpdate = false;
  20870. };
  20871. THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype );
  20872. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  20873. // File:src/extras/objects/ImmediateRenderObject.js
  20874. /**
  20875. * @author alteredq / http://alteredqualia.com/
  20876. */
  20877. THREE.ImmediateRenderObject = function () {
  20878. THREE.Object3D.call( this );
  20879. this.render = function ( renderCallback ) {};
  20880. };
  20881. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20882. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  20883. // File:src/extras/objects/MorphBlendMesh.js
  20884. /**
  20885. * @author alteredq / http://alteredqualia.com/
  20886. */
  20887. THREE.MorphBlendMesh = function( geometry, material ) {
  20888. THREE.Mesh.call( this, geometry, material );
  20889. this.animationsMap = {};
  20890. this.animationsList = [];
  20891. // prepare default animation
  20892. // (all frames played together in 1 second)
  20893. var numFrames = this.geometry.morphTargets.length;
  20894. var name = "__default";
  20895. var startFrame = 0;
  20896. var endFrame = numFrames - 1;
  20897. var fps = numFrames / 1;
  20898. this.createAnimation( name, startFrame, endFrame, fps );
  20899. this.setAnimationWeight( name, 1 );
  20900. };
  20901. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20902. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  20903. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20904. var animation = {
  20905. startFrame: start,
  20906. endFrame: end,
  20907. length: end - start + 1,
  20908. fps: fps,
  20909. duration: ( end - start ) / fps,
  20910. lastFrame: 0,
  20911. currentFrame: 0,
  20912. active: false,
  20913. time: 0,
  20914. direction: 1,
  20915. weight: 1,
  20916. directionBackwards: false,
  20917. mirroredLoop: false
  20918. };
  20919. this.animationsMap[ name ] = animation;
  20920. this.animationsList.push( animation );
  20921. };
  20922. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20923. var pattern = /([a-z]+)_?(\d+)/;
  20924. var firstAnimation, frameRanges = {};
  20925. var geometry = this.geometry;
  20926. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20927. var morph = geometry.morphTargets[ i ];
  20928. var chunks = morph.name.match( pattern );
  20929. if ( chunks && chunks.length > 1 ) {
  20930. var name = chunks[ 1 ];
  20931. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  20932. var range = frameRanges[ name ];
  20933. if ( i < range.start ) range.start = i;
  20934. if ( i > range.end ) range.end = i;
  20935. if ( ! firstAnimation ) firstAnimation = name;
  20936. }
  20937. }
  20938. for ( var name in frameRanges ) {
  20939. var range = frameRanges[ name ];
  20940. this.createAnimation( name, range.start, range.end, fps );
  20941. }
  20942. this.firstAnimation = firstAnimation;
  20943. };
  20944. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20945. var animation = this.animationsMap[ name ];
  20946. if ( animation ) {
  20947. animation.direction = 1;
  20948. animation.directionBackwards = false;
  20949. }
  20950. };
  20951. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20952. var animation = this.animationsMap[ name ];
  20953. if ( animation ) {
  20954. animation.direction = - 1;
  20955. animation.directionBackwards = true;
  20956. }
  20957. };
  20958. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20959. var animation = this.animationsMap[ name ];
  20960. if ( animation ) {
  20961. animation.fps = fps;
  20962. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20963. }
  20964. };
  20965. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20966. var animation = this.animationsMap[ name ];
  20967. if ( animation ) {
  20968. animation.duration = duration;
  20969. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20970. }
  20971. };
  20972. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20973. var animation = this.animationsMap[ name ];
  20974. if ( animation ) {
  20975. animation.weight = weight;
  20976. }
  20977. };
  20978. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20979. var animation = this.animationsMap[ name ];
  20980. if ( animation ) {
  20981. animation.time = time;
  20982. }
  20983. };
  20984. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20985. var time = 0;
  20986. var animation = this.animationsMap[ name ];
  20987. if ( animation ) {
  20988. time = animation.time;
  20989. }
  20990. return time;
  20991. };
  20992. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20993. var duration = - 1;
  20994. var animation = this.animationsMap[ name ];
  20995. if ( animation ) {
  20996. duration = animation.duration;
  20997. }
  20998. return duration;
  20999. };
  21000. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21001. var animation = this.animationsMap[ name ];
  21002. if ( animation ) {
  21003. animation.time = 0;
  21004. animation.active = true;
  21005. } else {
  21006. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  21007. }
  21008. };
  21009. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21010. var animation = this.animationsMap[ name ];
  21011. if ( animation ) {
  21012. animation.active = false;
  21013. }
  21014. };
  21015. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21016. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21017. var animation = this.animationsList[ i ];
  21018. if ( ! animation.active ) continue;
  21019. var frameTime = animation.duration / animation.length;
  21020. animation.time += animation.direction * delta;
  21021. if ( animation.mirroredLoop ) {
  21022. if ( animation.time > animation.duration || animation.time < 0 ) {
  21023. animation.direction *= - 1;
  21024. if ( animation.time > animation.duration ) {
  21025. animation.time = animation.duration;
  21026. animation.directionBackwards = true;
  21027. }
  21028. if ( animation.time < 0 ) {
  21029. animation.time = 0;
  21030. animation.directionBackwards = false;
  21031. }
  21032. }
  21033. } else {
  21034. animation.time = animation.time % animation.duration;
  21035. if ( animation.time < 0 ) animation.time += animation.duration;
  21036. }
  21037. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21038. var weight = animation.weight;
  21039. if ( keyframe !== animation.currentFrame ) {
  21040. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21041. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21042. this.morphTargetInfluences[ keyframe ] = 0;
  21043. animation.lastFrame = animation.currentFrame;
  21044. animation.currentFrame = keyframe;
  21045. }
  21046. var mix = ( animation.time % frameTime ) / frameTime;
  21047. if ( animation.directionBackwards ) mix = 1 - mix;
  21048. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21049. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21050. }
  21051. };
粤ICP备19079148号