three.js 941 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507
  1. // File:src/Three.js
  2. /**
  3. * @author mrdoob / http://mrdoob.com/
  4. */
  5. var THREE = { REVISION: '76' };
  6. //
  7. if ( typeof define === 'function' && define.amd ) {
  8. define( 'three', THREE );
  9. } else if ( 'undefined' !== typeof exports && 'undefined' !== typeof module ) {
  10. module.exports = THREE;
  11. }
  12. //
  13. if ( Number.EPSILON === undefined ) {
  14. Number.EPSILON = Math.pow( 2, - 52 );
  15. }
  16. //
  17. if ( Math.sign === undefined ) {
  18. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  19. Math.sign = function ( x ) {
  20. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  21. };
  22. }
  23. if ( Function.prototype.name === undefined && Object.defineProperty !== undefined ) {
  24. // Missing in IE9-11.
  25. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  26. Object.defineProperty( Function.prototype, 'name', {
  27. get: function () {
  28. return this.toString().match( /^\s*function\s*(\S*)\s*\(/ )[ 1 ];
  29. }
  30. } );
  31. }
  32. if ( Object.assign === undefined ) {
  33. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  34. Object.defineProperty( Object, 'assign', {
  35. writable: true,
  36. configurable: true,
  37. value: function ( target ) {
  38. 'use strict';
  39. if ( target === undefined || target === null ) {
  40. throw new TypeError( "Cannot convert first argument to object" );
  41. }
  42. var to = Object( target );
  43. for ( var i = 1, n = arguments.length; i !== n; ++ i ) {
  44. var nextSource = arguments[ i ];
  45. if ( nextSource === undefined || nextSource === null ) continue;
  46. nextSource = Object( nextSource );
  47. var keysArray = Object.keys( nextSource );
  48. for ( var nextIndex = 0, len = keysArray.length; nextIndex !== len; ++ nextIndex ) {
  49. var nextKey = keysArray[ nextIndex ];
  50. var desc = Object.getOwnPropertyDescriptor( nextSource, nextKey );
  51. if ( desc !== undefined && desc.enumerable ) {
  52. to[ nextKey ] = nextSource[ nextKey ];
  53. }
  54. }
  55. }
  56. return to;
  57. }
  58. } );
  59. }
  60. // https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent.button
  61. THREE.MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  62. // GL STATE CONSTANTS
  63. THREE.CullFaceNone = 0;
  64. THREE.CullFaceBack = 1;
  65. THREE.CullFaceFront = 2;
  66. THREE.CullFaceFrontBack = 3;
  67. THREE.FrontFaceDirectionCW = 0;
  68. THREE.FrontFaceDirectionCCW = 1;
  69. // SHADOWING TYPES
  70. THREE.BasicShadowMap = 0;
  71. THREE.PCFShadowMap = 1;
  72. THREE.PCFSoftShadowMap = 2;
  73. // MATERIAL CONSTANTS
  74. // side
  75. THREE.FrontSide = 0;
  76. THREE.BackSide = 1;
  77. THREE.DoubleSide = 2;
  78. // shading
  79. THREE.FlatShading = 1;
  80. THREE.SmoothShading = 2;
  81. // colors
  82. THREE.NoColors = 0;
  83. THREE.FaceColors = 1;
  84. THREE.VertexColors = 2;
  85. // blending modes
  86. THREE.NoBlending = 0;
  87. THREE.NormalBlending = 1;
  88. THREE.AdditiveBlending = 2;
  89. THREE.SubtractiveBlending = 3;
  90. THREE.MultiplyBlending = 4;
  91. THREE.CustomBlending = 5;
  92. // custom blending equations
  93. // (numbers start from 100 not to clash with other
  94. // mappings to OpenGL constants defined in Texture.js)
  95. THREE.AddEquation = 100;
  96. THREE.SubtractEquation = 101;
  97. THREE.ReverseSubtractEquation = 102;
  98. THREE.MinEquation = 103;
  99. THREE.MaxEquation = 104;
  100. // custom blending destination factors
  101. THREE.ZeroFactor = 200;
  102. THREE.OneFactor = 201;
  103. THREE.SrcColorFactor = 202;
  104. THREE.OneMinusSrcColorFactor = 203;
  105. THREE.SrcAlphaFactor = 204;
  106. THREE.OneMinusSrcAlphaFactor = 205;
  107. THREE.DstAlphaFactor = 206;
  108. THREE.OneMinusDstAlphaFactor = 207;
  109. // custom blending source factors
  110. //THREE.ZeroFactor = 200;
  111. //THREE.OneFactor = 201;
  112. //THREE.SrcAlphaFactor = 204;
  113. //THREE.OneMinusSrcAlphaFactor = 205;
  114. //THREE.DstAlphaFactor = 206;
  115. //THREE.OneMinusDstAlphaFactor = 207;
  116. THREE.DstColorFactor = 208;
  117. THREE.OneMinusDstColorFactor = 209;
  118. THREE.SrcAlphaSaturateFactor = 210;
  119. // depth modes
  120. THREE.NeverDepth = 0;
  121. THREE.AlwaysDepth = 1;
  122. THREE.LessDepth = 2;
  123. THREE.LessEqualDepth = 3;
  124. THREE.EqualDepth = 4;
  125. THREE.GreaterEqualDepth = 5;
  126. THREE.GreaterDepth = 6;
  127. THREE.NotEqualDepth = 7;
  128. // TEXTURE CONSTANTS
  129. THREE.MultiplyOperation = 0;
  130. THREE.MixOperation = 1;
  131. THREE.AddOperation = 2;
  132. // Tone Mapping modes
  133. THREE.NoToneMapping = 0; // do not do any tone mapping, not even exposure (required for special purpose passes.)
  134. THREE.LinearToneMapping = 1; // only apply exposure.
  135. THREE.ReinhardToneMapping = 2;
  136. THREE.Uncharted2ToneMapping = 3; // John Hable
  137. THREE.CineonToneMapping = 4; // optimized filmic operator by Jim Hejl and Richard Burgess-Dawson
  138. // Mapping modes
  139. THREE.UVMapping = 300;
  140. THREE.CubeReflectionMapping = 301;
  141. THREE.CubeRefractionMapping = 302;
  142. THREE.EquirectangularReflectionMapping = 303;
  143. THREE.EquirectangularRefractionMapping = 304;
  144. THREE.SphericalReflectionMapping = 305;
  145. THREE.CubeUVReflectionMapping = 306;
  146. THREE.CubeUVRefractionMapping = 307;
  147. // Wrapping modes
  148. THREE.RepeatWrapping = 1000;
  149. THREE.ClampToEdgeWrapping = 1001;
  150. THREE.MirroredRepeatWrapping = 1002;
  151. // Filters
  152. THREE.NearestFilter = 1003;
  153. THREE.NearestMipMapNearestFilter = 1004;
  154. THREE.NearestMipMapLinearFilter = 1005;
  155. THREE.LinearFilter = 1006;
  156. THREE.LinearMipMapNearestFilter = 1007;
  157. THREE.LinearMipMapLinearFilter = 1008;
  158. // Data types
  159. THREE.UnsignedByteType = 1009;
  160. THREE.ByteType = 1010;
  161. THREE.ShortType = 1011;
  162. THREE.UnsignedShortType = 1012;
  163. THREE.IntType = 1013;
  164. THREE.UnsignedIntType = 1014;
  165. THREE.FloatType = 1015;
  166. THREE.HalfFloatType = 1025;
  167. // Pixel types
  168. //THREE.UnsignedByteType = 1009;
  169. THREE.UnsignedShort4444Type = 1016;
  170. THREE.UnsignedShort5551Type = 1017;
  171. THREE.UnsignedShort565Type = 1018;
  172. // Pixel formats
  173. THREE.AlphaFormat = 1019;
  174. THREE.RGBFormat = 1020;
  175. THREE.RGBAFormat = 1021;
  176. THREE.LuminanceFormat = 1022;
  177. THREE.LuminanceAlphaFormat = 1023;
  178. // THREE.RGBEFormat handled as THREE.RGBAFormat in shaders
  179. THREE.RGBEFormat = THREE.RGBAFormat; //1024;
  180. THREE.DepthFormat = 1026;
  181. // DDS / ST3C Compressed texture formats
  182. THREE.RGB_S3TC_DXT1_Format = 2001;
  183. THREE.RGBA_S3TC_DXT1_Format = 2002;
  184. THREE.RGBA_S3TC_DXT3_Format = 2003;
  185. THREE.RGBA_S3TC_DXT5_Format = 2004;
  186. // PVRTC compressed texture formats
  187. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  188. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  189. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  190. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  191. // ETC compressed texture formats
  192. THREE.RGB_ETC1_Format = 2151;
  193. // Loop styles for AnimationAction
  194. THREE.LoopOnce = 2200;
  195. THREE.LoopRepeat = 2201;
  196. THREE.LoopPingPong = 2202;
  197. // Interpolation
  198. THREE.InterpolateDiscrete = 2300;
  199. THREE.InterpolateLinear = 2301;
  200. THREE.InterpolateSmooth = 2302;
  201. // Interpolant ending modes
  202. THREE.ZeroCurvatureEnding = 2400;
  203. THREE.ZeroSlopeEnding = 2401;
  204. THREE.WrapAroundEnding = 2402;
  205. // Triangle Draw modes
  206. THREE.TrianglesDrawMode = 0;
  207. THREE.TriangleStripDrawMode = 1;
  208. THREE.TriangleFanDrawMode = 2;
  209. // Texture Encodings
  210. THREE.LinearEncoding = 3000; // No encoding at all.
  211. THREE.sRGBEncoding = 3001;
  212. THREE.GammaEncoding = 3007; // uses GAMMA_FACTOR, for backwards compatibility with WebGLRenderer.gammaInput/gammaOutput
  213. // The following Texture Encodings are for RGB-only (no alpha) HDR light emission sources.
  214. // These encodings should not specified as output encodings except in rare situations.
  215. THREE.RGBEEncoding = 3002; // AKA Radiance.
  216. THREE.LogLuvEncoding = 3003;
  217. THREE.RGBM7Encoding = 3004;
  218. THREE.RGBM16Encoding = 3005;
  219. THREE.RGBDEncoding = 3006; // MaxRange is 256.
  220. // Depth packing strategies
  221. THREE.BasicDepthPacking = 3200; // for writing to float textures for high precision or for visualizing results in RGB buffers
  222. THREE.RGBADepthPacking = 3201; // for packing into RGBA buffers.
  223. // File:src/math/Color.js
  224. /**
  225. * @author mrdoob / http://mrdoob.com/
  226. */
  227. THREE.Color = function ( color ) {
  228. if ( arguments.length === 3 ) {
  229. return this.fromArray( arguments );
  230. }
  231. return this.set( color );
  232. };
  233. THREE.Color.prototype = {
  234. constructor: THREE.Color,
  235. r: 1, g: 1, b: 1,
  236. set: function ( value ) {
  237. if ( value instanceof THREE.Color ) {
  238. this.copy( value );
  239. } else if ( typeof value === 'number' ) {
  240. this.setHex( value );
  241. } else if ( typeof value === 'string' ) {
  242. this.setStyle( value );
  243. }
  244. return this;
  245. },
  246. setScalar: function ( scalar ) {
  247. this.r = scalar;
  248. this.g = scalar;
  249. this.b = scalar;
  250. },
  251. setHex: function ( hex ) {
  252. hex = Math.floor( hex );
  253. this.r = ( hex >> 16 & 255 ) / 255;
  254. this.g = ( hex >> 8 & 255 ) / 255;
  255. this.b = ( hex & 255 ) / 255;
  256. return this;
  257. },
  258. setRGB: function ( r, g, b ) {
  259. this.r = r;
  260. this.g = g;
  261. this.b = b;
  262. return this;
  263. },
  264. setHSL: function () {
  265. function hue2rgb( p, q, t ) {
  266. if ( t < 0 ) t += 1;
  267. if ( t > 1 ) t -= 1;
  268. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  269. if ( t < 1 / 2 ) return q;
  270. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  271. return p;
  272. }
  273. return function ( h, s, l ) {
  274. // h,s,l ranges are in 0.0 - 1.0
  275. h = THREE.Math.euclideanModulo( h, 1 );
  276. s = THREE.Math.clamp( s, 0, 1 );
  277. l = THREE.Math.clamp( l, 0, 1 );
  278. if ( s === 0 ) {
  279. this.r = this.g = this.b = l;
  280. } else {
  281. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  282. var q = ( 2 * l ) - p;
  283. this.r = hue2rgb( q, p, h + 1 / 3 );
  284. this.g = hue2rgb( q, p, h );
  285. this.b = hue2rgb( q, p, h - 1 / 3 );
  286. }
  287. return this;
  288. };
  289. }(),
  290. setStyle: function ( style ) {
  291. function handleAlpha( string ) {
  292. if ( string === undefined ) return;
  293. if ( parseFloat( string ) < 1 ) {
  294. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  295. }
  296. }
  297. var m;
  298. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  299. // rgb / hsl
  300. var color;
  301. var name = m[ 1 ];
  302. var components = m[ 2 ];
  303. switch ( name ) {
  304. case 'rgb':
  305. case 'rgba':
  306. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  307. // rgb(255,0,0) rgba(255,0,0,0.5)
  308. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  309. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  310. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  311. handleAlpha( color[ 5 ] );
  312. return this;
  313. }
  314. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  315. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  316. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  317. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  318. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  319. handleAlpha( color[ 5 ] );
  320. return this;
  321. }
  322. break;
  323. case 'hsl':
  324. case 'hsla':
  325. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  326. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  327. var h = parseFloat( color[ 1 ] ) / 360;
  328. var s = parseInt( color[ 2 ], 10 ) / 100;
  329. var l = parseInt( color[ 3 ], 10 ) / 100;
  330. handleAlpha( color[ 5 ] );
  331. return this.setHSL( h, s, l );
  332. }
  333. break;
  334. }
  335. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  336. // hex color
  337. var hex = m[ 1 ];
  338. var size = hex.length;
  339. if ( size === 3 ) {
  340. // #ff0
  341. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  342. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  343. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  344. return this;
  345. } else if ( size === 6 ) {
  346. // #ff0000
  347. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  348. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  349. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  350. return this;
  351. }
  352. }
  353. if ( style && style.length > 0 ) {
  354. // color keywords
  355. var hex = THREE.ColorKeywords[ style ];
  356. if ( hex !== undefined ) {
  357. // red
  358. this.setHex( hex );
  359. } else {
  360. // unknown color
  361. console.warn( 'THREE.Color: Unknown color ' + style );
  362. }
  363. }
  364. return this;
  365. },
  366. clone: function () {
  367. return new this.constructor( this.r, this.g, this.b );
  368. },
  369. copy: function ( color ) {
  370. this.r = color.r;
  371. this.g = color.g;
  372. this.b = color.b;
  373. return this;
  374. },
  375. copyGammaToLinear: function ( color, gammaFactor ) {
  376. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  377. this.r = Math.pow( color.r, gammaFactor );
  378. this.g = Math.pow( color.g, gammaFactor );
  379. this.b = Math.pow( color.b, gammaFactor );
  380. return this;
  381. },
  382. copyLinearToGamma: function ( color, gammaFactor ) {
  383. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  384. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  385. this.r = Math.pow( color.r, safeInverse );
  386. this.g = Math.pow( color.g, safeInverse );
  387. this.b = Math.pow( color.b, safeInverse );
  388. return this;
  389. },
  390. convertGammaToLinear: function () {
  391. var r = this.r, g = this.g, b = this.b;
  392. this.r = r * r;
  393. this.g = g * g;
  394. this.b = b * b;
  395. return this;
  396. },
  397. convertLinearToGamma: function () {
  398. this.r = Math.sqrt( this.r );
  399. this.g = Math.sqrt( this.g );
  400. this.b = Math.sqrt( this.b );
  401. return this;
  402. },
  403. getHex: function () {
  404. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  405. },
  406. getHexString: function () {
  407. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  408. },
  409. getHSL: function ( optionalTarget ) {
  410. // h,s,l ranges are in 0.0 - 1.0
  411. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  412. var r = this.r, g = this.g, b = this.b;
  413. var max = Math.max( r, g, b );
  414. var min = Math.min( r, g, b );
  415. var hue, saturation;
  416. var lightness = ( min + max ) / 2.0;
  417. if ( min === max ) {
  418. hue = 0;
  419. saturation = 0;
  420. } else {
  421. var delta = max - min;
  422. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  423. switch ( max ) {
  424. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  425. case g: hue = ( b - r ) / delta + 2; break;
  426. case b: hue = ( r - g ) / delta + 4; break;
  427. }
  428. hue /= 6;
  429. }
  430. hsl.h = hue;
  431. hsl.s = saturation;
  432. hsl.l = lightness;
  433. return hsl;
  434. },
  435. getStyle: function () {
  436. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  437. },
  438. offsetHSL: function ( h, s, l ) {
  439. var hsl = this.getHSL();
  440. hsl.h += h; hsl.s += s; hsl.l += l;
  441. this.setHSL( hsl.h, hsl.s, hsl.l );
  442. return this;
  443. },
  444. add: function ( color ) {
  445. this.r += color.r;
  446. this.g += color.g;
  447. this.b += color.b;
  448. return this;
  449. },
  450. addColors: function ( color1, color2 ) {
  451. this.r = color1.r + color2.r;
  452. this.g = color1.g + color2.g;
  453. this.b = color1.b + color2.b;
  454. return this;
  455. },
  456. addScalar: function ( s ) {
  457. this.r += s;
  458. this.g += s;
  459. this.b += s;
  460. return this;
  461. },
  462. multiply: function ( color ) {
  463. this.r *= color.r;
  464. this.g *= color.g;
  465. this.b *= color.b;
  466. return this;
  467. },
  468. multiplyScalar: function ( s ) {
  469. this.r *= s;
  470. this.g *= s;
  471. this.b *= s;
  472. return this;
  473. },
  474. lerp: function ( color, alpha ) {
  475. this.r += ( color.r - this.r ) * alpha;
  476. this.g += ( color.g - this.g ) * alpha;
  477. this.b += ( color.b - this.b ) * alpha;
  478. return this;
  479. },
  480. equals: function ( c ) {
  481. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  482. },
  483. fromArray: function ( array, offset ) {
  484. if ( offset === undefined ) offset = 0;
  485. this.r = array[ offset ];
  486. this.g = array[ offset + 1 ];
  487. this.b = array[ offset + 2 ];
  488. return this;
  489. },
  490. toArray: function ( array, offset ) {
  491. if ( array === undefined ) array = [];
  492. if ( offset === undefined ) offset = 0;
  493. array[ offset ] = this.r;
  494. array[ offset + 1 ] = this.g;
  495. array[ offset + 2 ] = this.b;
  496. return array;
  497. }
  498. };
  499. THREE.ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  500. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  501. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  502. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  503. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  504. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  505. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  506. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  507. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  508. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  509. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  510. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  511. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  512. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  513. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  514. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  515. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  516. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  517. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  518. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  519. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  520. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  521. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  522. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  523. // File:src/math/Quaternion.js
  524. /**
  525. * @author mikael emtinger / http://gomo.se/
  526. * @author alteredq / http://alteredqualia.com/
  527. * @author WestLangley / http://github.com/WestLangley
  528. * @author bhouston / http://clara.io
  529. */
  530. THREE.Quaternion = function ( x, y, z, w ) {
  531. this._x = x || 0;
  532. this._y = y || 0;
  533. this._z = z || 0;
  534. this._w = ( w !== undefined ) ? w : 1;
  535. };
  536. THREE.Quaternion.prototype = {
  537. constructor: THREE.Quaternion,
  538. get x () {
  539. return this._x;
  540. },
  541. set x ( value ) {
  542. this._x = value;
  543. this.onChangeCallback();
  544. },
  545. get y () {
  546. return this._y;
  547. },
  548. set y ( value ) {
  549. this._y = value;
  550. this.onChangeCallback();
  551. },
  552. get z () {
  553. return this._z;
  554. },
  555. set z ( value ) {
  556. this._z = value;
  557. this.onChangeCallback();
  558. },
  559. get w () {
  560. return this._w;
  561. },
  562. set w ( value ) {
  563. this._w = value;
  564. this.onChangeCallback();
  565. },
  566. set: function ( x, y, z, w ) {
  567. this._x = x;
  568. this._y = y;
  569. this._z = z;
  570. this._w = w;
  571. this.onChangeCallback();
  572. return this;
  573. },
  574. clone: function () {
  575. return new this.constructor( this._x, this._y, this._z, this._w );
  576. },
  577. copy: function ( quaternion ) {
  578. this._x = quaternion.x;
  579. this._y = quaternion.y;
  580. this._z = quaternion.z;
  581. this._w = quaternion.w;
  582. this.onChangeCallback();
  583. return this;
  584. },
  585. setFromEuler: function ( euler, update ) {
  586. if ( euler instanceof THREE.Euler === false ) {
  587. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  588. }
  589. // http://www.mathworks.com/matlabcentral/fileexchange/
  590. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  591. // content/SpinCalc.m
  592. var c1 = Math.cos( euler._x / 2 );
  593. var c2 = Math.cos( euler._y / 2 );
  594. var c3 = Math.cos( euler._z / 2 );
  595. var s1 = Math.sin( euler._x / 2 );
  596. var s2 = Math.sin( euler._y / 2 );
  597. var s3 = Math.sin( euler._z / 2 );
  598. var order = euler.order;
  599. if ( order === 'XYZ' ) {
  600. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  601. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  602. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  603. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  604. } else if ( order === 'YXZ' ) {
  605. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  606. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  607. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  608. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  609. } else if ( order === 'ZXY' ) {
  610. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  611. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  612. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  613. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  614. } else if ( order === 'ZYX' ) {
  615. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  616. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  617. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  618. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  619. } else if ( order === 'YZX' ) {
  620. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  621. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  622. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  623. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  624. } else if ( order === 'XZY' ) {
  625. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  626. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  627. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  628. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  629. }
  630. if ( update !== false ) this.onChangeCallback();
  631. return this;
  632. },
  633. setFromAxisAngle: function ( axis, angle ) {
  634. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  635. // assumes axis is normalized
  636. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  637. this._x = axis.x * s;
  638. this._y = axis.y * s;
  639. this._z = axis.z * s;
  640. this._w = Math.cos( halfAngle );
  641. this.onChangeCallback();
  642. return this;
  643. },
  644. setFromRotationMatrix: function ( m ) {
  645. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  646. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  647. var te = m.elements,
  648. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  649. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  650. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  651. trace = m11 + m22 + m33,
  652. s;
  653. if ( trace > 0 ) {
  654. s = 0.5 / Math.sqrt( trace + 1.0 );
  655. this._w = 0.25 / s;
  656. this._x = ( m32 - m23 ) * s;
  657. this._y = ( m13 - m31 ) * s;
  658. this._z = ( m21 - m12 ) * s;
  659. } else if ( m11 > m22 && m11 > m33 ) {
  660. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  661. this._w = ( m32 - m23 ) / s;
  662. this._x = 0.25 * s;
  663. this._y = ( m12 + m21 ) / s;
  664. this._z = ( m13 + m31 ) / s;
  665. } else if ( m22 > m33 ) {
  666. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  667. this._w = ( m13 - m31 ) / s;
  668. this._x = ( m12 + m21 ) / s;
  669. this._y = 0.25 * s;
  670. this._z = ( m23 + m32 ) / s;
  671. } else {
  672. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  673. this._w = ( m21 - m12 ) / s;
  674. this._x = ( m13 + m31 ) / s;
  675. this._y = ( m23 + m32 ) / s;
  676. this._z = 0.25 * s;
  677. }
  678. this.onChangeCallback();
  679. return this;
  680. },
  681. setFromUnitVectors: function () {
  682. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  683. // assumes direction vectors vFrom and vTo are normalized
  684. var v1, r;
  685. var EPS = 0.000001;
  686. return function ( vFrom, vTo ) {
  687. if ( v1 === undefined ) v1 = new THREE.Vector3();
  688. r = vFrom.dot( vTo ) + 1;
  689. if ( r < EPS ) {
  690. r = 0;
  691. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  692. v1.set( - vFrom.y, vFrom.x, 0 );
  693. } else {
  694. v1.set( 0, - vFrom.z, vFrom.y );
  695. }
  696. } else {
  697. v1.crossVectors( vFrom, vTo );
  698. }
  699. this._x = v1.x;
  700. this._y = v1.y;
  701. this._z = v1.z;
  702. this._w = r;
  703. this.normalize();
  704. return this;
  705. };
  706. }(),
  707. inverse: function () {
  708. this.conjugate().normalize();
  709. return this;
  710. },
  711. conjugate: function () {
  712. this._x *= - 1;
  713. this._y *= - 1;
  714. this._z *= - 1;
  715. this.onChangeCallback();
  716. return this;
  717. },
  718. dot: function ( v ) {
  719. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  720. },
  721. lengthSq: function () {
  722. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  723. },
  724. length: function () {
  725. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  726. },
  727. normalize: function () {
  728. var l = this.length();
  729. if ( l === 0 ) {
  730. this._x = 0;
  731. this._y = 0;
  732. this._z = 0;
  733. this._w = 1;
  734. } else {
  735. l = 1 / l;
  736. this._x = this._x * l;
  737. this._y = this._y * l;
  738. this._z = this._z * l;
  739. this._w = this._w * l;
  740. }
  741. this.onChangeCallback();
  742. return this;
  743. },
  744. multiply: function ( q, p ) {
  745. if ( p !== undefined ) {
  746. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  747. return this.multiplyQuaternions( q, p );
  748. }
  749. return this.multiplyQuaternions( this, q );
  750. },
  751. multiplyQuaternions: function ( a, b ) {
  752. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  753. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  754. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  755. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  756. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  757. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  758. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  759. this.onChangeCallback();
  760. return this;
  761. },
  762. slerp: function ( qb, t ) {
  763. if ( t === 0 ) return this;
  764. if ( t === 1 ) return this.copy( qb );
  765. var x = this._x, y = this._y, z = this._z, w = this._w;
  766. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  767. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  768. if ( cosHalfTheta < 0 ) {
  769. this._w = - qb._w;
  770. this._x = - qb._x;
  771. this._y = - qb._y;
  772. this._z = - qb._z;
  773. cosHalfTheta = - cosHalfTheta;
  774. } else {
  775. this.copy( qb );
  776. }
  777. if ( cosHalfTheta >= 1.0 ) {
  778. this._w = w;
  779. this._x = x;
  780. this._y = y;
  781. this._z = z;
  782. return this;
  783. }
  784. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  785. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  786. this._w = 0.5 * ( w + this._w );
  787. this._x = 0.5 * ( x + this._x );
  788. this._y = 0.5 * ( y + this._y );
  789. this._z = 0.5 * ( z + this._z );
  790. return this;
  791. }
  792. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  793. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  794. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  795. this._w = ( w * ratioA + this._w * ratioB );
  796. this._x = ( x * ratioA + this._x * ratioB );
  797. this._y = ( y * ratioA + this._y * ratioB );
  798. this._z = ( z * ratioA + this._z * ratioB );
  799. this.onChangeCallback();
  800. return this;
  801. },
  802. equals: function ( quaternion ) {
  803. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  804. },
  805. fromArray: function ( array, offset ) {
  806. if ( offset === undefined ) offset = 0;
  807. this._x = array[ offset ];
  808. this._y = array[ offset + 1 ];
  809. this._z = array[ offset + 2 ];
  810. this._w = array[ offset + 3 ];
  811. this.onChangeCallback();
  812. return this;
  813. },
  814. toArray: function ( array, offset ) {
  815. if ( array === undefined ) array = [];
  816. if ( offset === undefined ) offset = 0;
  817. array[ offset ] = this._x;
  818. array[ offset + 1 ] = this._y;
  819. array[ offset + 2 ] = this._z;
  820. array[ offset + 3 ] = this._w;
  821. return array;
  822. },
  823. onChange: function ( callback ) {
  824. this.onChangeCallback = callback;
  825. return this;
  826. },
  827. onChangeCallback: function () {}
  828. };
  829. Object.assign( THREE.Quaternion, {
  830. slerp: function( qa, qb, qm, t ) {
  831. return qm.copy( qa ).slerp( qb, t );
  832. },
  833. slerpFlat: function(
  834. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  835. // fuzz-free, array-based Quaternion SLERP operation
  836. var x0 = src0[ srcOffset0 + 0 ],
  837. y0 = src0[ srcOffset0 + 1 ],
  838. z0 = src0[ srcOffset0 + 2 ],
  839. w0 = src0[ srcOffset0 + 3 ],
  840. x1 = src1[ srcOffset1 + 0 ],
  841. y1 = src1[ srcOffset1 + 1 ],
  842. z1 = src1[ srcOffset1 + 2 ],
  843. w1 = src1[ srcOffset1 + 3 ];
  844. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  845. var s = 1 - t,
  846. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  847. dir = ( cos >= 0 ? 1 : - 1 ),
  848. sqrSin = 1 - cos * cos;
  849. // Skip the Slerp for tiny steps to avoid numeric problems:
  850. if ( sqrSin > Number.EPSILON ) {
  851. var sin = Math.sqrt( sqrSin ),
  852. len = Math.atan2( sin, cos * dir );
  853. s = Math.sin( s * len ) / sin;
  854. t = Math.sin( t * len ) / sin;
  855. }
  856. var tDir = t * dir;
  857. x0 = x0 * s + x1 * tDir;
  858. y0 = y0 * s + y1 * tDir;
  859. z0 = z0 * s + z1 * tDir;
  860. w0 = w0 * s + w1 * tDir;
  861. // Normalize in case we just did a lerp:
  862. if ( s === 1 - t ) {
  863. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  864. x0 *= f;
  865. y0 *= f;
  866. z0 *= f;
  867. w0 *= f;
  868. }
  869. }
  870. dst[ dstOffset ] = x0;
  871. dst[ dstOffset + 1 ] = y0;
  872. dst[ dstOffset + 2 ] = z0;
  873. dst[ dstOffset + 3 ] = w0;
  874. }
  875. } );
  876. // File:src/math/Vector2.js
  877. /**
  878. * @author mrdoob / http://mrdoob.com/
  879. * @author philogb / http://blog.thejit.org/
  880. * @author egraether / http://egraether.com/
  881. * @author zz85 / http://www.lab4games.net/zz85/blog
  882. */
  883. THREE.Vector2 = function ( x, y ) {
  884. this.x = x || 0;
  885. this.y = y || 0;
  886. };
  887. THREE.Vector2.prototype = {
  888. constructor: THREE.Vector2,
  889. get width() {
  890. return this.x;
  891. },
  892. set width( value ) {
  893. this.x = value;
  894. },
  895. get height() {
  896. return this.y;
  897. },
  898. set height( value ) {
  899. this.y = value;
  900. },
  901. //
  902. set: function ( x, y ) {
  903. this.x = x;
  904. this.y = y;
  905. return this;
  906. },
  907. setScalar: function ( scalar ) {
  908. this.x = scalar;
  909. this.y = scalar;
  910. return this;
  911. },
  912. setX: function ( x ) {
  913. this.x = x;
  914. return this;
  915. },
  916. setY: function ( y ) {
  917. this.y = y;
  918. return this;
  919. },
  920. setComponent: function ( index, value ) {
  921. switch ( index ) {
  922. case 0: this.x = value; break;
  923. case 1: this.y = value; break;
  924. default: throw new Error( 'index is out of range: ' + index );
  925. }
  926. },
  927. getComponent: function ( index ) {
  928. switch ( index ) {
  929. case 0: return this.x;
  930. case 1: return this.y;
  931. default: throw new Error( 'index is out of range: ' + index );
  932. }
  933. },
  934. clone: function () {
  935. return new this.constructor( this.x, this.y );
  936. },
  937. copy: function ( v ) {
  938. this.x = v.x;
  939. this.y = v.y;
  940. return this;
  941. },
  942. add: function ( v, w ) {
  943. if ( w !== undefined ) {
  944. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  945. return this.addVectors( v, w );
  946. }
  947. this.x += v.x;
  948. this.y += v.y;
  949. return this;
  950. },
  951. addScalar: function ( s ) {
  952. this.x += s;
  953. this.y += s;
  954. return this;
  955. },
  956. addVectors: function ( a, b ) {
  957. this.x = a.x + b.x;
  958. this.y = a.y + b.y;
  959. return this;
  960. },
  961. addScaledVector: function ( v, s ) {
  962. this.x += v.x * s;
  963. this.y += v.y * s;
  964. return this;
  965. },
  966. sub: function ( v, w ) {
  967. if ( w !== undefined ) {
  968. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  969. return this.subVectors( v, w );
  970. }
  971. this.x -= v.x;
  972. this.y -= v.y;
  973. return this;
  974. },
  975. subScalar: function ( s ) {
  976. this.x -= s;
  977. this.y -= s;
  978. return this;
  979. },
  980. subVectors: function ( a, b ) {
  981. this.x = a.x - b.x;
  982. this.y = a.y - b.y;
  983. return this;
  984. },
  985. multiply: function ( v ) {
  986. this.x *= v.x;
  987. this.y *= v.y;
  988. return this;
  989. },
  990. multiplyScalar: function ( scalar ) {
  991. if ( isFinite( scalar ) ) {
  992. this.x *= scalar;
  993. this.y *= scalar;
  994. } else {
  995. this.x = 0;
  996. this.y = 0;
  997. }
  998. return this;
  999. },
  1000. divide: function ( v ) {
  1001. this.x /= v.x;
  1002. this.y /= v.y;
  1003. return this;
  1004. },
  1005. divideScalar: function ( scalar ) {
  1006. return this.multiplyScalar( 1 / scalar );
  1007. },
  1008. min: function ( v ) {
  1009. this.x = Math.min( this.x, v.x );
  1010. this.y = Math.min( this.y, v.y );
  1011. return this;
  1012. },
  1013. max: function ( v ) {
  1014. this.x = Math.max( this.x, v.x );
  1015. this.y = Math.max( this.y, v.y );
  1016. return this;
  1017. },
  1018. clamp: function ( min, max ) {
  1019. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1020. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1021. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1022. return this;
  1023. },
  1024. clampScalar: function () {
  1025. var min, max;
  1026. return function clampScalar( minVal, maxVal ) {
  1027. if ( min === undefined ) {
  1028. min = new THREE.Vector2();
  1029. max = new THREE.Vector2();
  1030. }
  1031. min.set( minVal, minVal );
  1032. max.set( maxVal, maxVal );
  1033. return this.clamp( min, max );
  1034. };
  1035. }(),
  1036. clampLength: function ( min, max ) {
  1037. var length = this.length();
  1038. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1039. return this;
  1040. },
  1041. floor: function () {
  1042. this.x = Math.floor( this.x );
  1043. this.y = Math.floor( this.y );
  1044. return this;
  1045. },
  1046. ceil: function () {
  1047. this.x = Math.ceil( this.x );
  1048. this.y = Math.ceil( this.y );
  1049. return this;
  1050. },
  1051. round: function () {
  1052. this.x = Math.round( this.x );
  1053. this.y = Math.round( this.y );
  1054. return this;
  1055. },
  1056. roundToZero: function () {
  1057. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1058. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1059. return this;
  1060. },
  1061. negate: function () {
  1062. this.x = - this.x;
  1063. this.y = - this.y;
  1064. return this;
  1065. },
  1066. dot: function ( v ) {
  1067. return this.x * v.x + this.y * v.y;
  1068. },
  1069. lengthSq: function () {
  1070. return this.x * this.x + this.y * this.y;
  1071. },
  1072. length: function () {
  1073. return Math.sqrt( this.x * this.x + this.y * this.y );
  1074. },
  1075. lengthManhattan: function() {
  1076. return Math.abs( this.x ) + Math.abs( this.y );
  1077. },
  1078. normalize: function () {
  1079. return this.divideScalar( this.length() );
  1080. },
  1081. angle: function () {
  1082. // computes the angle in radians with respect to the positive x-axis
  1083. var angle = Math.atan2( this.y, this.x );
  1084. if ( angle < 0 ) angle += 2 * Math.PI;
  1085. return angle;
  1086. },
  1087. distanceTo: function ( v ) {
  1088. return Math.sqrt( this.distanceToSquared( v ) );
  1089. },
  1090. distanceToSquared: function ( v ) {
  1091. var dx = this.x - v.x, dy = this.y - v.y;
  1092. return dx * dx + dy * dy;
  1093. },
  1094. setLength: function ( length ) {
  1095. return this.multiplyScalar( length / this.length() );
  1096. },
  1097. lerp: function ( v, alpha ) {
  1098. this.x += ( v.x - this.x ) * alpha;
  1099. this.y += ( v.y - this.y ) * alpha;
  1100. return this;
  1101. },
  1102. lerpVectors: function ( v1, v2, alpha ) {
  1103. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1104. return this;
  1105. },
  1106. equals: function ( v ) {
  1107. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  1108. },
  1109. fromArray: function ( array, offset ) {
  1110. if ( offset === undefined ) offset = 0;
  1111. this.x = array[ offset ];
  1112. this.y = array[ offset + 1 ];
  1113. return this;
  1114. },
  1115. toArray: function ( array, offset ) {
  1116. if ( array === undefined ) array = [];
  1117. if ( offset === undefined ) offset = 0;
  1118. array[ offset ] = this.x;
  1119. array[ offset + 1 ] = this.y;
  1120. return array;
  1121. },
  1122. fromAttribute: function ( attribute, index, offset ) {
  1123. if ( offset === undefined ) offset = 0;
  1124. index = index * attribute.itemSize + offset;
  1125. this.x = attribute.array[ index ];
  1126. this.y = attribute.array[ index + 1 ];
  1127. return this;
  1128. },
  1129. rotateAround: function ( center, angle ) {
  1130. var c = Math.cos( angle ), s = Math.sin( angle );
  1131. var x = this.x - center.x;
  1132. var y = this.y - center.y;
  1133. this.x = x * c - y * s + center.x;
  1134. this.y = x * s + y * c + center.y;
  1135. return this;
  1136. }
  1137. };
  1138. // File:src/math/Vector3.js
  1139. /**
  1140. * @author mrdoob / http://mrdoob.com/
  1141. * @author *kile / http://kile.stravaganza.org/
  1142. * @author philogb / http://blog.thejit.org/
  1143. * @author mikael emtinger / http://gomo.se/
  1144. * @author egraether / http://egraether.com/
  1145. * @author WestLangley / http://github.com/WestLangley
  1146. */
  1147. THREE.Vector3 = function ( x, y, z ) {
  1148. this.x = x || 0;
  1149. this.y = y || 0;
  1150. this.z = z || 0;
  1151. };
  1152. THREE.Vector3.prototype = {
  1153. constructor: THREE.Vector3,
  1154. set: function ( x, y, z ) {
  1155. this.x = x;
  1156. this.y = y;
  1157. this.z = z;
  1158. return this;
  1159. },
  1160. setScalar: function ( scalar ) {
  1161. this.x = scalar;
  1162. this.y = scalar;
  1163. this.z = scalar;
  1164. return this;
  1165. },
  1166. setX: function ( x ) {
  1167. this.x = x;
  1168. return this;
  1169. },
  1170. setY: function ( y ) {
  1171. this.y = y;
  1172. return this;
  1173. },
  1174. setZ: function ( z ) {
  1175. this.z = z;
  1176. return this;
  1177. },
  1178. setComponent: function ( index, value ) {
  1179. switch ( index ) {
  1180. case 0: this.x = value; break;
  1181. case 1: this.y = value; break;
  1182. case 2: this.z = value; break;
  1183. default: throw new Error( 'index is out of range: ' + index );
  1184. }
  1185. },
  1186. getComponent: function ( index ) {
  1187. switch ( index ) {
  1188. case 0: return this.x;
  1189. case 1: return this.y;
  1190. case 2: return this.z;
  1191. default: throw new Error( 'index is out of range: ' + index );
  1192. }
  1193. },
  1194. clone: function () {
  1195. return new this.constructor( this.x, this.y, this.z );
  1196. },
  1197. copy: function ( v ) {
  1198. this.x = v.x;
  1199. this.y = v.y;
  1200. this.z = v.z;
  1201. return this;
  1202. },
  1203. add: function ( v, w ) {
  1204. if ( w !== undefined ) {
  1205. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1206. return this.addVectors( v, w );
  1207. }
  1208. this.x += v.x;
  1209. this.y += v.y;
  1210. this.z += v.z;
  1211. return this;
  1212. },
  1213. addScalar: function ( s ) {
  1214. this.x += s;
  1215. this.y += s;
  1216. this.z += s;
  1217. return this;
  1218. },
  1219. addVectors: function ( a, b ) {
  1220. this.x = a.x + b.x;
  1221. this.y = a.y + b.y;
  1222. this.z = a.z + b.z;
  1223. return this;
  1224. },
  1225. addScaledVector: function ( v, s ) {
  1226. this.x += v.x * s;
  1227. this.y += v.y * s;
  1228. this.z += v.z * s;
  1229. return this;
  1230. },
  1231. sub: function ( v, w ) {
  1232. if ( w !== undefined ) {
  1233. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1234. return this.subVectors( v, w );
  1235. }
  1236. this.x -= v.x;
  1237. this.y -= v.y;
  1238. this.z -= v.z;
  1239. return this;
  1240. },
  1241. subScalar: function ( s ) {
  1242. this.x -= s;
  1243. this.y -= s;
  1244. this.z -= s;
  1245. return this;
  1246. },
  1247. subVectors: function ( a, b ) {
  1248. this.x = a.x - b.x;
  1249. this.y = a.y - b.y;
  1250. this.z = a.z - b.z;
  1251. return this;
  1252. },
  1253. multiply: function ( v, w ) {
  1254. if ( w !== undefined ) {
  1255. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  1256. return this.multiplyVectors( v, w );
  1257. }
  1258. this.x *= v.x;
  1259. this.y *= v.y;
  1260. this.z *= v.z;
  1261. return this;
  1262. },
  1263. multiplyScalar: function ( scalar ) {
  1264. if ( isFinite( scalar ) ) {
  1265. this.x *= scalar;
  1266. this.y *= scalar;
  1267. this.z *= scalar;
  1268. } else {
  1269. this.x = 0;
  1270. this.y = 0;
  1271. this.z = 0;
  1272. }
  1273. return this;
  1274. },
  1275. multiplyVectors: function ( a, b ) {
  1276. this.x = a.x * b.x;
  1277. this.y = a.y * b.y;
  1278. this.z = a.z * b.z;
  1279. return this;
  1280. },
  1281. applyEuler: function () {
  1282. var quaternion;
  1283. return function applyEuler( euler ) {
  1284. if ( euler instanceof THREE.Euler === false ) {
  1285. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  1286. }
  1287. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1288. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1289. return this;
  1290. };
  1291. }(),
  1292. applyAxisAngle: function () {
  1293. var quaternion;
  1294. return function applyAxisAngle( axis, angle ) {
  1295. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1296. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1297. return this;
  1298. };
  1299. }(),
  1300. applyMatrix3: function ( m ) {
  1301. var x = this.x;
  1302. var y = this.y;
  1303. var z = this.z;
  1304. var e = m.elements;
  1305. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  1306. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  1307. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  1308. return this;
  1309. },
  1310. applyMatrix4: function ( m ) {
  1311. // input: THREE.Matrix4 affine matrix
  1312. var x = this.x, y = this.y, z = this.z;
  1313. var e = m.elements;
  1314. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  1315. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  1316. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  1317. return this;
  1318. },
  1319. applyProjection: function ( m ) {
  1320. // input: THREE.Matrix4 projection matrix
  1321. var x = this.x, y = this.y, z = this.z;
  1322. var e = m.elements;
  1323. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  1324. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  1325. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  1326. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  1327. return this;
  1328. },
  1329. applyQuaternion: function ( q ) {
  1330. var x = this.x;
  1331. var y = this.y;
  1332. var z = this.z;
  1333. var qx = q.x;
  1334. var qy = q.y;
  1335. var qz = q.z;
  1336. var qw = q.w;
  1337. // calculate quat * vector
  1338. var ix = qw * x + qy * z - qz * y;
  1339. var iy = qw * y + qz * x - qx * z;
  1340. var iz = qw * z + qx * y - qy * x;
  1341. var iw = - qx * x - qy * y - qz * z;
  1342. // calculate result * inverse quat
  1343. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  1344. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  1345. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  1346. return this;
  1347. },
  1348. project: function () {
  1349. var matrix;
  1350. return function project( camera ) {
  1351. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1352. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  1353. return this.applyProjection( matrix );
  1354. };
  1355. }(),
  1356. unproject: function () {
  1357. var matrix;
  1358. return function unproject( camera ) {
  1359. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  1360. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  1361. return this.applyProjection( matrix );
  1362. };
  1363. }(),
  1364. transformDirection: function ( m ) {
  1365. // input: THREE.Matrix4 affine matrix
  1366. // vector interpreted as a direction
  1367. var x = this.x, y = this.y, z = this.z;
  1368. var e = m.elements;
  1369. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  1370. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  1371. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  1372. this.normalize();
  1373. return this;
  1374. },
  1375. divide: function ( v ) {
  1376. this.x /= v.x;
  1377. this.y /= v.y;
  1378. this.z /= v.z;
  1379. return this;
  1380. },
  1381. divideScalar: function ( scalar ) {
  1382. return this.multiplyScalar( 1 / scalar );
  1383. },
  1384. min: function ( v ) {
  1385. this.x = Math.min( this.x, v.x );
  1386. this.y = Math.min( this.y, v.y );
  1387. this.z = Math.min( this.z, v.z );
  1388. return this;
  1389. },
  1390. max: function ( v ) {
  1391. this.x = Math.max( this.x, v.x );
  1392. this.y = Math.max( this.y, v.y );
  1393. this.z = Math.max( this.z, v.z );
  1394. return this;
  1395. },
  1396. clamp: function ( min, max ) {
  1397. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1398. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1399. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1400. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1401. return this;
  1402. },
  1403. clampScalar: function () {
  1404. var min, max;
  1405. return function clampScalar( minVal, maxVal ) {
  1406. if ( min === undefined ) {
  1407. min = new THREE.Vector3();
  1408. max = new THREE.Vector3();
  1409. }
  1410. min.set( minVal, minVal, minVal );
  1411. max.set( maxVal, maxVal, maxVal );
  1412. return this.clamp( min, max );
  1413. };
  1414. }(),
  1415. clampLength: function ( min, max ) {
  1416. var length = this.length();
  1417. this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  1418. return this;
  1419. },
  1420. floor: function () {
  1421. this.x = Math.floor( this.x );
  1422. this.y = Math.floor( this.y );
  1423. this.z = Math.floor( this.z );
  1424. return this;
  1425. },
  1426. ceil: function () {
  1427. this.x = Math.ceil( this.x );
  1428. this.y = Math.ceil( this.y );
  1429. this.z = Math.ceil( this.z );
  1430. return this;
  1431. },
  1432. round: function () {
  1433. this.x = Math.round( this.x );
  1434. this.y = Math.round( this.y );
  1435. this.z = Math.round( this.z );
  1436. return this;
  1437. },
  1438. roundToZero: function () {
  1439. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1440. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1441. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1442. return this;
  1443. },
  1444. negate: function () {
  1445. this.x = - this.x;
  1446. this.y = - this.y;
  1447. this.z = - this.z;
  1448. return this;
  1449. },
  1450. dot: function ( v ) {
  1451. return this.x * v.x + this.y * v.y + this.z * v.z;
  1452. },
  1453. lengthSq: function () {
  1454. return this.x * this.x + this.y * this.y + this.z * this.z;
  1455. },
  1456. length: function () {
  1457. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1458. },
  1459. lengthManhattan: function () {
  1460. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1461. },
  1462. normalize: function () {
  1463. return this.divideScalar( this.length() );
  1464. },
  1465. setLength: function ( length ) {
  1466. return this.multiplyScalar( length / this.length() );
  1467. },
  1468. lerp: function ( v, alpha ) {
  1469. this.x += ( v.x - this.x ) * alpha;
  1470. this.y += ( v.y - this.y ) * alpha;
  1471. this.z += ( v.z - this.z ) * alpha;
  1472. return this;
  1473. },
  1474. lerpVectors: function ( v1, v2, alpha ) {
  1475. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1476. return this;
  1477. },
  1478. cross: function ( v, w ) {
  1479. if ( w !== undefined ) {
  1480. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1481. return this.crossVectors( v, w );
  1482. }
  1483. var x = this.x, y = this.y, z = this.z;
  1484. this.x = y * v.z - z * v.y;
  1485. this.y = z * v.x - x * v.z;
  1486. this.z = x * v.y - y * v.x;
  1487. return this;
  1488. },
  1489. crossVectors: function ( a, b ) {
  1490. var ax = a.x, ay = a.y, az = a.z;
  1491. var bx = b.x, by = b.y, bz = b.z;
  1492. this.x = ay * bz - az * by;
  1493. this.y = az * bx - ax * bz;
  1494. this.z = ax * by - ay * bx;
  1495. return this;
  1496. },
  1497. projectOnVector: function () {
  1498. var v1, dot;
  1499. return function projectOnVector( vector ) {
  1500. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1501. v1.copy( vector ).normalize();
  1502. dot = this.dot( v1 );
  1503. return this.copy( v1 ).multiplyScalar( dot );
  1504. };
  1505. }(),
  1506. projectOnPlane: function () {
  1507. var v1;
  1508. return function projectOnPlane( planeNormal ) {
  1509. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1510. v1.copy( this ).projectOnVector( planeNormal );
  1511. return this.sub( v1 );
  1512. };
  1513. }(),
  1514. reflect: function () {
  1515. // reflect incident vector off plane orthogonal to normal
  1516. // normal is assumed to have unit length
  1517. var v1;
  1518. return function reflect( normal ) {
  1519. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1520. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1521. };
  1522. }(),
  1523. angleTo: function ( v ) {
  1524. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  1525. // clamp, to handle numerical problems
  1526. return Math.acos( THREE.Math.clamp( theta, - 1, 1 ) );
  1527. },
  1528. distanceTo: function ( v ) {
  1529. return Math.sqrt( this.distanceToSquared( v ) );
  1530. },
  1531. distanceToSquared: function ( v ) {
  1532. var dx = this.x - v.x;
  1533. var dy = this.y - v.y;
  1534. var dz = this.z - v.z;
  1535. return dx * dx + dy * dy + dz * dz;
  1536. },
  1537. setFromSpherical: function( s ) {
  1538. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  1539. this.x = sinPhiRadius * Math.sin( s.theta );
  1540. this.y = Math.cos( s.phi ) * s.radius;
  1541. this.z = sinPhiRadius * Math.cos( s.theta );
  1542. return this;
  1543. },
  1544. setFromMatrixPosition: function ( m ) {
  1545. return this.setFromMatrixColumn( m, 3 );
  1546. },
  1547. setFromMatrixScale: function ( m ) {
  1548. var sx = this.setFromMatrixColumn( m, 0 ).length();
  1549. var sy = this.setFromMatrixColumn( m, 1 ).length();
  1550. var sz = this.setFromMatrixColumn( m, 2 ).length();
  1551. this.x = sx;
  1552. this.y = sy;
  1553. this.z = sz;
  1554. return this;
  1555. },
  1556. setFromMatrixColumn: function ( m, index ) {
  1557. if ( typeof m === 'number' ) {
  1558. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  1559. m = arguments[ 1 ];
  1560. index = arguments[ 0 ];
  1561. }
  1562. return this.fromArray( m.elements, index * 4 );
  1563. },
  1564. equals: function ( v ) {
  1565. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1566. },
  1567. fromArray: function ( array, offset ) {
  1568. if ( offset === undefined ) offset = 0;
  1569. this.x = array[ offset ];
  1570. this.y = array[ offset + 1 ];
  1571. this.z = array[ offset + 2 ];
  1572. return this;
  1573. },
  1574. toArray: function ( array, offset ) {
  1575. if ( array === undefined ) array = [];
  1576. if ( offset === undefined ) offset = 0;
  1577. array[ offset ] = this.x;
  1578. array[ offset + 1 ] = this.y;
  1579. array[ offset + 2 ] = this.z;
  1580. return array;
  1581. },
  1582. fromAttribute: function ( attribute, index, offset ) {
  1583. if ( offset === undefined ) offset = 0;
  1584. index = index * attribute.itemSize + offset;
  1585. this.x = attribute.array[ index ];
  1586. this.y = attribute.array[ index + 1 ];
  1587. this.z = attribute.array[ index + 2 ];
  1588. return this;
  1589. }
  1590. };
  1591. // File:src/math/Vector4.js
  1592. /**
  1593. * @author supereggbert / http://www.paulbrunt.co.uk/
  1594. * @author philogb / http://blog.thejit.org/
  1595. * @author mikael emtinger / http://gomo.se/
  1596. * @author egraether / http://egraether.com/
  1597. * @author WestLangley / http://github.com/WestLangley
  1598. */
  1599. THREE.Vector4 = function ( x, y, z, w ) {
  1600. this.x = x || 0;
  1601. this.y = y || 0;
  1602. this.z = z || 0;
  1603. this.w = ( w !== undefined ) ? w : 1;
  1604. };
  1605. THREE.Vector4.prototype = {
  1606. constructor: THREE.Vector4,
  1607. set: function ( x, y, z, w ) {
  1608. this.x = x;
  1609. this.y = y;
  1610. this.z = z;
  1611. this.w = w;
  1612. return this;
  1613. },
  1614. setScalar: function ( scalar ) {
  1615. this.x = scalar;
  1616. this.y = scalar;
  1617. this.z = scalar;
  1618. this.w = scalar;
  1619. return this;
  1620. },
  1621. setX: function ( x ) {
  1622. this.x = x;
  1623. return this;
  1624. },
  1625. setY: function ( y ) {
  1626. this.y = y;
  1627. return this;
  1628. },
  1629. setZ: function ( z ) {
  1630. this.z = z;
  1631. return this;
  1632. },
  1633. setW: function ( w ) {
  1634. this.w = w;
  1635. return this;
  1636. },
  1637. setComponent: function ( index, value ) {
  1638. switch ( index ) {
  1639. case 0: this.x = value; break;
  1640. case 1: this.y = value; break;
  1641. case 2: this.z = value; break;
  1642. case 3: this.w = value; break;
  1643. default: throw new Error( 'index is out of range: ' + index );
  1644. }
  1645. },
  1646. getComponent: function ( index ) {
  1647. switch ( index ) {
  1648. case 0: return this.x;
  1649. case 1: return this.y;
  1650. case 2: return this.z;
  1651. case 3: return this.w;
  1652. default: throw new Error( 'index is out of range: ' + index );
  1653. }
  1654. },
  1655. clone: function () {
  1656. return new this.constructor( this.x, this.y, this.z, this.w );
  1657. },
  1658. copy: function ( v ) {
  1659. this.x = v.x;
  1660. this.y = v.y;
  1661. this.z = v.z;
  1662. this.w = ( v.w !== undefined ) ? v.w : 1;
  1663. return this;
  1664. },
  1665. add: function ( v, w ) {
  1666. if ( w !== undefined ) {
  1667. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1668. return this.addVectors( v, w );
  1669. }
  1670. this.x += v.x;
  1671. this.y += v.y;
  1672. this.z += v.z;
  1673. this.w += v.w;
  1674. return this;
  1675. },
  1676. addScalar: function ( s ) {
  1677. this.x += s;
  1678. this.y += s;
  1679. this.z += s;
  1680. this.w += s;
  1681. return this;
  1682. },
  1683. addVectors: function ( a, b ) {
  1684. this.x = a.x + b.x;
  1685. this.y = a.y + b.y;
  1686. this.z = a.z + b.z;
  1687. this.w = a.w + b.w;
  1688. return this;
  1689. },
  1690. addScaledVector: function ( v, s ) {
  1691. this.x += v.x * s;
  1692. this.y += v.y * s;
  1693. this.z += v.z * s;
  1694. this.w += v.w * s;
  1695. return this;
  1696. },
  1697. sub: function ( v, w ) {
  1698. if ( w !== undefined ) {
  1699. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1700. return this.subVectors( v, w );
  1701. }
  1702. this.x -= v.x;
  1703. this.y -= v.y;
  1704. this.z -= v.z;
  1705. this.w -= v.w;
  1706. return this;
  1707. },
  1708. subScalar: function ( s ) {
  1709. this.x -= s;
  1710. this.y -= s;
  1711. this.z -= s;
  1712. this.w -= s;
  1713. return this;
  1714. },
  1715. subVectors: function ( a, b ) {
  1716. this.x = a.x - b.x;
  1717. this.y = a.y - b.y;
  1718. this.z = a.z - b.z;
  1719. this.w = a.w - b.w;
  1720. return this;
  1721. },
  1722. multiplyScalar: function ( scalar ) {
  1723. if ( isFinite( scalar ) ) {
  1724. this.x *= scalar;
  1725. this.y *= scalar;
  1726. this.z *= scalar;
  1727. this.w *= scalar;
  1728. } else {
  1729. this.x = 0;
  1730. this.y = 0;
  1731. this.z = 0;
  1732. this.w = 0;
  1733. }
  1734. return this;
  1735. },
  1736. applyMatrix4: function ( m ) {
  1737. var x = this.x;
  1738. var y = this.y;
  1739. var z = this.z;
  1740. var w = this.w;
  1741. var e = m.elements;
  1742. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  1743. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  1744. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  1745. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  1746. return this;
  1747. },
  1748. divideScalar: function ( scalar ) {
  1749. return this.multiplyScalar( 1 / scalar );
  1750. },
  1751. setAxisAngleFromQuaternion: function ( q ) {
  1752. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1753. // q is assumed to be normalized
  1754. this.w = 2 * Math.acos( q.w );
  1755. var s = Math.sqrt( 1 - q.w * q.w );
  1756. if ( s < 0.0001 ) {
  1757. this.x = 1;
  1758. this.y = 0;
  1759. this.z = 0;
  1760. } else {
  1761. this.x = q.x / s;
  1762. this.y = q.y / s;
  1763. this.z = q.z / s;
  1764. }
  1765. return this;
  1766. },
  1767. setAxisAngleFromRotationMatrix: function ( m ) {
  1768. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1769. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1770. var angle, x, y, z, // variables for result
  1771. epsilon = 0.01, // margin to allow for rounding errors
  1772. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1773. te = m.elements,
  1774. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  1775. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  1776. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  1777. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  1778. ( Math.abs( m13 - m31 ) < epsilon ) &&
  1779. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1780. // singularity found
  1781. // first check for identity matrix which must have +1 for all terms
  1782. // in leading diagonal and zero in other terms
  1783. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  1784. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  1785. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  1786. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1787. // this singularity is identity matrix so angle = 0
  1788. this.set( 1, 0, 0, 0 );
  1789. return this; // zero angle, arbitrary axis
  1790. }
  1791. // otherwise this singularity is angle = 180
  1792. angle = Math.PI;
  1793. var xx = ( m11 + 1 ) / 2;
  1794. var yy = ( m22 + 1 ) / 2;
  1795. var zz = ( m33 + 1 ) / 2;
  1796. var xy = ( m12 + m21 ) / 4;
  1797. var xz = ( m13 + m31 ) / 4;
  1798. var yz = ( m23 + m32 ) / 4;
  1799. if ( ( xx > yy ) && ( xx > zz ) ) {
  1800. // m11 is the largest diagonal term
  1801. if ( xx < epsilon ) {
  1802. x = 0;
  1803. y = 0.707106781;
  1804. z = 0.707106781;
  1805. } else {
  1806. x = Math.sqrt( xx );
  1807. y = xy / x;
  1808. z = xz / x;
  1809. }
  1810. } else if ( yy > zz ) {
  1811. // m22 is the largest diagonal term
  1812. if ( yy < epsilon ) {
  1813. x = 0.707106781;
  1814. y = 0;
  1815. z = 0.707106781;
  1816. } else {
  1817. y = Math.sqrt( yy );
  1818. x = xy / y;
  1819. z = yz / y;
  1820. }
  1821. } else {
  1822. // m33 is the largest diagonal term so base result on this
  1823. if ( zz < epsilon ) {
  1824. x = 0.707106781;
  1825. y = 0.707106781;
  1826. z = 0;
  1827. } else {
  1828. z = Math.sqrt( zz );
  1829. x = xz / z;
  1830. y = yz / z;
  1831. }
  1832. }
  1833. this.set( x, y, z, angle );
  1834. return this; // return 180 deg rotation
  1835. }
  1836. // as we have reached here there are no singularities so we can handle normally
  1837. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  1838. ( m13 - m31 ) * ( m13 - m31 ) +
  1839. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1840. if ( Math.abs( s ) < 0.001 ) s = 1;
  1841. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1842. // caught by singularity test above, but I've left it in just in case
  1843. this.x = ( m32 - m23 ) / s;
  1844. this.y = ( m13 - m31 ) / s;
  1845. this.z = ( m21 - m12 ) / s;
  1846. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1847. return this;
  1848. },
  1849. min: function ( v ) {
  1850. this.x = Math.min( this.x, v.x );
  1851. this.y = Math.min( this.y, v.y );
  1852. this.z = Math.min( this.z, v.z );
  1853. this.w = Math.min( this.w, v.w );
  1854. return this;
  1855. },
  1856. max: function ( v ) {
  1857. this.x = Math.max( this.x, v.x );
  1858. this.y = Math.max( this.y, v.y );
  1859. this.z = Math.max( this.z, v.z );
  1860. this.w = Math.max( this.w, v.w );
  1861. return this;
  1862. },
  1863. clamp: function ( min, max ) {
  1864. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1865. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  1866. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  1867. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  1868. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  1869. return this;
  1870. },
  1871. clampScalar: function () {
  1872. var min, max;
  1873. return function clampScalar( minVal, maxVal ) {
  1874. if ( min === undefined ) {
  1875. min = new THREE.Vector4();
  1876. max = new THREE.Vector4();
  1877. }
  1878. min.set( minVal, minVal, minVal, minVal );
  1879. max.set( maxVal, maxVal, maxVal, maxVal );
  1880. return this.clamp( min, max );
  1881. };
  1882. }(),
  1883. floor: function () {
  1884. this.x = Math.floor( this.x );
  1885. this.y = Math.floor( this.y );
  1886. this.z = Math.floor( this.z );
  1887. this.w = Math.floor( this.w );
  1888. return this;
  1889. },
  1890. ceil: function () {
  1891. this.x = Math.ceil( this.x );
  1892. this.y = Math.ceil( this.y );
  1893. this.z = Math.ceil( this.z );
  1894. this.w = Math.ceil( this.w );
  1895. return this;
  1896. },
  1897. round: function () {
  1898. this.x = Math.round( this.x );
  1899. this.y = Math.round( this.y );
  1900. this.z = Math.round( this.z );
  1901. this.w = Math.round( this.w );
  1902. return this;
  1903. },
  1904. roundToZero: function () {
  1905. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1906. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1907. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1908. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1909. return this;
  1910. },
  1911. negate: function () {
  1912. this.x = - this.x;
  1913. this.y = - this.y;
  1914. this.z = - this.z;
  1915. this.w = - this.w;
  1916. return this;
  1917. },
  1918. dot: function ( v ) {
  1919. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1920. },
  1921. lengthSq: function () {
  1922. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1923. },
  1924. length: function () {
  1925. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1926. },
  1927. lengthManhattan: function () {
  1928. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1929. },
  1930. normalize: function () {
  1931. return this.divideScalar( this.length() );
  1932. },
  1933. setLength: function ( length ) {
  1934. return this.multiplyScalar( length / this.length() );
  1935. },
  1936. lerp: function ( v, alpha ) {
  1937. this.x += ( v.x - this.x ) * alpha;
  1938. this.y += ( v.y - this.y ) * alpha;
  1939. this.z += ( v.z - this.z ) * alpha;
  1940. this.w += ( v.w - this.w ) * alpha;
  1941. return this;
  1942. },
  1943. lerpVectors: function ( v1, v2, alpha ) {
  1944. this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  1945. return this;
  1946. },
  1947. equals: function ( v ) {
  1948. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1949. },
  1950. fromArray: function ( array, offset ) {
  1951. if ( offset === undefined ) offset = 0;
  1952. this.x = array[ offset ];
  1953. this.y = array[ offset + 1 ];
  1954. this.z = array[ offset + 2 ];
  1955. this.w = array[ offset + 3 ];
  1956. return this;
  1957. },
  1958. toArray: function ( array, offset ) {
  1959. if ( array === undefined ) array = [];
  1960. if ( offset === undefined ) offset = 0;
  1961. array[ offset ] = this.x;
  1962. array[ offset + 1 ] = this.y;
  1963. array[ offset + 2 ] = this.z;
  1964. array[ offset + 3 ] = this.w;
  1965. return array;
  1966. },
  1967. fromAttribute: function ( attribute, index, offset ) {
  1968. if ( offset === undefined ) offset = 0;
  1969. index = index * attribute.itemSize + offset;
  1970. this.x = attribute.array[ index ];
  1971. this.y = attribute.array[ index + 1 ];
  1972. this.z = attribute.array[ index + 2 ];
  1973. this.w = attribute.array[ index + 3 ];
  1974. return this;
  1975. }
  1976. };
  1977. // File:src/math/Euler.js
  1978. /**
  1979. * @author mrdoob / http://mrdoob.com/
  1980. * @author WestLangley / http://github.com/WestLangley
  1981. * @author bhouston / http://clara.io
  1982. */
  1983. THREE.Euler = function ( x, y, z, order ) {
  1984. this._x = x || 0;
  1985. this._y = y || 0;
  1986. this._z = z || 0;
  1987. this._order = order || THREE.Euler.DefaultOrder;
  1988. };
  1989. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1990. THREE.Euler.DefaultOrder = 'XYZ';
  1991. THREE.Euler.prototype = {
  1992. constructor: THREE.Euler,
  1993. get x () {
  1994. return this._x;
  1995. },
  1996. set x ( value ) {
  1997. this._x = value;
  1998. this.onChangeCallback();
  1999. },
  2000. get y () {
  2001. return this._y;
  2002. },
  2003. set y ( value ) {
  2004. this._y = value;
  2005. this.onChangeCallback();
  2006. },
  2007. get z () {
  2008. return this._z;
  2009. },
  2010. set z ( value ) {
  2011. this._z = value;
  2012. this.onChangeCallback();
  2013. },
  2014. get order () {
  2015. return this._order;
  2016. },
  2017. set order ( value ) {
  2018. this._order = value;
  2019. this.onChangeCallback();
  2020. },
  2021. set: function ( x, y, z, order ) {
  2022. this._x = x;
  2023. this._y = y;
  2024. this._z = z;
  2025. this._order = order || this._order;
  2026. this.onChangeCallback();
  2027. return this;
  2028. },
  2029. clone: function () {
  2030. return new this.constructor( this._x, this._y, this._z, this._order );
  2031. },
  2032. copy: function ( euler ) {
  2033. this._x = euler._x;
  2034. this._y = euler._y;
  2035. this._z = euler._z;
  2036. this._order = euler._order;
  2037. this.onChangeCallback();
  2038. return this;
  2039. },
  2040. setFromRotationMatrix: function ( m, order, update ) {
  2041. var clamp = THREE.Math.clamp;
  2042. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2043. var te = m.elements;
  2044. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  2045. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  2046. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  2047. order = order || this._order;
  2048. if ( order === 'XYZ' ) {
  2049. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  2050. if ( Math.abs( m13 ) < 0.99999 ) {
  2051. this._x = Math.atan2( - m23, m33 );
  2052. this._z = Math.atan2( - m12, m11 );
  2053. } else {
  2054. this._x = Math.atan2( m32, m22 );
  2055. this._z = 0;
  2056. }
  2057. } else if ( order === 'YXZ' ) {
  2058. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  2059. if ( Math.abs( m23 ) < 0.99999 ) {
  2060. this._y = Math.atan2( m13, m33 );
  2061. this._z = Math.atan2( m21, m22 );
  2062. } else {
  2063. this._y = Math.atan2( - m31, m11 );
  2064. this._z = 0;
  2065. }
  2066. } else if ( order === 'ZXY' ) {
  2067. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  2068. if ( Math.abs( m32 ) < 0.99999 ) {
  2069. this._y = Math.atan2( - m31, m33 );
  2070. this._z = Math.atan2( - m12, m22 );
  2071. } else {
  2072. this._y = 0;
  2073. this._z = Math.atan2( m21, m11 );
  2074. }
  2075. } else if ( order === 'ZYX' ) {
  2076. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  2077. if ( Math.abs( m31 ) < 0.99999 ) {
  2078. this._x = Math.atan2( m32, m33 );
  2079. this._z = Math.atan2( m21, m11 );
  2080. } else {
  2081. this._x = 0;
  2082. this._z = Math.atan2( - m12, m22 );
  2083. }
  2084. } else if ( order === 'YZX' ) {
  2085. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  2086. if ( Math.abs( m21 ) < 0.99999 ) {
  2087. this._x = Math.atan2( - m23, m22 );
  2088. this._y = Math.atan2( - m31, m11 );
  2089. } else {
  2090. this._x = 0;
  2091. this._y = Math.atan2( m13, m33 );
  2092. }
  2093. } else if ( order === 'XZY' ) {
  2094. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  2095. if ( Math.abs( m12 ) < 0.99999 ) {
  2096. this._x = Math.atan2( m32, m22 );
  2097. this._y = Math.atan2( m13, m11 );
  2098. } else {
  2099. this._x = Math.atan2( - m23, m33 );
  2100. this._y = 0;
  2101. }
  2102. } else {
  2103. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  2104. }
  2105. this._order = order;
  2106. if ( update !== false ) this.onChangeCallback();
  2107. return this;
  2108. },
  2109. setFromQuaternion: function () {
  2110. var matrix;
  2111. return function ( q, order, update ) {
  2112. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  2113. matrix.makeRotationFromQuaternion( q );
  2114. this.setFromRotationMatrix( matrix, order, update );
  2115. return this;
  2116. };
  2117. }(),
  2118. setFromVector3: function ( v, order ) {
  2119. return this.set( v.x, v.y, v.z, order || this._order );
  2120. },
  2121. reorder: function () {
  2122. // WARNING: this discards revolution information -bhouston
  2123. var q = new THREE.Quaternion();
  2124. return function ( newOrder ) {
  2125. q.setFromEuler( this );
  2126. this.setFromQuaternion( q, newOrder );
  2127. };
  2128. }(),
  2129. equals: function ( euler ) {
  2130. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  2131. },
  2132. fromArray: function ( array ) {
  2133. this._x = array[ 0 ];
  2134. this._y = array[ 1 ];
  2135. this._z = array[ 2 ];
  2136. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  2137. this.onChangeCallback();
  2138. return this;
  2139. },
  2140. toArray: function ( array, offset ) {
  2141. if ( array === undefined ) array = [];
  2142. if ( offset === undefined ) offset = 0;
  2143. array[ offset ] = this._x;
  2144. array[ offset + 1 ] = this._y;
  2145. array[ offset + 2 ] = this._z;
  2146. array[ offset + 3 ] = this._order;
  2147. return array;
  2148. },
  2149. toVector3: function ( optionalResult ) {
  2150. if ( optionalResult ) {
  2151. return optionalResult.set( this._x, this._y, this._z );
  2152. } else {
  2153. return new THREE.Vector3( this._x, this._y, this._z );
  2154. }
  2155. },
  2156. onChange: function ( callback ) {
  2157. this.onChangeCallback = callback;
  2158. return this;
  2159. },
  2160. onChangeCallback: function () {}
  2161. };
  2162. // File:src/math/Line3.js
  2163. /**
  2164. * @author bhouston / http://clara.io
  2165. */
  2166. THREE.Line3 = function ( start, end ) {
  2167. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  2168. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  2169. };
  2170. THREE.Line3.prototype = {
  2171. constructor: THREE.Line3,
  2172. set: function ( start, end ) {
  2173. this.start.copy( start );
  2174. this.end.copy( end );
  2175. return this;
  2176. },
  2177. clone: function () {
  2178. return new this.constructor().copy( this );
  2179. },
  2180. copy: function ( line ) {
  2181. this.start.copy( line.start );
  2182. this.end.copy( line.end );
  2183. return this;
  2184. },
  2185. center: function ( optionalTarget ) {
  2186. var result = optionalTarget || new THREE.Vector3();
  2187. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  2188. },
  2189. delta: function ( optionalTarget ) {
  2190. var result = optionalTarget || new THREE.Vector3();
  2191. return result.subVectors( this.end, this.start );
  2192. },
  2193. distanceSq: function () {
  2194. return this.start.distanceToSquared( this.end );
  2195. },
  2196. distance: function () {
  2197. return this.start.distanceTo( this.end );
  2198. },
  2199. at: function ( t, optionalTarget ) {
  2200. var result = optionalTarget || new THREE.Vector3();
  2201. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2202. },
  2203. closestPointToPointParameter: function () {
  2204. var startP = new THREE.Vector3();
  2205. var startEnd = new THREE.Vector3();
  2206. return function ( point, clampToLine ) {
  2207. startP.subVectors( point, this.start );
  2208. startEnd.subVectors( this.end, this.start );
  2209. var startEnd2 = startEnd.dot( startEnd );
  2210. var startEnd_startP = startEnd.dot( startP );
  2211. var t = startEnd_startP / startEnd2;
  2212. if ( clampToLine ) {
  2213. t = THREE.Math.clamp( t, 0, 1 );
  2214. }
  2215. return t;
  2216. };
  2217. }(),
  2218. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  2219. var t = this.closestPointToPointParameter( point, clampToLine );
  2220. var result = optionalTarget || new THREE.Vector3();
  2221. return this.delta( result ).multiplyScalar( t ).add( this.start );
  2222. },
  2223. applyMatrix4: function ( matrix ) {
  2224. this.start.applyMatrix4( matrix );
  2225. this.end.applyMatrix4( matrix );
  2226. return this;
  2227. },
  2228. equals: function ( line ) {
  2229. return line.start.equals( this.start ) && line.end.equals( this.end );
  2230. }
  2231. };
  2232. // File:src/math/Box2.js
  2233. /**
  2234. * @author bhouston / http://clara.io
  2235. */
  2236. THREE.Box2 = function ( min, max ) {
  2237. this.min = ( min !== undefined ) ? min : new THREE.Vector2( + Infinity, + Infinity );
  2238. this.max = ( max !== undefined ) ? max : new THREE.Vector2( - Infinity, - Infinity );
  2239. };
  2240. THREE.Box2.prototype = {
  2241. constructor: THREE.Box2,
  2242. set: function ( min, max ) {
  2243. this.min.copy( min );
  2244. this.max.copy( max );
  2245. return this;
  2246. },
  2247. setFromPoints: function ( points ) {
  2248. this.makeEmpty();
  2249. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2250. this.expandByPoint( points[ i ] );
  2251. }
  2252. return this;
  2253. },
  2254. setFromCenterAndSize: function () {
  2255. var v1 = new THREE.Vector2();
  2256. return function ( center, size ) {
  2257. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2258. this.min.copy( center ).sub( halfSize );
  2259. this.max.copy( center ).add( halfSize );
  2260. return this;
  2261. };
  2262. }(),
  2263. clone: function () {
  2264. return new this.constructor().copy( this );
  2265. },
  2266. copy: function ( box ) {
  2267. this.min.copy( box.min );
  2268. this.max.copy( box.max );
  2269. return this;
  2270. },
  2271. makeEmpty: function () {
  2272. this.min.x = this.min.y = + Infinity;
  2273. this.max.x = this.max.y = - Infinity;
  2274. return this;
  2275. },
  2276. isEmpty: function () {
  2277. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2278. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2279. },
  2280. center: function ( optionalTarget ) {
  2281. var result = optionalTarget || new THREE.Vector2();
  2282. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2283. },
  2284. size: function ( optionalTarget ) {
  2285. var result = optionalTarget || new THREE.Vector2();
  2286. return result.subVectors( this.max, this.min );
  2287. },
  2288. expandByPoint: function ( point ) {
  2289. this.min.min( point );
  2290. this.max.max( point );
  2291. return this;
  2292. },
  2293. expandByVector: function ( vector ) {
  2294. this.min.sub( vector );
  2295. this.max.add( vector );
  2296. return this;
  2297. },
  2298. expandByScalar: function ( scalar ) {
  2299. this.min.addScalar( - scalar );
  2300. this.max.addScalar( scalar );
  2301. return this;
  2302. },
  2303. containsPoint: function ( point ) {
  2304. if ( point.x < this.min.x || point.x > this.max.x ||
  2305. point.y < this.min.y || point.y > this.max.y ) {
  2306. return false;
  2307. }
  2308. return true;
  2309. },
  2310. containsBox: function ( box ) {
  2311. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2312. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2313. return true;
  2314. }
  2315. return false;
  2316. },
  2317. getParameter: function ( point, optionalTarget ) {
  2318. // This can potentially have a divide by zero if the box
  2319. // has a size dimension of 0.
  2320. var result = optionalTarget || new THREE.Vector2();
  2321. return result.set(
  2322. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2323. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2324. );
  2325. },
  2326. intersectsBox: function ( box ) {
  2327. // using 6 splitting planes to rule out intersections.
  2328. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2329. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2330. return false;
  2331. }
  2332. return true;
  2333. },
  2334. clampPoint: function ( point, optionalTarget ) {
  2335. var result = optionalTarget || new THREE.Vector2();
  2336. return result.copy( point ).clamp( this.min, this.max );
  2337. },
  2338. distanceToPoint: function () {
  2339. var v1 = new THREE.Vector2();
  2340. return function ( point ) {
  2341. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2342. return clampedPoint.sub( point ).length();
  2343. };
  2344. }(),
  2345. intersect: function ( box ) {
  2346. this.min.max( box.min );
  2347. this.max.min( box.max );
  2348. return this;
  2349. },
  2350. union: function ( box ) {
  2351. this.min.min( box.min );
  2352. this.max.max( box.max );
  2353. return this;
  2354. },
  2355. translate: function ( offset ) {
  2356. this.min.add( offset );
  2357. this.max.add( offset );
  2358. return this;
  2359. },
  2360. equals: function ( box ) {
  2361. return box.min.equals( this.min ) && box.max.equals( this.max );
  2362. }
  2363. };
  2364. // File:src/math/Box3.js
  2365. /**
  2366. * @author bhouston / http://clara.io
  2367. * @author WestLangley / http://github.com/WestLangley
  2368. */
  2369. THREE.Box3 = function ( min, max ) {
  2370. this.min = ( min !== undefined ) ? min : new THREE.Vector3( + Infinity, + Infinity, + Infinity );
  2371. this.max = ( max !== undefined ) ? max : new THREE.Vector3( - Infinity, - Infinity, - Infinity );
  2372. };
  2373. THREE.Box3.prototype = {
  2374. constructor: THREE.Box3,
  2375. set: function ( min, max ) {
  2376. this.min.copy( min );
  2377. this.max.copy( max );
  2378. return this;
  2379. },
  2380. setFromArray: function ( array ) {
  2381. var minX = + Infinity;
  2382. var minY = + Infinity;
  2383. var minZ = + Infinity;
  2384. var maxX = - Infinity;
  2385. var maxY = - Infinity;
  2386. var maxZ = - Infinity;
  2387. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  2388. var x = array[ i ];
  2389. var y = array[ i + 1 ];
  2390. var z = array[ i + 2 ];
  2391. if ( x < minX ) minX = x;
  2392. if ( y < minY ) minY = y;
  2393. if ( z < minZ ) minZ = z;
  2394. if ( x > maxX ) maxX = x;
  2395. if ( y > maxY ) maxY = y;
  2396. if ( z > maxZ ) maxZ = z;
  2397. }
  2398. this.min.set( minX, minY, minZ );
  2399. this.max.set( maxX, maxY, maxZ );
  2400. },
  2401. setFromPoints: function ( points ) {
  2402. this.makeEmpty();
  2403. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2404. this.expandByPoint( points[ i ] );
  2405. }
  2406. return this;
  2407. },
  2408. setFromCenterAndSize: function () {
  2409. var v1 = new THREE.Vector3();
  2410. return function ( center, size ) {
  2411. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2412. this.min.copy( center ).sub( halfSize );
  2413. this.max.copy( center ).add( halfSize );
  2414. return this;
  2415. };
  2416. }(),
  2417. setFromObject: function () {
  2418. // Computes the world-axis-aligned bounding box of an object (including its children),
  2419. // accounting for both the object's, and children's, world transforms
  2420. var v1 = new THREE.Vector3();
  2421. return function ( object ) {
  2422. var scope = this;
  2423. object.updateMatrixWorld( true );
  2424. this.makeEmpty();
  2425. object.traverse( function ( node ) {
  2426. var geometry = node.geometry;
  2427. if ( geometry !== undefined ) {
  2428. if ( geometry instanceof THREE.Geometry ) {
  2429. var vertices = geometry.vertices;
  2430. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  2431. v1.copy( vertices[ i ] );
  2432. v1.applyMatrix4( node.matrixWorld );
  2433. scope.expandByPoint( v1 );
  2434. }
  2435. } else if ( geometry instanceof THREE.BufferGeometry && geometry.attributes[ 'position' ] !== undefined ) {
  2436. var positions = geometry.attributes[ 'position' ].array;
  2437. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  2438. v1.fromArray( positions, i );
  2439. v1.applyMatrix4( node.matrixWorld );
  2440. scope.expandByPoint( v1 );
  2441. }
  2442. }
  2443. }
  2444. } );
  2445. return this;
  2446. };
  2447. }(),
  2448. clone: function () {
  2449. return new this.constructor().copy( this );
  2450. },
  2451. copy: function ( box ) {
  2452. this.min.copy( box.min );
  2453. this.max.copy( box.max );
  2454. return this;
  2455. },
  2456. makeEmpty: function () {
  2457. this.min.x = this.min.y = this.min.z = + Infinity;
  2458. this.max.x = this.max.y = this.max.z = - Infinity;
  2459. return this;
  2460. },
  2461. isEmpty: function () {
  2462. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2463. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2464. },
  2465. center: function ( optionalTarget ) {
  2466. var result = optionalTarget || new THREE.Vector3();
  2467. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2468. },
  2469. size: function ( optionalTarget ) {
  2470. var result = optionalTarget || new THREE.Vector3();
  2471. return result.subVectors( this.max, this.min );
  2472. },
  2473. expandByPoint: function ( point ) {
  2474. this.min.min( point );
  2475. this.max.max( point );
  2476. return this;
  2477. },
  2478. expandByVector: function ( vector ) {
  2479. this.min.sub( vector );
  2480. this.max.add( vector );
  2481. return this;
  2482. },
  2483. expandByScalar: function ( scalar ) {
  2484. this.min.addScalar( - scalar );
  2485. this.max.addScalar( scalar );
  2486. return this;
  2487. },
  2488. containsPoint: function ( point ) {
  2489. if ( point.x < this.min.x || point.x > this.max.x ||
  2490. point.y < this.min.y || point.y > this.max.y ||
  2491. point.z < this.min.z || point.z > this.max.z ) {
  2492. return false;
  2493. }
  2494. return true;
  2495. },
  2496. containsBox: function ( box ) {
  2497. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2498. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2499. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2500. return true;
  2501. }
  2502. return false;
  2503. },
  2504. getParameter: function ( point, optionalTarget ) {
  2505. // This can potentially have a divide by zero if the box
  2506. // has a size dimension of 0.
  2507. var result = optionalTarget || new THREE.Vector3();
  2508. return result.set(
  2509. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2510. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2511. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2512. );
  2513. },
  2514. intersectsBox: function ( box ) {
  2515. // using 6 splitting planes to rule out intersections.
  2516. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2517. box.max.y < this.min.y || box.min.y > this.max.y ||
  2518. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2519. return false;
  2520. }
  2521. return true;
  2522. },
  2523. intersectsSphere: ( function () {
  2524. var closestPoint;
  2525. return function intersectsSphere( sphere ) {
  2526. if ( closestPoint === undefined ) closestPoint = new THREE.Vector3();
  2527. // Find the point on the AABB closest to the sphere center.
  2528. this.clampPoint( sphere.center, closestPoint );
  2529. // If that point is inside the sphere, the AABB and sphere intersect.
  2530. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  2531. };
  2532. } )(),
  2533. intersectsPlane: function ( plane ) {
  2534. // We compute the minimum and maximum dot product values. If those values
  2535. // are on the same side (back or front) of the plane, then there is no intersection.
  2536. var min, max;
  2537. if ( plane.normal.x > 0 ) {
  2538. min = plane.normal.x * this.min.x;
  2539. max = plane.normal.x * this.max.x;
  2540. } else {
  2541. min = plane.normal.x * this.max.x;
  2542. max = plane.normal.x * this.min.x;
  2543. }
  2544. if ( plane.normal.y > 0 ) {
  2545. min += plane.normal.y * this.min.y;
  2546. max += plane.normal.y * this.max.y;
  2547. } else {
  2548. min += plane.normal.y * this.max.y;
  2549. max += plane.normal.y * this.min.y;
  2550. }
  2551. if ( plane.normal.z > 0 ) {
  2552. min += plane.normal.z * this.min.z;
  2553. max += plane.normal.z * this.max.z;
  2554. } else {
  2555. min += plane.normal.z * this.max.z;
  2556. max += plane.normal.z * this.min.z;
  2557. }
  2558. return ( min <= plane.constant && max >= plane.constant );
  2559. },
  2560. clampPoint: function ( point, optionalTarget ) {
  2561. var result = optionalTarget || new THREE.Vector3();
  2562. return result.copy( point ).clamp( this.min, this.max );
  2563. },
  2564. distanceToPoint: function () {
  2565. var v1 = new THREE.Vector3();
  2566. return function ( point ) {
  2567. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2568. return clampedPoint.sub( point ).length();
  2569. };
  2570. }(),
  2571. getBoundingSphere: function () {
  2572. var v1 = new THREE.Vector3();
  2573. return function ( optionalTarget ) {
  2574. var result = optionalTarget || new THREE.Sphere();
  2575. result.center = this.center();
  2576. result.radius = this.size( v1 ).length() * 0.5;
  2577. return result;
  2578. };
  2579. }(),
  2580. intersect: function ( box ) {
  2581. this.min.max( box.min );
  2582. this.max.min( box.max );
  2583. // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
  2584. if( this.isEmpty() ) this.makeEmpty();
  2585. return this;
  2586. },
  2587. union: function ( box ) {
  2588. this.min.min( box.min );
  2589. this.max.max( box.max );
  2590. return this;
  2591. },
  2592. applyMatrix4: function () {
  2593. var points = [
  2594. new THREE.Vector3(),
  2595. new THREE.Vector3(),
  2596. new THREE.Vector3(),
  2597. new THREE.Vector3(),
  2598. new THREE.Vector3(),
  2599. new THREE.Vector3(),
  2600. new THREE.Vector3(),
  2601. new THREE.Vector3()
  2602. ];
  2603. return function ( matrix ) {
  2604. // transform of empty box is an empty box.
  2605. if( this.isEmpty() ) return this;
  2606. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2607. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2608. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2609. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2610. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2611. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2612. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2613. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2614. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2615. this.setFromPoints( points );
  2616. return this;
  2617. };
  2618. }(),
  2619. translate: function ( offset ) {
  2620. this.min.add( offset );
  2621. this.max.add( offset );
  2622. return this;
  2623. },
  2624. equals: function ( box ) {
  2625. return box.min.equals( this.min ) && box.max.equals( this.max );
  2626. }
  2627. };
  2628. // File:src/math/Matrix3.js
  2629. /**
  2630. * @author alteredq / http://alteredqualia.com/
  2631. * @author WestLangley / http://github.com/WestLangley
  2632. * @author bhouston / http://clara.io
  2633. * @author tschw
  2634. */
  2635. THREE.Matrix3 = function () {
  2636. this.elements = new Float32Array( [
  2637. 1, 0, 0,
  2638. 0, 1, 0,
  2639. 0, 0, 1
  2640. ] );
  2641. if ( arguments.length > 0 ) {
  2642. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  2643. }
  2644. };
  2645. THREE.Matrix3.prototype = {
  2646. constructor: THREE.Matrix3,
  2647. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2648. var te = this.elements;
  2649. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  2650. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  2651. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  2652. return this;
  2653. },
  2654. identity: function () {
  2655. this.set(
  2656. 1, 0, 0,
  2657. 0, 1, 0,
  2658. 0, 0, 1
  2659. );
  2660. return this;
  2661. },
  2662. clone: function () {
  2663. return new this.constructor().fromArray( this.elements );
  2664. },
  2665. copy: function ( m ) {
  2666. var me = m.elements;
  2667. this.set(
  2668. me[ 0 ], me[ 3 ], me[ 6 ],
  2669. me[ 1 ], me[ 4 ], me[ 7 ],
  2670. me[ 2 ], me[ 5 ], me[ 8 ]
  2671. );
  2672. return this;
  2673. },
  2674. setFromMatrix4: function( m ) {
  2675. var me = m.elements;
  2676. this.set(
  2677. me[ 0 ], me[ 4 ], me[ 8 ],
  2678. me[ 1 ], me[ 5 ], me[ 9 ],
  2679. me[ 2 ], me[ 6 ], me[ 10 ]
  2680. );
  2681. return this;
  2682. },
  2683. applyToVector3Array: function () {
  2684. var v1;
  2685. return function ( array, offset, length ) {
  2686. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2687. if ( offset === undefined ) offset = 0;
  2688. if ( length === undefined ) length = array.length;
  2689. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  2690. v1.fromArray( array, j );
  2691. v1.applyMatrix3( this );
  2692. v1.toArray( array, j );
  2693. }
  2694. return array;
  2695. };
  2696. }(),
  2697. applyToBuffer: function () {
  2698. var v1;
  2699. return function applyToBuffer( buffer, offset, length ) {
  2700. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2701. if ( offset === undefined ) offset = 0;
  2702. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  2703. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  2704. v1.x = buffer.getX( j );
  2705. v1.y = buffer.getY( j );
  2706. v1.z = buffer.getZ( j );
  2707. v1.applyMatrix3( this );
  2708. buffer.setXYZ( v1.x, v1.y, v1.z );
  2709. }
  2710. return buffer;
  2711. };
  2712. }(),
  2713. multiplyScalar: function ( s ) {
  2714. var te = this.elements;
  2715. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  2716. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  2717. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  2718. return this;
  2719. },
  2720. determinant: function () {
  2721. var te = this.elements;
  2722. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  2723. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  2724. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  2725. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  2726. },
  2727. getInverse: function ( matrix, throwOnDegenerate ) {
  2728. if ( matrix instanceof THREE.Matrix4 ) {
  2729. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  2730. }
  2731. var me = matrix.elements,
  2732. te = this.elements,
  2733. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  2734. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  2735. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  2736. t11 = n33 * n22 - n32 * n23,
  2737. t12 = n32 * n13 - n33 * n12,
  2738. t13 = n23 * n12 - n22 * n13,
  2739. det = n11 * t11 + n21 * t12 + n31 * t13;
  2740. if ( det === 0 ) {
  2741. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2742. if ( throwOnDegenerate || false ) {
  2743. throw new Error( msg );
  2744. } else {
  2745. console.warn( msg );
  2746. }
  2747. return this.identity();
  2748. }
  2749. te[ 0 ] = t11;
  2750. te[ 1 ] = n31 * n23 - n33 * n21;
  2751. te[ 2 ] = n32 * n21 - n31 * n22;
  2752. te[ 3 ] = t12;
  2753. te[ 4 ] = n33 * n11 - n31 * n13;
  2754. te[ 5 ] = n31 * n12 - n32 * n11;
  2755. te[ 6 ] = t13;
  2756. te[ 7 ] = n21 * n13 - n23 * n11;
  2757. te[ 8 ] = n22 * n11 - n21 * n12;
  2758. return this.multiplyScalar( 1 / det );
  2759. },
  2760. transpose: function () {
  2761. var tmp, m = this.elements;
  2762. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  2763. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  2764. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  2765. return this;
  2766. },
  2767. flattenToArrayOffset: function ( array, offset ) {
  2768. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  2769. "- just use .toArray instead." );
  2770. return this.toArray( array, offset );
  2771. },
  2772. getNormalMatrix: function ( matrix4 ) {
  2773. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  2774. },
  2775. transposeIntoArray: function ( r ) {
  2776. var m = this.elements;
  2777. r[ 0 ] = m[ 0 ];
  2778. r[ 1 ] = m[ 3 ];
  2779. r[ 2 ] = m[ 6 ];
  2780. r[ 3 ] = m[ 1 ];
  2781. r[ 4 ] = m[ 4 ];
  2782. r[ 5 ] = m[ 7 ];
  2783. r[ 6 ] = m[ 2 ];
  2784. r[ 7 ] = m[ 5 ];
  2785. r[ 8 ] = m[ 8 ];
  2786. return this;
  2787. },
  2788. fromArray: function ( array ) {
  2789. this.elements.set( array );
  2790. return this;
  2791. },
  2792. toArray: function ( array, offset ) {
  2793. if ( array === undefined ) array = [];
  2794. if ( offset === undefined ) offset = 0;
  2795. var te = this.elements;
  2796. array[ offset ] = te[ 0 ];
  2797. array[ offset + 1 ] = te[ 1 ];
  2798. array[ offset + 2 ] = te[ 2 ];
  2799. array[ offset + 3 ] = te[ 3 ];
  2800. array[ offset + 4 ] = te[ 4 ];
  2801. array[ offset + 5 ] = te[ 5 ];
  2802. array[ offset + 6 ] = te[ 6 ];
  2803. array[ offset + 7 ] = te[ 7 ];
  2804. array[ offset + 8 ] = te[ 8 ];
  2805. return array;
  2806. }
  2807. };
  2808. // File:src/math/Matrix4.js
  2809. /**
  2810. * @author mrdoob / http://mrdoob.com/
  2811. * @author supereggbert / http://www.paulbrunt.co.uk/
  2812. * @author philogb / http://blog.thejit.org/
  2813. * @author jordi_ros / http://plattsoft.com
  2814. * @author D1plo1d / http://github.com/D1plo1d
  2815. * @author alteredq / http://alteredqualia.com/
  2816. * @author mikael emtinger / http://gomo.se/
  2817. * @author timknip / http://www.floorplanner.com/
  2818. * @author bhouston / http://clara.io
  2819. * @author WestLangley / http://github.com/WestLangley
  2820. */
  2821. THREE.Matrix4 = function () {
  2822. this.elements = new Float32Array( [
  2823. 1, 0, 0, 0,
  2824. 0, 1, 0, 0,
  2825. 0, 0, 1, 0,
  2826. 0, 0, 0, 1
  2827. ] );
  2828. if ( arguments.length > 0 ) {
  2829. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  2830. }
  2831. };
  2832. THREE.Matrix4.prototype = {
  2833. constructor: THREE.Matrix4,
  2834. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2835. var te = this.elements;
  2836. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  2837. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  2838. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  2839. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  2840. return this;
  2841. },
  2842. identity: function () {
  2843. this.set(
  2844. 1, 0, 0, 0,
  2845. 0, 1, 0, 0,
  2846. 0, 0, 1, 0,
  2847. 0, 0, 0, 1
  2848. );
  2849. return this;
  2850. },
  2851. clone: function () {
  2852. return new THREE.Matrix4().fromArray( this.elements );
  2853. },
  2854. copy: function ( m ) {
  2855. this.elements.set( m.elements );
  2856. return this;
  2857. },
  2858. copyPosition: function ( m ) {
  2859. var te = this.elements;
  2860. var me = m.elements;
  2861. te[ 12 ] = me[ 12 ];
  2862. te[ 13 ] = me[ 13 ];
  2863. te[ 14 ] = me[ 14 ];
  2864. return this;
  2865. },
  2866. extractBasis: function ( xAxis, yAxis, zAxis ) {
  2867. xAxis.setFromMatrixColumn( this, 0 );
  2868. yAxis.setFromMatrixColumn( this, 1 );
  2869. zAxis.setFromMatrixColumn( this, 2 );
  2870. return this;
  2871. },
  2872. makeBasis: function ( xAxis, yAxis, zAxis ) {
  2873. this.set(
  2874. xAxis.x, yAxis.x, zAxis.x, 0,
  2875. xAxis.y, yAxis.y, zAxis.y, 0,
  2876. xAxis.z, yAxis.z, zAxis.z, 0,
  2877. 0, 0, 0, 1
  2878. );
  2879. return this;
  2880. },
  2881. extractRotation: function () {
  2882. var v1;
  2883. return function ( m ) {
  2884. if ( v1 === undefined ) v1 = new THREE.Vector3();
  2885. var te = this.elements;
  2886. var me = m.elements;
  2887. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  2888. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  2889. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  2890. te[ 0 ] = me[ 0 ] * scaleX;
  2891. te[ 1 ] = me[ 1 ] * scaleX;
  2892. te[ 2 ] = me[ 2 ] * scaleX;
  2893. te[ 4 ] = me[ 4 ] * scaleY;
  2894. te[ 5 ] = me[ 5 ] * scaleY;
  2895. te[ 6 ] = me[ 6 ] * scaleY;
  2896. te[ 8 ] = me[ 8 ] * scaleZ;
  2897. te[ 9 ] = me[ 9 ] * scaleZ;
  2898. te[ 10 ] = me[ 10 ] * scaleZ;
  2899. return this;
  2900. };
  2901. }(),
  2902. makeRotationFromEuler: function ( euler ) {
  2903. if ( euler instanceof THREE.Euler === false ) {
  2904. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  2905. }
  2906. var te = this.elements;
  2907. var x = euler.x, y = euler.y, z = euler.z;
  2908. var a = Math.cos( x ), b = Math.sin( x );
  2909. var c = Math.cos( y ), d = Math.sin( y );
  2910. var e = Math.cos( z ), f = Math.sin( z );
  2911. if ( euler.order === 'XYZ' ) {
  2912. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2913. te[ 0 ] = c * e;
  2914. te[ 4 ] = - c * f;
  2915. te[ 8 ] = d;
  2916. te[ 1 ] = af + be * d;
  2917. te[ 5 ] = ae - bf * d;
  2918. te[ 9 ] = - b * c;
  2919. te[ 2 ] = bf - ae * d;
  2920. te[ 6 ] = be + af * d;
  2921. te[ 10 ] = a * c;
  2922. } else if ( euler.order === 'YXZ' ) {
  2923. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2924. te[ 0 ] = ce + df * b;
  2925. te[ 4 ] = de * b - cf;
  2926. te[ 8 ] = a * d;
  2927. te[ 1 ] = a * f;
  2928. te[ 5 ] = a * e;
  2929. te[ 9 ] = - b;
  2930. te[ 2 ] = cf * b - de;
  2931. te[ 6 ] = df + ce * b;
  2932. te[ 10 ] = a * c;
  2933. } else if ( euler.order === 'ZXY' ) {
  2934. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2935. te[ 0 ] = ce - df * b;
  2936. te[ 4 ] = - a * f;
  2937. te[ 8 ] = de + cf * b;
  2938. te[ 1 ] = cf + de * b;
  2939. te[ 5 ] = a * e;
  2940. te[ 9 ] = df - ce * b;
  2941. te[ 2 ] = - a * d;
  2942. te[ 6 ] = b;
  2943. te[ 10 ] = a * c;
  2944. } else if ( euler.order === 'ZYX' ) {
  2945. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2946. te[ 0 ] = c * e;
  2947. te[ 4 ] = be * d - af;
  2948. te[ 8 ] = ae * d + bf;
  2949. te[ 1 ] = c * f;
  2950. te[ 5 ] = bf * d + ae;
  2951. te[ 9 ] = af * d - be;
  2952. te[ 2 ] = - d;
  2953. te[ 6 ] = b * c;
  2954. te[ 10 ] = a * c;
  2955. } else if ( euler.order === 'YZX' ) {
  2956. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2957. te[ 0 ] = c * e;
  2958. te[ 4 ] = bd - ac * f;
  2959. te[ 8 ] = bc * f + ad;
  2960. te[ 1 ] = f;
  2961. te[ 5 ] = a * e;
  2962. te[ 9 ] = - b * e;
  2963. te[ 2 ] = - d * e;
  2964. te[ 6 ] = ad * f + bc;
  2965. te[ 10 ] = ac - bd * f;
  2966. } else if ( euler.order === 'XZY' ) {
  2967. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2968. te[ 0 ] = c * e;
  2969. te[ 4 ] = - f;
  2970. te[ 8 ] = d * e;
  2971. te[ 1 ] = ac * f + bd;
  2972. te[ 5 ] = a * e;
  2973. te[ 9 ] = ad * f - bc;
  2974. te[ 2 ] = bc * f - ad;
  2975. te[ 6 ] = b * e;
  2976. te[ 10 ] = bd * f + ac;
  2977. }
  2978. // last column
  2979. te[ 3 ] = 0;
  2980. te[ 7 ] = 0;
  2981. te[ 11 ] = 0;
  2982. // bottom row
  2983. te[ 12 ] = 0;
  2984. te[ 13 ] = 0;
  2985. te[ 14 ] = 0;
  2986. te[ 15 ] = 1;
  2987. return this;
  2988. },
  2989. makeRotationFromQuaternion: function ( q ) {
  2990. var te = this.elements;
  2991. var x = q.x, y = q.y, z = q.z, w = q.w;
  2992. var x2 = x + x, y2 = y + y, z2 = z + z;
  2993. var xx = x * x2, xy = x * y2, xz = x * z2;
  2994. var yy = y * y2, yz = y * z2, zz = z * z2;
  2995. var wx = w * x2, wy = w * y2, wz = w * z2;
  2996. te[ 0 ] = 1 - ( yy + zz );
  2997. te[ 4 ] = xy - wz;
  2998. te[ 8 ] = xz + wy;
  2999. te[ 1 ] = xy + wz;
  3000. te[ 5 ] = 1 - ( xx + zz );
  3001. te[ 9 ] = yz - wx;
  3002. te[ 2 ] = xz - wy;
  3003. te[ 6 ] = yz + wx;
  3004. te[ 10 ] = 1 - ( xx + yy );
  3005. // last column
  3006. te[ 3 ] = 0;
  3007. te[ 7 ] = 0;
  3008. te[ 11 ] = 0;
  3009. // bottom row
  3010. te[ 12 ] = 0;
  3011. te[ 13 ] = 0;
  3012. te[ 14 ] = 0;
  3013. te[ 15 ] = 1;
  3014. return this;
  3015. },
  3016. lookAt: function () {
  3017. var x, y, z;
  3018. return function ( eye, target, up ) {
  3019. if ( x === undefined ) x = new THREE.Vector3();
  3020. if ( y === undefined ) y = new THREE.Vector3();
  3021. if ( z === undefined ) z = new THREE.Vector3();
  3022. var te = this.elements;
  3023. z.subVectors( eye, target ).normalize();
  3024. if ( z.lengthSq() === 0 ) {
  3025. z.z = 1;
  3026. }
  3027. x.crossVectors( up, z ).normalize();
  3028. if ( x.lengthSq() === 0 ) {
  3029. z.x += 0.0001;
  3030. x.crossVectors( up, z ).normalize();
  3031. }
  3032. y.crossVectors( z, x );
  3033. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  3034. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  3035. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  3036. return this;
  3037. };
  3038. }(),
  3039. multiply: function ( m, n ) {
  3040. if ( n !== undefined ) {
  3041. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  3042. return this.multiplyMatrices( m, n );
  3043. }
  3044. return this.multiplyMatrices( this, m );
  3045. },
  3046. premultiply: function ( m ) {
  3047. return this.multiplyMatrices( m, this );
  3048. },
  3049. multiplyMatrices: function ( a, b ) {
  3050. var ae = a.elements;
  3051. var be = b.elements;
  3052. var te = this.elements;
  3053. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  3054. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  3055. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  3056. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  3057. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  3058. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  3059. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  3060. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  3061. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  3062. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  3063. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  3064. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  3065. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  3066. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  3067. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  3068. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  3069. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  3070. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  3071. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  3072. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  3073. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  3074. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  3075. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  3076. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  3077. return this;
  3078. },
  3079. multiplyToArray: function ( a, b, r ) {
  3080. var te = this.elements;
  3081. this.multiplyMatrices( a, b );
  3082. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  3083. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  3084. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  3085. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  3086. return this;
  3087. },
  3088. multiplyScalar: function ( s ) {
  3089. var te = this.elements;
  3090. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  3091. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  3092. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  3093. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  3094. return this;
  3095. },
  3096. applyToVector3Array: function () {
  3097. var v1;
  3098. return function ( array, offset, length ) {
  3099. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3100. if ( offset === undefined ) offset = 0;
  3101. if ( length === undefined ) length = array.length;
  3102. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  3103. v1.fromArray( array, j );
  3104. v1.applyMatrix4( this );
  3105. v1.toArray( array, j );
  3106. }
  3107. return array;
  3108. };
  3109. }(),
  3110. applyToBuffer: function () {
  3111. var v1;
  3112. return function applyToBuffer( buffer, offset, length ) {
  3113. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3114. if ( offset === undefined ) offset = 0;
  3115. if ( length === undefined ) length = buffer.length / buffer.itemSize;
  3116. for ( var i = 0, j = offset; i < length; i ++, j ++ ) {
  3117. v1.x = buffer.getX( j );
  3118. v1.y = buffer.getY( j );
  3119. v1.z = buffer.getZ( j );
  3120. v1.applyMatrix4( this );
  3121. buffer.setXYZ( v1.x, v1.y, v1.z );
  3122. }
  3123. return buffer;
  3124. };
  3125. }(),
  3126. determinant: function () {
  3127. var te = this.elements;
  3128. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  3129. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  3130. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  3131. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  3132. //TODO: make this more efficient
  3133. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  3134. return (
  3135. n41 * (
  3136. + n14 * n23 * n32
  3137. - n13 * n24 * n32
  3138. - n14 * n22 * n33
  3139. + n12 * n24 * n33
  3140. + n13 * n22 * n34
  3141. - n12 * n23 * n34
  3142. ) +
  3143. n42 * (
  3144. + n11 * n23 * n34
  3145. - n11 * n24 * n33
  3146. + n14 * n21 * n33
  3147. - n13 * n21 * n34
  3148. + n13 * n24 * n31
  3149. - n14 * n23 * n31
  3150. ) +
  3151. n43 * (
  3152. + n11 * n24 * n32
  3153. - n11 * n22 * n34
  3154. - n14 * n21 * n32
  3155. + n12 * n21 * n34
  3156. + n14 * n22 * n31
  3157. - n12 * n24 * n31
  3158. ) +
  3159. n44 * (
  3160. - n13 * n22 * n31
  3161. - n11 * n23 * n32
  3162. + n11 * n22 * n33
  3163. + n13 * n21 * n32
  3164. - n12 * n21 * n33
  3165. + n12 * n23 * n31
  3166. )
  3167. );
  3168. },
  3169. transpose: function () {
  3170. var te = this.elements;
  3171. var tmp;
  3172. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  3173. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  3174. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  3175. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  3176. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  3177. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  3178. return this;
  3179. },
  3180. flattenToArrayOffset: function ( array, offset ) {
  3181. console.warn( "THREE.Matrix3: .flattenToArrayOffset is deprecated " +
  3182. "- just use .toArray instead." );
  3183. return this.toArray( array, offset );
  3184. },
  3185. getPosition: function () {
  3186. var v1;
  3187. return function () {
  3188. if ( v1 === undefined ) v1 = new THREE.Vector3();
  3189. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  3190. return v1.setFromMatrixColumn( this, 3 );
  3191. };
  3192. }(),
  3193. setPosition: function ( v ) {
  3194. var te = this.elements;
  3195. te[ 12 ] = v.x;
  3196. te[ 13 ] = v.y;
  3197. te[ 14 ] = v.z;
  3198. return this;
  3199. },
  3200. getInverse: function ( m, throwOnDegenerate ) {
  3201. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  3202. var te = this.elements,
  3203. me = m.elements,
  3204. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  3205. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  3206. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  3207. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  3208. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  3209. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  3210. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  3211. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  3212. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  3213. if ( det === 0 ) {
  3214. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  3215. if ( throwOnDegenerate || false ) {
  3216. throw new Error( msg );
  3217. } else {
  3218. console.warn( msg );
  3219. }
  3220. return this.identity();
  3221. }
  3222. te[ 0 ] = t11;
  3223. te[ 1 ] = n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44;
  3224. te[ 2 ] = n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44;
  3225. te[ 3 ] = n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43;
  3226. te[ 4 ] = t12;
  3227. te[ 5 ] = n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44;
  3228. te[ 6 ] = n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44;
  3229. te[ 7 ] = n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43;
  3230. te[ 8 ] = t13;
  3231. te[ 9 ] = n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44;
  3232. te[ 10 ] = n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44;
  3233. te[ 11 ] = n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43;
  3234. te[ 12 ] = t14;
  3235. te[ 13 ] = n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34;
  3236. te[ 14 ] = n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34;
  3237. te[ 15 ] = n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33;
  3238. return this.multiplyScalar( 1 / det );
  3239. },
  3240. scale: function ( v ) {
  3241. var te = this.elements;
  3242. var x = v.x, y = v.y, z = v.z;
  3243. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  3244. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  3245. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  3246. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  3247. return this;
  3248. },
  3249. getMaxScaleOnAxis: function () {
  3250. var te = this.elements;
  3251. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  3252. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  3253. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  3254. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  3255. },
  3256. makeTranslation: function ( x, y, z ) {
  3257. this.set(
  3258. 1, 0, 0, x,
  3259. 0, 1, 0, y,
  3260. 0, 0, 1, z,
  3261. 0, 0, 0, 1
  3262. );
  3263. return this;
  3264. },
  3265. makeRotationX: function ( theta ) {
  3266. var c = Math.cos( theta ), s = Math.sin( theta );
  3267. this.set(
  3268. 1, 0, 0, 0,
  3269. 0, c, - s, 0,
  3270. 0, s, c, 0,
  3271. 0, 0, 0, 1
  3272. );
  3273. return this;
  3274. },
  3275. makeRotationY: function ( theta ) {
  3276. var c = Math.cos( theta ), s = Math.sin( theta );
  3277. this.set(
  3278. c, 0, s, 0,
  3279. 0, 1, 0, 0,
  3280. - s, 0, c, 0,
  3281. 0, 0, 0, 1
  3282. );
  3283. return this;
  3284. },
  3285. makeRotationZ: function ( theta ) {
  3286. var c = Math.cos( theta ), s = Math.sin( theta );
  3287. this.set(
  3288. c, - s, 0, 0,
  3289. s, c, 0, 0,
  3290. 0, 0, 1, 0,
  3291. 0, 0, 0, 1
  3292. );
  3293. return this;
  3294. },
  3295. makeRotationAxis: function ( axis, angle ) {
  3296. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3297. var c = Math.cos( angle );
  3298. var s = Math.sin( angle );
  3299. var t = 1 - c;
  3300. var x = axis.x, y = axis.y, z = axis.z;
  3301. var tx = t * x, ty = t * y;
  3302. this.set(
  3303. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3304. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3305. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3306. 0, 0, 0, 1
  3307. );
  3308. return this;
  3309. },
  3310. makeScale: function ( x, y, z ) {
  3311. this.set(
  3312. x, 0, 0, 0,
  3313. 0, y, 0, 0,
  3314. 0, 0, z, 0,
  3315. 0, 0, 0, 1
  3316. );
  3317. return this;
  3318. },
  3319. compose: function ( position, quaternion, scale ) {
  3320. this.makeRotationFromQuaternion( quaternion );
  3321. this.scale( scale );
  3322. this.setPosition( position );
  3323. return this;
  3324. },
  3325. decompose: function () {
  3326. var vector, matrix;
  3327. return function ( position, quaternion, scale ) {
  3328. if ( vector === undefined ) vector = new THREE.Vector3();
  3329. if ( matrix === undefined ) matrix = new THREE.Matrix4();
  3330. var te = this.elements;
  3331. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  3332. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  3333. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  3334. // if determine is negative, we need to invert one scale
  3335. var det = this.determinant();
  3336. if ( det < 0 ) {
  3337. sx = - sx;
  3338. }
  3339. position.x = te[ 12 ];
  3340. position.y = te[ 13 ];
  3341. position.z = te[ 14 ];
  3342. // scale the rotation part
  3343. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3344. var invSX = 1 / sx;
  3345. var invSY = 1 / sy;
  3346. var invSZ = 1 / sz;
  3347. matrix.elements[ 0 ] *= invSX;
  3348. matrix.elements[ 1 ] *= invSX;
  3349. matrix.elements[ 2 ] *= invSX;
  3350. matrix.elements[ 4 ] *= invSY;
  3351. matrix.elements[ 5 ] *= invSY;
  3352. matrix.elements[ 6 ] *= invSY;
  3353. matrix.elements[ 8 ] *= invSZ;
  3354. matrix.elements[ 9 ] *= invSZ;
  3355. matrix.elements[ 10 ] *= invSZ;
  3356. quaternion.setFromRotationMatrix( matrix );
  3357. scale.x = sx;
  3358. scale.y = sy;
  3359. scale.z = sz;
  3360. return this;
  3361. };
  3362. }(),
  3363. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3364. var te = this.elements;
  3365. var x = 2 * near / ( right - left );
  3366. var y = 2 * near / ( top - bottom );
  3367. var a = ( right + left ) / ( right - left );
  3368. var b = ( top + bottom ) / ( top - bottom );
  3369. var c = - ( far + near ) / ( far - near );
  3370. var d = - 2 * far * near / ( far - near );
  3371. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  3372. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  3373. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  3374. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  3375. return this;
  3376. },
  3377. makePerspective: function ( fov, aspect, near, far ) {
  3378. var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 );
  3379. var ymin = - ymax;
  3380. var xmin = ymin * aspect;
  3381. var xmax = ymax * aspect;
  3382. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3383. },
  3384. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3385. var te = this.elements;
  3386. var w = 1.0 / ( right - left );
  3387. var h = 1.0 / ( top - bottom );
  3388. var p = 1.0 / ( far - near );
  3389. var x = ( right + left ) * w;
  3390. var y = ( top + bottom ) * h;
  3391. var z = ( far + near ) * p;
  3392. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  3393. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  3394. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  3395. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  3396. return this;
  3397. },
  3398. equals: function ( matrix ) {
  3399. var te = this.elements;
  3400. var me = matrix.elements;
  3401. for ( var i = 0; i < 16; i ++ ) {
  3402. if ( te[ i ] !== me[ i ] ) return false;
  3403. }
  3404. return true;
  3405. },
  3406. fromArray: function ( array ) {
  3407. this.elements.set( array );
  3408. return this;
  3409. },
  3410. toArray: function ( array, offset ) {
  3411. if ( array === undefined ) array = [];
  3412. if ( offset === undefined ) offset = 0;
  3413. var te = this.elements;
  3414. array[ offset ] = te[ 0 ];
  3415. array[ offset + 1 ] = te[ 1 ];
  3416. array[ offset + 2 ] = te[ 2 ];
  3417. array[ offset + 3 ] = te[ 3 ];
  3418. array[ offset + 4 ] = te[ 4 ];
  3419. array[ offset + 5 ] = te[ 5 ];
  3420. array[ offset + 6 ] = te[ 6 ];
  3421. array[ offset + 7 ] = te[ 7 ];
  3422. array[ offset + 8 ] = te[ 8 ];
  3423. array[ offset + 9 ] = te[ 9 ];
  3424. array[ offset + 10 ] = te[ 10 ];
  3425. array[ offset + 11 ] = te[ 11 ];
  3426. array[ offset + 12 ] = te[ 12 ];
  3427. array[ offset + 13 ] = te[ 13 ];
  3428. array[ offset + 14 ] = te[ 14 ];
  3429. array[ offset + 15 ] = te[ 15 ];
  3430. return array;
  3431. }
  3432. };
  3433. // File:src/math/Ray.js
  3434. /**
  3435. * @author bhouston / http://clara.io
  3436. */
  3437. THREE.Ray = function ( origin, direction ) {
  3438. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3439. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3440. };
  3441. THREE.Ray.prototype = {
  3442. constructor: THREE.Ray,
  3443. set: function ( origin, direction ) {
  3444. this.origin.copy( origin );
  3445. this.direction.copy( direction );
  3446. return this;
  3447. },
  3448. clone: function () {
  3449. return new this.constructor().copy( this );
  3450. },
  3451. copy: function ( ray ) {
  3452. this.origin.copy( ray.origin );
  3453. this.direction.copy( ray.direction );
  3454. return this;
  3455. },
  3456. at: function ( t, optionalTarget ) {
  3457. var result = optionalTarget || new THREE.Vector3();
  3458. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3459. },
  3460. lookAt: function ( v ) {
  3461. this.direction.copy( v ).sub( this.origin ).normalize();
  3462. },
  3463. recast: function () {
  3464. var v1 = new THREE.Vector3();
  3465. return function ( t ) {
  3466. this.origin.copy( this.at( t, v1 ) );
  3467. return this;
  3468. };
  3469. }(),
  3470. closestPointToPoint: function ( point, optionalTarget ) {
  3471. var result = optionalTarget || new THREE.Vector3();
  3472. result.subVectors( point, this.origin );
  3473. var directionDistance = result.dot( this.direction );
  3474. if ( directionDistance < 0 ) {
  3475. return result.copy( this.origin );
  3476. }
  3477. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3478. },
  3479. distanceToPoint: function ( point ) {
  3480. return Math.sqrt( this.distanceSqToPoint( point ) );
  3481. },
  3482. distanceSqToPoint: function () {
  3483. var v1 = new THREE.Vector3();
  3484. return function ( point ) {
  3485. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3486. // point behind the ray
  3487. if ( directionDistance < 0 ) {
  3488. return this.origin.distanceToSquared( point );
  3489. }
  3490. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3491. return v1.distanceToSquared( point );
  3492. };
  3493. }(),
  3494. distanceSqToSegment: function () {
  3495. var segCenter = new THREE.Vector3();
  3496. var segDir = new THREE.Vector3();
  3497. var diff = new THREE.Vector3();
  3498. return function ( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3499. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3500. // It returns the min distance between the ray and the segment
  3501. // defined by v0 and v1
  3502. // It can also set two optional targets :
  3503. // - The closest point on the ray
  3504. // - The closest point on the segment
  3505. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  3506. segDir.copy( v1 ).sub( v0 ).normalize();
  3507. diff.copy( this.origin ).sub( segCenter );
  3508. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3509. var a01 = - this.direction.dot( segDir );
  3510. var b0 = diff.dot( this.direction );
  3511. var b1 = - diff.dot( segDir );
  3512. var c = diff.lengthSq();
  3513. var det = Math.abs( 1 - a01 * a01 );
  3514. var s0, s1, sqrDist, extDet;
  3515. if ( det > 0 ) {
  3516. // The ray and segment are not parallel.
  3517. s0 = a01 * b1 - b0;
  3518. s1 = a01 * b0 - b1;
  3519. extDet = segExtent * det;
  3520. if ( s0 >= 0 ) {
  3521. if ( s1 >= - extDet ) {
  3522. if ( s1 <= extDet ) {
  3523. // region 0
  3524. // Minimum at interior points of ray and segment.
  3525. var invDet = 1 / det;
  3526. s0 *= invDet;
  3527. s1 *= invDet;
  3528. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3529. } else {
  3530. // region 1
  3531. s1 = segExtent;
  3532. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3533. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3534. }
  3535. } else {
  3536. // region 5
  3537. s1 = - segExtent;
  3538. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3539. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3540. }
  3541. } else {
  3542. if ( s1 <= - extDet ) {
  3543. // region 4
  3544. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3545. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3546. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3547. } else if ( s1 <= extDet ) {
  3548. // region 3
  3549. s0 = 0;
  3550. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3551. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3552. } else {
  3553. // region 2
  3554. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3555. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3556. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3557. }
  3558. }
  3559. } else {
  3560. // Ray and segment are parallel.
  3561. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3562. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3563. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3564. }
  3565. if ( optionalPointOnRay ) {
  3566. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  3567. }
  3568. if ( optionalPointOnSegment ) {
  3569. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  3570. }
  3571. return sqrDist;
  3572. };
  3573. }(),
  3574. intersectSphere: function () {
  3575. var v1 = new THREE.Vector3();
  3576. return function ( sphere, optionalTarget ) {
  3577. v1.subVectors( sphere.center, this.origin );
  3578. var tca = v1.dot( this.direction );
  3579. var d2 = v1.dot( v1 ) - tca * tca;
  3580. var radius2 = sphere.radius * sphere.radius;
  3581. if ( d2 > radius2 ) return null;
  3582. var thc = Math.sqrt( radius2 - d2 );
  3583. // t0 = first intersect point - entrance on front of sphere
  3584. var t0 = tca - thc;
  3585. // t1 = second intersect point - exit point on back of sphere
  3586. var t1 = tca + thc;
  3587. // test to see if both t0 and t1 are behind the ray - if so, return null
  3588. if ( t0 < 0 && t1 < 0 ) return null;
  3589. // test to see if t0 is behind the ray:
  3590. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  3591. // in order to always return an intersect point that is in front of the ray.
  3592. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  3593. // else t0 is in front of the ray, so return the first collision point scaled by t0
  3594. return this.at( t0, optionalTarget );
  3595. };
  3596. }(),
  3597. intersectsSphere: function ( sphere ) {
  3598. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3599. },
  3600. distanceToPlane: function ( plane ) {
  3601. var denominator = plane.normal.dot( this.direction );
  3602. if ( denominator === 0 ) {
  3603. // line is coplanar, return origin
  3604. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  3605. return 0;
  3606. }
  3607. // Null is preferable to undefined since undefined means.... it is undefined
  3608. return null;
  3609. }
  3610. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3611. // Return if the ray never intersects the plane
  3612. return t >= 0 ? t : null;
  3613. },
  3614. intersectPlane: function ( plane, optionalTarget ) {
  3615. var t = this.distanceToPlane( plane );
  3616. if ( t === null ) {
  3617. return null;
  3618. }
  3619. return this.at( t, optionalTarget );
  3620. },
  3621. intersectsPlane: function ( plane ) {
  3622. // check if the ray lies on the plane first
  3623. var distToPoint = plane.distanceToPoint( this.origin );
  3624. if ( distToPoint === 0 ) {
  3625. return true;
  3626. }
  3627. var denominator = plane.normal.dot( this.direction );
  3628. if ( denominator * distToPoint < 0 ) {
  3629. return true;
  3630. }
  3631. // ray origin is behind the plane (and is pointing behind it)
  3632. return false;
  3633. },
  3634. intersectBox: function ( box, optionalTarget ) {
  3635. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  3636. var invdirx = 1 / this.direction.x,
  3637. invdiry = 1 / this.direction.y,
  3638. invdirz = 1 / this.direction.z;
  3639. var origin = this.origin;
  3640. if ( invdirx >= 0 ) {
  3641. tmin = ( box.min.x - origin.x ) * invdirx;
  3642. tmax = ( box.max.x - origin.x ) * invdirx;
  3643. } else {
  3644. tmin = ( box.max.x - origin.x ) * invdirx;
  3645. tmax = ( box.min.x - origin.x ) * invdirx;
  3646. }
  3647. if ( invdiry >= 0 ) {
  3648. tymin = ( box.min.y - origin.y ) * invdiry;
  3649. tymax = ( box.max.y - origin.y ) * invdiry;
  3650. } else {
  3651. tymin = ( box.max.y - origin.y ) * invdiry;
  3652. tymax = ( box.min.y - origin.y ) * invdiry;
  3653. }
  3654. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  3655. // These lines also handle the case where tmin or tmax is NaN
  3656. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3657. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  3658. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  3659. if ( invdirz >= 0 ) {
  3660. tzmin = ( box.min.z - origin.z ) * invdirz;
  3661. tzmax = ( box.max.z - origin.z ) * invdirz;
  3662. } else {
  3663. tzmin = ( box.max.z - origin.z ) * invdirz;
  3664. tzmax = ( box.min.z - origin.z ) * invdirz;
  3665. }
  3666. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  3667. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3668. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3669. //return point closest to the ray (positive side)
  3670. if ( tmax < 0 ) return null;
  3671. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3672. },
  3673. intersectsBox: ( function () {
  3674. var v = new THREE.Vector3();
  3675. return function ( box ) {
  3676. return this.intersectBox( box, v ) !== null;
  3677. };
  3678. } )(),
  3679. intersectTriangle: function () {
  3680. // Compute the offset origin, edges, and normal.
  3681. var diff = new THREE.Vector3();
  3682. var edge1 = new THREE.Vector3();
  3683. var edge2 = new THREE.Vector3();
  3684. var normal = new THREE.Vector3();
  3685. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3686. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3687. edge1.subVectors( b, a );
  3688. edge2.subVectors( c, a );
  3689. normal.crossVectors( edge1, edge2 );
  3690. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3691. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3692. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3693. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3694. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3695. var DdN = this.direction.dot( normal );
  3696. var sign;
  3697. if ( DdN > 0 ) {
  3698. if ( backfaceCulling ) return null;
  3699. sign = 1;
  3700. } else if ( DdN < 0 ) {
  3701. sign = - 1;
  3702. DdN = - DdN;
  3703. } else {
  3704. return null;
  3705. }
  3706. diff.subVectors( this.origin, a );
  3707. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3708. // b1 < 0, no intersection
  3709. if ( DdQxE2 < 0 ) {
  3710. return null;
  3711. }
  3712. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3713. // b2 < 0, no intersection
  3714. if ( DdE1xQ < 0 ) {
  3715. return null;
  3716. }
  3717. // b1+b2 > 1, no intersection
  3718. if ( DdQxE2 + DdE1xQ > DdN ) {
  3719. return null;
  3720. }
  3721. // Line intersects triangle, check if ray does.
  3722. var QdN = - sign * diff.dot( normal );
  3723. // t < 0, no intersection
  3724. if ( QdN < 0 ) {
  3725. return null;
  3726. }
  3727. // Ray intersects triangle.
  3728. return this.at( QdN / DdN, optionalTarget );
  3729. };
  3730. }(),
  3731. applyMatrix4: function ( matrix4 ) {
  3732. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3733. this.origin.applyMatrix4( matrix4 );
  3734. this.direction.sub( this.origin );
  3735. this.direction.normalize();
  3736. return this;
  3737. },
  3738. equals: function ( ray ) {
  3739. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3740. }
  3741. };
  3742. // File:src/math/Sphere.js
  3743. /**
  3744. * @author bhouston / http://clara.io
  3745. * @author mrdoob / http://mrdoob.com/
  3746. */
  3747. THREE.Sphere = function ( center, radius ) {
  3748. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3749. this.radius = ( radius !== undefined ) ? radius : 0;
  3750. };
  3751. THREE.Sphere.prototype = {
  3752. constructor: THREE.Sphere,
  3753. set: function ( center, radius ) {
  3754. this.center.copy( center );
  3755. this.radius = radius;
  3756. return this;
  3757. },
  3758. setFromPoints: function () {
  3759. var box = new THREE.Box3();
  3760. return function ( points, optionalCenter ) {
  3761. var center = this.center;
  3762. if ( optionalCenter !== undefined ) {
  3763. center.copy( optionalCenter );
  3764. } else {
  3765. box.setFromPoints( points ).center( center );
  3766. }
  3767. var maxRadiusSq = 0;
  3768. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3769. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3770. }
  3771. this.radius = Math.sqrt( maxRadiusSq );
  3772. return this;
  3773. };
  3774. }(),
  3775. clone: function () {
  3776. return new this.constructor().copy( this );
  3777. },
  3778. copy: function ( sphere ) {
  3779. this.center.copy( sphere.center );
  3780. this.radius = sphere.radius;
  3781. return this;
  3782. },
  3783. empty: function () {
  3784. return ( this.radius <= 0 );
  3785. },
  3786. containsPoint: function ( point ) {
  3787. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3788. },
  3789. distanceToPoint: function ( point ) {
  3790. return ( point.distanceTo( this.center ) - this.radius );
  3791. },
  3792. intersectsSphere: function ( sphere ) {
  3793. var radiusSum = this.radius + sphere.radius;
  3794. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3795. },
  3796. intersectsBox: function ( box ) {
  3797. return box.intersectsSphere( this );
  3798. },
  3799. intersectsPlane: function ( plane ) {
  3800. // We use the following equation to compute the signed distance from
  3801. // the center of the sphere to the plane.
  3802. //
  3803. // distance = q * n - d
  3804. //
  3805. // If this distance is greater than the radius of the sphere,
  3806. // then there is no intersection.
  3807. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  3808. },
  3809. clampPoint: function ( point, optionalTarget ) {
  3810. var deltaLengthSq = this.center.distanceToSquared( point );
  3811. var result = optionalTarget || new THREE.Vector3();
  3812. result.copy( point );
  3813. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3814. result.sub( this.center ).normalize();
  3815. result.multiplyScalar( this.radius ).add( this.center );
  3816. }
  3817. return result;
  3818. },
  3819. getBoundingBox: function ( optionalTarget ) {
  3820. var box = optionalTarget || new THREE.Box3();
  3821. box.set( this.center, this.center );
  3822. box.expandByScalar( this.radius );
  3823. return box;
  3824. },
  3825. applyMatrix4: function ( matrix ) {
  3826. this.center.applyMatrix4( matrix );
  3827. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3828. return this;
  3829. },
  3830. translate: function ( offset ) {
  3831. this.center.add( offset );
  3832. return this;
  3833. },
  3834. equals: function ( sphere ) {
  3835. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3836. }
  3837. };
  3838. // File:src/math/Frustum.js
  3839. /**
  3840. * @author mrdoob / http://mrdoob.com/
  3841. * @author alteredq / http://alteredqualia.com/
  3842. * @author bhouston / http://clara.io
  3843. */
  3844. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3845. this.planes = [
  3846. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3847. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3848. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3849. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3850. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3851. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3852. ];
  3853. };
  3854. THREE.Frustum.prototype = {
  3855. constructor: THREE.Frustum,
  3856. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3857. var planes = this.planes;
  3858. planes[ 0 ].copy( p0 );
  3859. planes[ 1 ].copy( p1 );
  3860. planes[ 2 ].copy( p2 );
  3861. planes[ 3 ].copy( p3 );
  3862. planes[ 4 ].copy( p4 );
  3863. planes[ 5 ].copy( p5 );
  3864. return this;
  3865. },
  3866. clone: function () {
  3867. return new this.constructor().copy( this );
  3868. },
  3869. copy: function ( frustum ) {
  3870. var planes = this.planes;
  3871. for ( var i = 0; i < 6; i ++ ) {
  3872. planes[ i ].copy( frustum.planes[ i ] );
  3873. }
  3874. return this;
  3875. },
  3876. setFromMatrix: function ( m ) {
  3877. var planes = this.planes;
  3878. var me = m.elements;
  3879. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  3880. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  3881. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  3882. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  3883. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3884. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3885. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3886. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3887. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3888. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3889. return this;
  3890. },
  3891. intersectsObject: function () {
  3892. var sphere = new THREE.Sphere();
  3893. return function ( object ) {
  3894. var geometry = object.geometry;
  3895. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3896. sphere.copy( geometry.boundingSphere );
  3897. sphere.applyMatrix4( object.matrixWorld );
  3898. return this.intersectsSphere( sphere );
  3899. };
  3900. }(),
  3901. intersectsSphere: function ( sphere ) {
  3902. var planes = this.planes;
  3903. var center = sphere.center;
  3904. var negRadius = - sphere.radius;
  3905. for ( var i = 0; i < 6; i ++ ) {
  3906. var distance = planes[ i ].distanceToPoint( center );
  3907. if ( distance < negRadius ) {
  3908. return false;
  3909. }
  3910. }
  3911. return true;
  3912. },
  3913. intersectsBox: function () {
  3914. var p1 = new THREE.Vector3(),
  3915. p2 = new THREE.Vector3();
  3916. return function ( box ) {
  3917. var planes = this.planes;
  3918. for ( var i = 0; i < 6 ; i ++ ) {
  3919. var plane = planes[ i ];
  3920. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3921. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3922. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3923. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3924. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3925. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3926. var d1 = plane.distanceToPoint( p1 );
  3927. var d2 = plane.distanceToPoint( p2 );
  3928. // if both outside plane, no intersection
  3929. if ( d1 < 0 && d2 < 0 ) {
  3930. return false;
  3931. }
  3932. }
  3933. return true;
  3934. };
  3935. }(),
  3936. containsPoint: function ( point ) {
  3937. var planes = this.planes;
  3938. for ( var i = 0; i < 6; i ++ ) {
  3939. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3940. return false;
  3941. }
  3942. }
  3943. return true;
  3944. }
  3945. };
  3946. // File:src/math/Plane.js
  3947. /**
  3948. * @author bhouston / http://clara.io
  3949. */
  3950. THREE.Plane = function ( normal, constant ) {
  3951. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3952. this.constant = ( constant !== undefined ) ? constant : 0;
  3953. };
  3954. THREE.Plane.prototype = {
  3955. constructor: THREE.Plane,
  3956. set: function ( normal, constant ) {
  3957. this.normal.copy( normal );
  3958. this.constant = constant;
  3959. return this;
  3960. },
  3961. setComponents: function ( x, y, z, w ) {
  3962. this.normal.set( x, y, z );
  3963. this.constant = w;
  3964. return this;
  3965. },
  3966. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3967. this.normal.copy( normal );
  3968. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3969. return this;
  3970. },
  3971. setFromCoplanarPoints: function () {
  3972. var v1 = new THREE.Vector3();
  3973. var v2 = new THREE.Vector3();
  3974. return function ( a, b, c ) {
  3975. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3976. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3977. this.setFromNormalAndCoplanarPoint( normal, a );
  3978. return this;
  3979. };
  3980. }(),
  3981. clone: function () {
  3982. return new this.constructor().copy( this );
  3983. },
  3984. copy: function ( plane ) {
  3985. this.normal.copy( plane.normal );
  3986. this.constant = plane.constant;
  3987. return this;
  3988. },
  3989. normalize: function () {
  3990. // Note: will lead to a divide by zero if the plane is invalid.
  3991. var inverseNormalLength = 1.0 / this.normal.length();
  3992. this.normal.multiplyScalar( inverseNormalLength );
  3993. this.constant *= inverseNormalLength;
  3994. return this;
  3995. },
  3996. negate: function () {
  3997. this.constant *= - 1;
  3998. this.normal.negate();
  3999. return this;
  4000. },
  4001. distanceToPoint: function ( point ) {
  4002. return this.normal.dot( point ) + this.constant;
  4003. },
  4004. distanceToSphere: function ( sphere ) {
  4005. return this.distanceToPoint( sphere.center ) - sphere.radius;
  4006. },
  4007. projectPoint: function ( point, optionalTarget ) {
  4008. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  4009. },
  4010. orthoPoint: function ( point, optionalTarget ) {
  4011. var perpendicularMagnitude = this.distanceToPoint( point );
  4012. var result = optionalTarget || new THREE.Vector3();
  4013. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  4014. },
  4015. intersectLine: function () {
  4016. var v1 = new THREE.Vector3();
  4017. return function ( line, optionalTarget ) {
  4018. var result = optionalTarget || new THREE.Vector3();
  4019. var direction = line.delta( v1 );
  4020. var denominator = this.normal.dot( direction );
  4021. if ( denominator === 0 ) {
  4022. // line is coplanar, return origin
  4023. if ( this.distanceToPoint( line.start ) === 0 ) {
  4024. return result.copy( line.start );
  4025. }
  4026. // Unsure if this is the correct method to handle this case.
  4027. return undefined;
  4028. }
  4029. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  4030. if ( t < 0 || t > 1 ) {
  4031. return undefined;
  4032. }
  4033. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  4034. };
  4035. }(),
  4036. intersectsLine: function ( line ) {
  4037. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  4038. var startSign = this.distanceToPoint( line.start );
  4039. var endSign = this.distanceToPoint( line.end );
  4040. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  4041. },
  4042. intersectsBox: function ( box ) {
  4043. return box.intersectsPlane( this );
  4044. },
  4045. intersectsSphere: function ( sphere ) {
  4046. return sphere.intersectsPlane( this );
  4047. },
  4048. coplanarPoint: function ( optionalTarget ) {
  4049. var result = optionalTarget || new THREE.Vector3();
  4050. return result.copy( this.normal ).multiplyScalar( - this.constant );
  4051. },
  4052. applyMatrix4: function () {
  4053. var v1 = new THREE.Vector3();
  4054. var m1 = new THREE.Matrix3();
  4055. return function ( matrix, optionalNormalMatrix ) {
  4056. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  4057. // transform normal based on theory here:
  4058. // http://www.songho.ca/opengl/gl_normaltransform.html
  4059. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  4060. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  4061. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  4062. this.constant = - referencePoint.dot( normal );
  4063. return this;
  4064. };
  4065. }(),
  4066. translate: function ( offset ) {
  4067. this.constant = this.constant - offset.dot( this.normal );
  4068. return this;
  4069. },
  4070. equals: function ( plane ) {
  4071. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  4072. }
  4073. };
  4074. // File:src/math/Spherical.js
  4075. /**
  4076. * @author bhouston / http://clara.io
  4077. * @author WestLangley / http://github.com/WestLangley
  4078. *
  4079. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  4080. *
  4081. * The poles (phi) are at the positive and negative y axis.
  4082. * The equator starts at positive z.
  4083. */
  4084. THREE.Spherical = function ( radius, phi, theta ) {
  4085. this.radius = ( radius !== undefined ) ? radius : 1.0;
  4086. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  4087. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  4088. return this;
  4089. };
  4090. THREE.Spherical.prototype = {
  4091. constructor: THREE.Spherical,
  4092. set: function ( radius, phi, theta ) {
  4093. this.radius = radius;
  4094. this.phi = phi;
  4095. this.theta = theta;
  4096. },
  4097. clone: function () {
  4098. return new this.constructor().copy( this );
  4099. },
  4100. copy: function ( other ) {
  4101. this.radius.copy( other.radius );
  4102. this.phi.copy( other.phi );
  4103. this.theta.copy( other.theta );
  4104. return this;
  4105. },
  4106. // restrict phi to be betwee EPS and PI-EPS
  4107. makeSafe: function() {
  4108. var EPS = 0.000001;
  4109. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  4110. },
  4111. setFromVector3: function( vec3 ) {
  4112. this.radius = vec3.length();
  4113. if ( this.radius === 0 ) {
  4114. this.theta = 0;
  4115. this.phi = 0;
  4116. } else {
  4117. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  4118. this.phi = Math.acos( THREE.Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  4119. }
  4120. return this;
  4121. },
  4122. };
  4123. // File:src/math/Math.js
  4124. /**
  4125. * @author alteredq / http://alteredqualia.com/
  4126. * @author mrdoob / http://mrdoob.com/
  4127. */
  4128. THREE.Math = {
  4129. DEG2RAD: Math.PI / 180,
  4130. RAD2DEG: 180 / Math.PI,
  4131. generateUUID: function () {
  4132. // http://www.broofa.com/Tools/Math.uuid.htm
  4133. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4134. var uuid = new Array( 36 );
  4135. var rnd = 0, r;
  4136. return function () {
  4137. for ( var i = 0; i < 36; i ++ ) {
  4138. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4139. uuid[ i ] = '-';
  4140. } else if ( i === 14 ) {
  4141. uuid[ i ] = '4';
  4142. } else {
  4143. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4144. r = rnd & 0xf;
  4145. rnd = rnd >> 4;
  4146. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4147. }
  4148. }
  4149. return uuid.join( '' );
  4150. };
  4151. }(),
  4152. clamp: function ( value, min, max ) {
  4153. return Math.max( min, Math.min( max, value ) );
  4154. },
  4155. // compute euclidian modulo of m % n
  4156. // https://en.wikipedia.org/wiki/Modulo_operation
  4157. euclideanModulo: function ( n, m ) {
  4158. return ( ( n % m ) + m ) % m;
  4159. },
  4160. // Linear mapping from range <a1, a2> to range <b1, b2>
  4161. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4162. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4163. },
  4164. // http://en.wikipedia.org/wiki/Smoothstep
  4165. smoothstep: function ( x, min, max ) {
  4166. if ( x <= min ) return 0;
  4167. if ( x >= max ) return 1;
  4168. x = ( x - min ) / ( max - min );
  4169. return x * x * ( 3 - 2 * x );
  4170. },
  4171. smootherstep: function ( x, min, max ) {
  4172. if ( x <= min ) return 0;
  4173. if ( x >= max ) return 1;
  4174. x = ( x - min ) / ( max - min );
  4175. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4176. },
  4177. random16: function () {
  4178. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  4179. return Math.random();
  4180. },
  4181. // Random integer from <low, high> interval
  4182. randInt: function ( low, high ) {
  4183. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4184. },
  4185. // Random float from <low, high> interval
  4186. randFloat: function ( low, high ) {
  4187. return low + Math.random() * ( high - low );
  4188. },
  4189. // Random float from <-range/2, range/2> interval
  4190. randFloatSpread: function ( range ) {
  4191. return range * ( 0.5 - Math.random() );
  4192. },
  4193. degToRad: function ( degrees ) {
  4194. return degrees * THREE.Math.DEG2RAD;
  4195. },
  4196. radToDeg: function ( radians ) {
  4197. return radians * THREE.Math.RAD2DEG;
  4198. },
  4199. isPowerOfTwo: function ( value ) {
  4200. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4201. },
  4202. nearestPowerOfTwo: function ( value ) {
  4203. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4204. },
  4205. nextPowerOfTwo: function ( value ) {
  4206. value --;
  4207. value |= value >> 1;
  4208. value |= value >> 2;
  4209. value |= value >> 4;
  4210. value |= value >> 8;
  4211. value |= value >> 16;
  4212. value ++;
  4213. return value;
  4214. }
  4215. };
  4216. // File:src/math/Spline.js
  4217. /**
  4218. * Spline from Tween.js, slightly optimized (and trashed)
  4219. * http://sole.github.com/tween.js/examples/05_spline.html
  4220. *
  4221. * @author mrdoob / http://mrdoob.com/
  4222. * @author alteredq / http://alteredqualia.com/
  4223. */
  4224. THREE.Spline = function ( points ) {
  4225. this.points = points;
  4226. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4227. point, intPoint, weight, w2, w3,
  4228. pa, pb, pc, pd;
  4229. this.initFromArray = function ( a ) {
  4230. this.points = [];
  4231. for ( var i = 0; i < a.length; i ++ ) {
  4232. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4233. }
  4234. };
  4235. this.getPoint = function ( k ) {
  4236. point = ( this.points.length - 1 ) * k;
  4237. intPoint = Math.floor( point );
  4238. weight = point - intPoint;
  4239. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4240. c[ 1 ] = intPoint;
  4241. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4242. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4243. pa = this.points[ c[ 0 ] ];
  4244. pb = this.points[ c[ 1 ] ];
  4245. pc = this.points[ c[ 2 ] ];
  4246. pd = this.points[ c[ 3 ] ];
  4247. w2 = weight * weight;
  4248. w3 = weight * w2;
  4249. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4250. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4251. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4252. return v3;
  4253. };
  4254. this.getControlPointsArray = function () {
  4255. var i, p, l = this.points.length,
  4256. coords = [];
  4257. for ( i = 0; i < l; i ++ ) {
  4258. p = this.points[ i ];
  4259. coords[ i ] = [ p.x, p.y, p.z ];
  4260. }
  4261. return coords;
  4262. };
  4263. // approximate length by summing linear segments
  4264. this.getLength = function ( nSubDivisions ) {
  4265. var i, index, nSamples, position,
  4266. point = 0, intPoint = 0, oldIntPoint = 0,
  4267. oldPosition = new THREE.Vector3(),
  4268. tmpVec = new THREE.Vector3(),
  4269. chunkLengths = [],
  4270. totalLength = 0;
  4271. // first point has 0 length
  4272. chunkLengths[ 0 ] = 0;
  4273. if ( ! nSubDivisions ) nSubDivisions = 100;
  4274. nSamples = this.points.length * nSubDivisions;
  4275. oldPosition.copy( this.points[ 0 ] );
  4276. for ( i = 1; i < nSamples; i ++ ) {
  4277. index = i / nSamples;
  4278. position = this.getPoint( index );
  4279. tmpVec.copy( position );
  4280. totalLength += tmpVec.distanceTo( oldPosition );
  4281. oldPosition.copy( position );
  4282. point = ( this.points.length - 1 ) * index;
  4283. intPoint = Math.floor( point );
  4284. if ( intPoint !== oldIntPoint ) {
  4285. chunkLengths[ intPoint ] = totalLength;
  4286. oldIntPoint = intPoint;
  4287. }
  4288. }
  4289. // last point ends with total length
  4290. chunkLengths[ chunkLengths.length ] = totalLength;
  4291. return { chunks: chunkLengths, total: totalLength };
  4292. };
  4293. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4294. var i, j,
  4295. index, indexCurrent, indexNext,
  4296. realDistance,
  4297. sampling, position,
  4298. newpoints = [],
  4299. tmpVec = new THREE.Vector3(),
  4300. sl = this.getLength();
  4301. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4302. for ( i = 1; i < this.points.length; i ++ ) {
  4303. //tmpVec.copy( this.points[ i - 1 ] );
  4304. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4305. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4306. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4307. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4308. indexNext = i / ( this.points.length - 1 );
  4309. for ( j = 1; j < sampling - 1; j ++ ) {
  4310. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4311. position = this.getPoint( index );
  4312. newpoints.push( tmpVec.copy( position ).clone() );
  4313. }
  4314. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4315. }
  4316. this.points = newpoints;
  4317. };
  4318. // Catmull-Rom
  4319. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4320. var v0 = ( p2 - p0 ) * 0.5,
  4321. v1 = ( p3 - p1 ) * 0.5;
  4322. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4323. }
  4324. };
  4325. // File:src/math/Triangle.js
  4326. /**
  4327. * @author bhouston / http://clara.io
  4328. * @author mrdoob / http://mrdoob.com/
  4329. */
  4330. THREE.Triangle = function ( a, b, c ) {
  4331. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  4332. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  4333. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  4334. };
  4335. THREE.Triangle.normal = function () {
  4336. var v0 = new THREE.Vector3();
  4337. return function ( a, b, c, optionalTarget ) {
  4338. var result = optionalTarget || new THREE.Vector3();
  4339. result.subVectors( c, b );
  4340. v0.subVectors( a, b );
  4341. result.cross( v0 );
  4342. var resultLengthSq = result.lengthSq();
  4343. if ( resultLengthSq > 0 ) {
  4344. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  4345. }
  4346. return result.set( 0, 0, 0 );
  4347. };
  4348. }();
  4349. // static/instance method to calculate barycentric coordinates
  4350. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  4351. THREE.Triangle.barycoordFromPoint = function () {
  4352. var v0 = new THREE.Vector3();
  4353. var v1 = new THREE.Vector3();
  4354. var v2 = new THREE.Vector3();
  4355. return function ( point, a, b, c, optionalTarget ) {
  4356. v0.subVectors( c, a );
  4357. v1.subVectors( b, a );
  4358. v2.subVectors( point, a );
  4359. var dot00 = v0.dot( v0 );
  4360. var dot01 = v0.dot( v1 );
  4361. var dot02 = v0.dot( v2 );
  4362. var dot11 = v1.dot( v1 );
  4363. var dot12 = v1.dot( v2 );
  4364. var denom = ( dot00 * dot11 - dot01 * dot01 );
  4365. var result = optionalTarget || new THREE.Vector3();
  4366. // collinear or singular triangle
  4367. if ( denom === 0 ) {
  4368. // arbitrary location outside of triangle?
  4369. // not sure if this is the best idea, maybe should be returning undefined
  4370. return result.set( - 2, - 1, - 1 );
  4371. }
  4372. var invDenom = 1 / denom;
  4373. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  4374. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  4375. // barycentric coordinates must always sum to 1
  4376. return result.set( 1 - u - v, v, u );
  4377. };
  4378. }();
  4379. THREE.Triangle.containsPoint = function () {
  4380. var v1 = new THREE.Vector3();
  4381. return function ( point, a, b, c ) {
  4382. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  4383. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  4384. };
  4385. }();
  4386. THREE.Triangle.prototype = {
  4387. constructor: THREE.Triangle,
  4388. set: function ( a, b, c ) {
  4389. this.a.copy( a );
  4390. this.b.copy( b );
  4391. this.c.copy( c );
  4392. return this;
  4393. },
  4394. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  4395. this.a.copy( points[ i0 ] );
  4396. this.b.copy( points[ i1 ] );
  4397. this.c.copy( points[ i2 ] );
  4398. return this;
  4399. },
  4400. clone: function () {
  4401. return new this.constructor().copy( this );
  4402. },
  4403. copy: function ( triangle ) {
  4404. this.a.copy( triangle.a );
  4405. this.b.copy( triangle.b );
  4406. this.c.copy( triangle.c );
  4407. return this;
  4408. },
  4409. area: function () {
  4410. var v0 = new THREE.Vector3();
  4411. var v1 = new THREE.Vector3();
  4412. return function () {
  4413. v0.subVectors( this.c, this.b );
  4414. v1.subVectors( this.a, this.b );
  4415. return v0.cross( v1 ).length() * 0.5;
  4416. };
  4417. }(),
  4418. midpoint: function ( optionalTarget ) {
  4419. var result = optionalTarget || new THREE.Vector3();
  4420. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4421. },
  4422. normal: function ( optionalTarget ) {
  4423. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4424. },
  4425. plane: function ( optionalTarget ) {
  4426. var result = optionalTarget || new THREE.Plane();
  4427. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4428. },
  4429. barycoordFromPoint: function ( point, optionalTarget ) {
  4430. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4431. },
  4432. containsPoint: function ( point ) {
  4433. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4434. },
  4435. closestPointToPoint: function () {
  4436. var plane, edgeList, projectedPoint, closestPoint;
  4437. return function closestPointToPoint( point, optionalTarget ) {
  4438. if ( plane === undefined ) {
  4439. plane = new THREE.Plane();
  4440. edgeList = [ new THREE.Line3(), new THREE.Line3(), new THREE.Line3() ];
  4441. projectedPoint = new THREE.Vector3();
  4442. closestPoint = new THREE.Vector3();
  4443. }
  4444. var result = optionalTarget || new THREE.Vector3();
  4445. var minDistance = Infinity;
  4446. // project the point onto the plane of the triangle
  4447. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  4448. plane.projectPoint( point, projectedPoint );
  4449. // check if the projection lies within the triangle
  4450. if( this.containsPoint( projectedPoint ) === true ) {
  4451. // if so, this is the closest point
  4452. result.copy( projectedPoint );
  4453. } else {
  4454. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  4455. edgeList[ 0 ].set( this.a, this.b );
  4456. edgeList[ 1 ].set( this.b, this.c );
  4457. edgeList[ 2 ].set( this.c, this.a );
  4458. for( var i = 0; i < edgeList.length; i ++ ) {
  4459. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  4460. var distance = projectedPoint.distanceToSquared( closestPoint );
  4461. if( distance < minDistance ) {
  4462. minDistance = distance;
  4463. result.copy( closestPoint );
  4464. }
  4465. }
  4466. }
  4467. return result;
  4468. };
  4469. }(),
  4470. equals: function ( triangle ) {
  4471. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4472. }
  4473. };
  4474. // File:src/math/Interpolant.js
  4475. /**
  4476. * Abstract base class of interpolants over parametric samples.
  4477. *
  4478. * The parameter domain is one dimensional, typically the time or a path
  4479. * along a curve defined by the data.
  4480. *
  4481. * The sample values can have any dimensionality and derived classes may
  4482. * apply special interpretations to the data.
  4483. *
  4484. * This class provides the interval seek in a Template Method, deferring
  4485. * the actual interpolation to derived classes.
  4486. *
  4487. * Time complexity is O(1) for linear access crossing at most two points
  4488. * and O(log N) for random access, where N is the number of positions.
  4489. *
  4490. * References:
  4491. *
  4492. * http://www.oodesign.com/template-method-pattern.html
  4493. *
  4494. * @author tschw
  4495. */
  4496. THREE.Interpolant = function(
  4497. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4498. this.parameterPositions = parameterPositions;
  4499. this._cachedIndex = 0;
  4500. this.resultBuffer = resultBuffer !== undefined ?
  4501. resultBuffer : new sampleValues.constructor( sampleSize );
  4502. this.sampleValues = sampleValues;
  4503. this.valueSize = sampleSize;
  4504. };
  4505. THREE.Interpolant.prototype = {
  4506. constructor: THREE.Interpolant,
  4507. evaluate: function( t ) {
  4508. var pp = this.parameterPositions,
  4509. i1 = this._cachedIndex,
  4510. t1 = pp[ i1 ],
  4511. t0 = pp[ i1 - 1 ];
  4512. validate_interval: {
  4513. seek: {
  4514. var right;
  4515. linear_scan: {
  4516. //- See http://jsperf.com/comparison-to-undefined/3
  4517. //- slower code:
  4518. //-
  4519. //- if ( t >= t1 || t1 === undefined ) {
  4520. forward_scan: if ( ! ( t < t1 ) ) {
  4521. for ( var giveUpAt = i1 + 2; ;) {
  4522. if ( t1 === undefined ) {
  4523. if ( t < t0 ) break forward_scan;
  4524. // after end
  4525. i1 = pp.length;
  4526. this._cachedIndex = i1;
  4527. return this.afterEnd_( i1 - 1, t, t0 );
  4528. }
  4529. if ( i1 === giveUpAt ) break; // this loop
  4530. t0 = t1;
  4531. t1 = pp[ ++ i1 ];
  4532. if ( t < t1 ) {
  4533. // we have arrived at the sought interval
  4534. break seek;
  4535. }
  4536. }
  4537. // prepare binary search on the right side of the index
  4538. right = pp.length;
  4539. break linear_scan;
  4540. }
  4541. //- slower code:
  4542. //- if ( t < t0 || t0 === undefined ) {
  4543. if ( ! ( t >= t0 ) ) {
  4544. // looping?
  4545. var t1global = pp[ 1 ];
  4546. if ( t < t1global ) {
  4547. i1 = 2; // + 1, using the scan for the details
  4548. t0 = t1global;
  4549. }
  4550. // linear reverse scan
  4551. for ( var giveUpAt = i1 - 2; ;) {
  4552. if ( t0 === undefined ) {
  4553. // before start
  4554. this._cachedIndex = 0;
  4555. return this.beforeStart_( 0, t, t1 );
  4556. }
  4557. if ( i1 === giveUpAt ) break; // this loop
  4558. t1 = t0;
  4559. t0 = pp[ -- i1 - 1 ];
  4560. if ( t >= t0 ) {
  4561. // we have arrived at the sought interval
  4562. break seek;
  4563. }
  4564. }
  4565. // prepare binary search on the left side of the index
  4566. right = i1;
  4567. i1 = 0;
  4568. break linear_scan;
  4569. }
  4570. // the interval is valid
  4571. break validate_interval;
  4572. } // linear scan
  4573. // binary search
  4574. while ( i1 < right ) {
  4575. var mid = ( i1 + right ) >>> 1;
  4576. if ( t < pp[ mid ] ) {
  4577. right = mid;
  4578. } else {
  4579. i1 = mid + 1;
  4580. }
  4581. }
  4582. t1 = pp[ i1 ];
  4583. t0 = pp[ i1 - 1 ];
  4584. // check boundary cases, again
  4585. if ( t0 === undefined ) {
  4586. this._cachedIndex = 0;
  4587. return this.beforeStart_( 0, t, t1 );
  4588. }
  4589. if ( t1 === undefined ) {
  4590. i1 = pp.length;
  4591. this._cachedIndex = i1;
  4592. return this.afterEnd_( i1 - 1, t0, t );
  4593. }
  4594. } // seek
  4595. this._cachedIndex = i1;
  4596. this.intervalChanged_( i1, t0, t1 );
  4597. } // validate_interval
  4598. return this.interpolate_( i1, t0, t, t1 );
  4599. },
  4600. settings: null, // optional, subclass-specific settings structure
  4601. // Note: The indirection allows central control of many interpolants.
  4602. // --- Protected interface
  4603. DefaultSettings_: {},
  4604. getSettings_: function() {
  4605. return this.settings || this.DefaultSettings_;
  4606. },
  4607. copySampleValue_: function( index ) {
  4608. // copies a sample value to the result buffer
  4609. var result = this.resultBuffer,
  4610. values = this.sampleValues,
  4611. stride = this.valueSize,
  4612. offset = index * stride;
  4613. for ( var i = 0; i !== stride; ++ i ) {
  4614. result[ i ] = values[ offset + i ];
  4615. }
  4616. return result;
  4617. },
  4618. // Template methods for derived classes:
  4619. interpolate_: function( i1, t0, t, t1 ) {
  4620. throw new Error( "call to abstract method" );
  4621. // implementations shall return this.resultBuffer
  4622. },
  4623. intervalChanged_: function( i1, t0, t1 ) {
  4624. // empty
  4625. }
  4626. };
  4627. Object.assign( THREE.Interpolant.prototype, {
  4628. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  4629. THREE.Interpolant.prototype.copySampleValue_,
  4630. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  4631. THREE.Interpolant.prototype.copySampleValue_
  4632. } );
  4633. // File:src/math/interpolants/CubicInterpolant.js
  4634. /**
  4635. * Fast and simple cubic spline interpolant.
  4636. *
  4637. * It was derived from a Hermitian construction setting the first derivative
  4638. * at each sample position to the linear slope between neighboring positions
  4639. * over their parameter interval.
  4640. *
  4641. * @author tschw
  4642. */
  4643. THREE.CubicInterpolant = function(
  4644. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4645. THREE.Interpolant.call(
  4646. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4647. this._weightPrev = -0;
  4648. this._offsetPrev = -0;
  4649. this._weightNext = -0;
  4650. this._offsetNext = -0;
  4651. };
  4652. THREE.CubicInterpolant.prototype =
  4653. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4654. constructor: THREE.CubicInterpolant,
  4655. DefaultSettings_: {
  4656. endingStart: THREE.ZeroCurvatureEnding,
  4657. endingEnd: THREE.ZeroCurvatureEnding
  4658. },
  4659. intervalChanged_: function( i1, t0, t1 ) {
  4660. var pp = this.parameterPositions,
  4661. iPrev = i1 - 2,
  4662. iNext = i1 + 1,
  4663. tPrev = pp[ iPrev ],
  4664. tNext = pp[ iNext ];
  4665. if ( tPrev === undefined ) {
  4666. switch ( this.getSettings_().endingStart ) {
  4667. case THREE.ZeroSlopeEnding:
  4668. // f'(t0) = 0
  4669. iPrev = i1;
  4670. tPrev = 2 * t0 - t1;
  4671. break;
  4672. case THREE.WrapAroundEnding:
  4673. // use the other end of the curve
  4674. iPrev = pp.length - 2;
  4675. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  4676. break;
  4677. default: // ZeroCurvatureEnding
  4678. // f''(t0) = 0 a.k.a. Natural Spline
  4679. iPrev = i1;
  4680. tPrev = t1;
  4681. }
  4682. }
  4683. if ( tNext === undefined ) {
  4684. switch ( this.getSettings_().endingEnd ) {
  4685. case THREE.ZeroSlopeEnding:
  4686. // f'(tN) = 0
  4687. iNext = i1;
  4688. tNext = 2 * t1 - t0;
  4689. break;
  4690. case THREE.WrapAroundEnding:
  4691. // use the other end of the curve
  4692. iNext = 1;
  4693. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  4694. break;
  4695. default: // ZeroCurvatureEnding
  4696. // f''(tN) = 0, a.k.a. Natural Spline
  4697. iNext = i1 - 1;
  4698. tNext = t0;
  4699. }
  4700. }
  4701. var halfDt = ( t1 - t0 ) * 0.5,
  4702. stride = this.valueSize;
  4703. this._weightPrev = halfDt / ( t0 - tPrev );
  4704. this._weightNext = halfDt / ( tNext - t1 );
  4705. this._offsetPrev = iPrev * stride;
  4706. this._offsetNext = iNext * stride;
  4707. },
  4708. interpolate_: function( i1, t0, t, t1 ) {
  4709. var result = this.resultBuffer,
  4710. values = this.sampleValues,
  4711. stride = this.valueSize,
  4712. o1 = i1 * stride, o0 = o1 - stride,
  4713. oP = this._offsetPrev, oN = this._offsetNext,
  4714. wP = this._weightPrev, wN = this._weightNext,
  4715. p = ( t - t0 ) / ( t1 - t0 ),
  4716. pp = p * p,
  4717. ppp = pp * p;
  4718. // evaluate polynomials
  4719. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  4720. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  4721. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  4722. var sN = wN * ppp - wN * pp;
  4723. // combine data linearly
  4724. for ( var i = 0; i !== stride; ++ i ) {
  4725. result[ i ] =
  4726. sP * values[ oP + i ] +
  4727. s0 * values[ o0 + i ] +
  4728. s1 * values[ o1 + i ] +
  4729. sN * values[ oN + i ];
  4730. }
  4731. return result;
  4732. }
  4733. } );
  4734. // File:src/math/interpolants/DiscreteInterpolant.js
  4735. /**
  4736. *
  4737. * Interpolant that evaluates to the sample value at the position preceeding
  4738. * the parameter.
  4739. *
  4740. * @author tschw
  4741. */
  4742. THREE.DiscreteInterpolant = function(
  4743. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4744. THREE.Interpolant.call(
  4745. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4746. };
  4747. THREE.DiscreteInterpolant.prototype =
  4748. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4749. constructor: THREE.DiscreteInterpolant,
  4750. interpolate_: function( i1, t0, t, t1 ) {
  4751. return this.copySampleValue_( i1 - 1 );
  4752. }
  4753. } );
  4754. // File:src/math/interpolants/LinearInterpolant.js
  4755. /**
  4756. * @author tschw
  4757. */
  4758. THREE.LinearInterpolant = function(
  4759. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4760. THREE.Interpolant.call(
  4761. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4762. };
  4763. THREE.LinearInterpolant.prototype =
  4764. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4765. constructor: THREE.LinearInterpolant,
  4766. interpolate_: function( i1, t0, t, t1 ) {
  4767. var result = this.resultBuffer,
  4768. values = this.sampleValues,
  4769. stride = this.valueSize,
  4770. offset1 = i1 * stride,
  4771. offset0 = offset1 - stride,
  4772. weight1 = ( t - t0 ) / ( t1 - t0 ),
  4773. weight0 = 1 - weight1;
  4774. for ( var i = 0; i !== stride; ++ i ) {
  4775. result[ i ] =
  4776. values[ offset0 + i ] * weight0 +
  4777. values[ offset1 + i ] * weight1;
  4778. }
  4779. return result;
  4780. }
  4781. } );
  4782. // File:src/math/interpolants/QuaternionLinearInterpolant.js
  4783. /**
  4784. * Spherical linear unit quaternion interpolant.
  4785. *
  4786. * @author tschw
  4787. */
  4788. THREE.QuaternionLinearInterpolant = function(
  4789. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  4790. THREE.Interpolant.call(
  4791. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  4792. };
  4793. THREE.QuaternionLinearInterpolant.prototype =
  4794. Object.assign( Object.create( THREE.Interpolant.prototype ), {
  4795. constructor: THREE.QuaternionLinearInterpolant,
  4796. interpolate_: function( i1, t0, t, t1 ) {
  4797. var result = this.resultBuffer,
  4798. values = this.sampleValues,
  4799. stride = this.valueSize,
  4800. offset = i1 * stride,
  4801. alpha = ( t - t0 ) / ( t1 - t0 );
  4802. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  4803. THREE.Quaternion.slerpFlat( result, 0,
  4804. values, offset - stride, values, offset, alpha );
  4805. }
  4806. return result;
  4807. }
  4808. } );
  4809. // File:src/core/Clock.js
  4810. /**
  4811. * @author alteredq / http://alteredqualia.com/
  4812. */
  4813. THREE.Clock = function ( autoStart ) {
  4814. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4815. this.startTime = 0;
  4816. this.oldTime = 0;
  4817. this.elapsedTime = 0;
  4818. this.running = false;
  4819. };
  4820. THREE.Clock.prototype = {
  4821. constructor: THREE.Clock,
  4822. start: function () {
  4823. this.startTime = ( performance || Date ).now();
  4824. this.oldTime = this.startTime;
  4825. this.running = true;
  4826. },
  4827. stop: function () {
  4828. this.getElapsedTime();
  4829. this.running = false;
  4830. },
  4831. getElapsedTime: function () {
  4832. this.getDelta();
  4833. return this.elapsedTime;
  4834. },
  4835. getDelta: function () {
  4836. var diff = 0;
  4837. if ( this.autoStart && ! this.running ) {
  4838. this.start();
  4839. }
  4840. if ( this.running ) {
  4841. var newTime = ( performance || Date ).now();
  4842. diff = ( newTime - this.oldTime ) / 1000;
  4843. this.oldTime = newTime;
  4844. this.elapsedTime += diff;
  4845. }
  4846. return diff;
  4847. }
  4848. };
  4849. // File:src/core/EventDispatcher.js
  4850. /**
  4851. * https://github.com/mrdoob/eventdispatcher.js/
  4852. */
  4853. THREE.EventDispatcher = function () {};
  4854. THREE.EventDispatcher.prototype = {
  4855. constructor: THREE.EventDispatcher,
  4856. apply: function ( object ) {
  4857. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4858. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4859. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4860. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4861. },
  4862. addEventListener: function ( type, listener ) {
  4863. if ( this._listeners === undefined ) this._listeners = {};
  4864. var listeners = this._listeners;
  4865. if ( listeners[ type ] === undefined ) {
  4866. listeners[ type ] = [];
  4867. }
  4868. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4869. listeners[ type ].push( listener );
  4870. }
  4871. },
  4872. hasEventListener: function ( type, listener ) {
  4873. if ( this._listeners === undefined ) return false;
  4874. var listeners = this._listeners;
  4875. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4876. return true;
  4877. }
  4878. return false;
  4879. },
  4880. removeEventListener: function ( type, listener ) {
  4881. if ( this._listeners === undefined ) return;
  4882. var listeners = this._listeners;
  4883. var listenerArray = listeners[ type ];
  4884. if ( listenerArray !== undefined ) {
  4885. var index = listenerArray.indexOf( listener );
  4886. if ( index !== - 1 ) {
  4887. listenerArray.splice( index, 1 );
  4888. }
  4889. }
  4890. },
  4891. dispatchEvent: function ( event ) {
  4892. if ( this._listeners === undefined ) return;
  4893. var listeners = this._listeners;
  4894. var listenerArray = listeners[ event.type ];
  4895. if ( listenerArray !== undefined ) {
  4896. event.target = this;
  4897. var array = [];
  4898. var length = listenerArray.length;
  4899. for ( var i = 0; i < length; i ++ ) {
  4900. array[ i ] = listenerArray[ i ];
  4901. }
  4902. for ( var i = 0; i < length; i ++ ) {
  4903. array[ i ].call( this, event );
  4904. }
  4905. }
  4906. }
  4907. };
  4908. // File:src/core/Layers.js
  4909. /**
  4910. * @author mrdoob / http://mrdoob.com/
  4911. */
  4912. THREE.Layers = function () {
  4913. this.mask = 1;
  4914. };
  4915. THREE.Layers.prototype = {
  4916. constructor: THREE.Layers,
  4917. set: function ( channel ) {
  4918. this.mask = 1 << channel;
  4919. },
  4920. enable: function ( channel ) {
  4921. this.mask |= 1 << channel;
  4922. },
  4923. toggle: function ( channel ) {
  4924. this.mask ^= 1 << channel;
  4925. },
  4926. disable: function ( channel ) {
  4927. this.mask &= ~ ( 1 << channel );
  4928. },
  4929. test: function ( layers ) {
  4930. return ( this.mask & layers.mask ) !== 0;
  4931. }
  4932. };
  4933. // File:src/core/Raycaster.js
  4934. /**
  4935. * @author mrdoob / http://mrdoob.com/
  4936. * @author bhouston / http://clara.io/
  4937. * @author stephomi / http://stephaneginier.com/
  4938. */
  4939. ( function ( THREE ) {
  4940. THREE.Raycaster = function ( origin, direction, near, far ) {
  4941. this.ray = new THREE.Ray( origin, direction );
  4942. // direction is assumed to be normalized (for accurate distance calculations)
  4943. this.near = near || 0;
  4944. this.far = far || Infinity;
  4945. this.params = {
  4946. Mesh: {},
  4947. Line: {},
  4948. LOD: {},
  4949. Points: { threshold: 1 },
  4950. Sprite: {}
  4951. };
  4952. Object.defineProperties( this.params, {
  4953. PointCloud: {
  4954. get: function () {
  4955. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  4956. return this.Points;
  4957. }
  4958. }
  4959. } );
  4960. };
  4961. function ascSort( a, b ) {
  4962. return a.distance - b.distance;
  4963. }
  4964. function intersectObject( object, raycaster, intersects, recursive ) {
  4965. if ( object.visible === false ) return;
  4966. object.raycast( raycaster, intersects );
  4967. if ( recursive === true ) {
  4968. var children = object.children;
  4969. for ( var i = 0, l = children.length; i < l; i ++ ) {
  4970. intersectObject( children[ i ], raycaster, intersects, true );
  4971. }
  4972. }
  4973. }
  4974. //
  4975. THREE.Raycaster.prototype = {
  4976. constructor: THREE.Raycaster,
  4977. linePrecision: 1,
  4978. set: function ( origin, direction ) {
  4979. // direction is assumed to be normalized (for accurate distance calculations)
  4980. this.ray.set( origin, direction );
  4981. },
  4982. setFromCamera: function ( coords, camera ) {
  4983. if ( camera instanceof THREE.PerspectiveCamera ) {
  4984. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  4985. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  4986. } else if ( camera instanceof THREE.OrthographicCamera ) {
  4987. this.ray.origin.set( coords.x, coords.y, - 1 ).unproject( camera );
  4988. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  4989. } else {
  4990. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  4991. }
  4992. },
  4993. intersectObject: function ( object, recursive ) {
  4994. var intersects = [];
  4995. intersectObject( object, this, intersects, recursive );
  4996. intersects.sort( ascSort );
  4997. return intersects;
  4998. },
  4999. intersectObjects: function ( objects, recursive ) {
  5000. var intersects = [];
  5001. if ( Array.isArray( objects ) === false ) {
  5002. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  5003. return intersects;
  5004. }
  5005. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  5006. intersectObject( objects[ i ], this, intersects, recursive );
  5007. }
  5008. intersects.sort( ascSort );
  5009. return intersects;
  5010. }
  5011. };
  5012. }( THREE ) );
  5013. // File:src/core/Object3D.js
  5014. /**
  5015. * @author mrdoob / http://mrdoob.com/
  5016. * @author mikael emtinger / http://gomo.se/
  5017. * @author alteredq / http://alteredqualia.com/
  5018. * @author WestLangley / http://github.com/WestLangley
  5019. * @author elephantatwork / www.elephantatwork.ch
  5020. */
  5021. THREE.Object3D = function () {
  5022. Object.defineProperty( this, 'id', { value: THREE.Object3DIdCount ++ } );
  5023. this.uuid = THREE.Math.generateUUID();
  5024. this.name = '';
  5025. this.type = 'Object3D';
  5026. this.parent = null;
  5027. this.children = [];
  5028. this.up = THREE.Object3D.DefaultUp.clone();
  5029. var position = new THREE.Vector3();
  5030. var rotation = new THREE.Euler();
  5031. var quaternion = new THREE.Quaternion();
  5032. var scale = new THREE.Vector3( 1, 1, 1 );
  5033. function onRotationChange() {
  5034. quaternion.setFromEuler( rotation, false );
  5035. }
  5036. function onQuaternionChange() {
  5037. rotation.setFromQuaternion( quaternion, undefined, false );
  5038. }
  5039. rotation.onChange( onRotationChange );
  5040. quaternion.onChange( onQuaternionChange );
  5041. Object.defineProperties( this, {
  5042. position: {
  5043. enumerable: true,
  5044. value: position
  5045. },
  5046. rotation: {
  5047. enumerable: true,
  5048. value: rotation
  5049. },
  5050. quaternion: {
  5051. enumerable: true,
  5052. value: quaternion
  5053. },
  5054. scale: {
  5055. enumerable: true,
  5056. value: scale
  5057. },
  5058. modelViewMatrix: {
  5059. value: new THREE.Matrix4()
  5060. },
  5061. normalMatrix: {
  5062. value: new THREE.Matrix3()
  5063. }
  5064. } );
  5065. this.rotationAutoUpdate = true;
  5066. this.matrix = new THREE.Matrix4();
  5067. this.matrixWorld = new THREE.Matrix4();
  5068. this.matrixAutoUpdate = THREE.Object3D.DefaultMatrixAutoUpdate;
  5069. this.matrixWorldNeedsUpdate = false;
  5070. this.layers = new THREE.Layers();
  5071. this.visible = true;
  5072. this.castShadow = false;
  5073. this.receiveShadow = false;
  5074. this.frustumCulled = true;
  5075. this.renderOrder = 0;
  5076. this.userData = {};
  5077. };
  5078. THREE.Object3D.DefaultUp = new THREE.Vector3( 0, 1, 0 );
  5079. THREE.Object3D.DefaultMatrixAutoUpdate = true;
  5080. THREE.Object3D.prototype = {
  5081. constructor: THREE.Object3D,
  5082. applyMatrix: function ( matrix ) {
  5083. this.matrix.multiplyMatrices( matrix, this.matrix );
  5084. this.matrix.decompose( this.position, this.quaternion, this.scale );
  5085. },
  5086. setRotationFromAxisAngle: function ( axis, angle ) {
  5087. // assumes axis is normalized
  5088. this.quaternion.setFromAxisAngle( axis, angle );
  5089. },
  5090. setRotationFromEuler: function ( euler ) {
  5091. this.quaternion.setFromEuler( euler, true );
  5092. },
  5093. setRotationFromMatrix: function ( m ) {
  5094. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5095. this.quaternion.setFromRotationMatrix( m );
  5096. },
  5097. setRotationFromQuaternion: function ( q ) {
  5098. // assumes q is normalized
  5099. this.quaternion.copy( q );
  5100. },
  5101. rotateOnAxis: function () {
  5102. // rotate object on axis in object space
  5103. // axis is assumed to be normalized
  5104. var q1 = new THREE.Quaternion();
  5105. return function ( axis, angle ) {
  5106. q1.setFromAxisAngle( axis, angle );
  5107. this.quaternion.multiply( q1 );
  5108. return this;
  5109. };
  5110. }(),
  5111. rotateX: function () {
  5112. var v1 = new THREE.Vector3( 1, 0, 0 );
  5113. return function ( angle ) {
  5114. return this.rotateOnAxis( v1, angle );
  5115. };
  5116. }(),
  5117. rotateY: function () {
  5118. var v1 = new THREE.Vector3( 0, 1, 0 );
  5119. return function ( angle ) {
  5120. return this.rotateOnAxis( v1, angle );
  5121. };
  5122. }(),
  5123. rotateZ: function () {
  5124. var v1 = new THREE.Vector3( 0, 0, 1 );
  5125. return function ( angle ) {
  5126. return this.rotateOnAxis( v1, angle );
  5127. };
  5128. }(),
  5129. translateOnAxis: function () {
  5130. // translate object by distance along axis in object space
  5131. // axis is assumed to be normalized
  5132. var v1 = new THREE.Vector3();
  5133. return function ( axis, distance ) {
  5134. v1.copy( axis ).applyQuaternion( this.quaternion );
  5135. this.position.add( v1.multiplyScalar( distance ) );
  5136. return this;
  5137. };
  5138. }(),
  5139. translateX: function () {
  5140. var v1 = new THREE.Vector3( 1, 0, 0 );
  5141. return function ( distance ) {
  5142. return this.translateOnAxis( v1, distance );
  5143. };
  5144. }(),
  5145. translateY: function () {
  5146. var v1 = new THREE.Vector3( 0, 1, 0 );
  5147. return function ( distance ) {
  5148. return this.translateOnAxis( v1, distance );
  5149. };
  5150. }(),
  5151. translateZ: function () {
  5152. var v1 = new THREE.Vector3( 0, 0, 1 );
  5153. return function ( distance ) {
  5154. return this.translateOnAxis( v1, distance );
  5155. };
  5156. }(),
  5157. localToWorld: function ( vector ) {
  5158. return vector.applyMatrix4( this.matrixWorld );
  5159. },
  5160. worldToLocal: function () {
  5161. var m1 = new THREE.Matrix4();
  5162. return function ( vector ) {
  5163. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  5164. };
  5165. }(),
  5166. lookAt: function () {
  5167. // This routine does not support objects with rotated and/or translated parent(s)
  5168. var m1 = new THREE.Matrix4();
  5169. return function ( vector ) {
  5170. m1.lookAt( vector, this.position, this.up );
  5171. this.quaternion.setFromRotationMatrix( m1 );
  5172. };
  5173. }(),
  5174. add: function ( object ) {
  5175. if ( arguments.length > 1 ) {
  5176. for ( var i = 0; i < arguments.length; i ++ ) {
  5177. this.add( arguments[ i ] );
  5178. }
  5179. return this;
  5180. }
  5181. if ( object === this ) {
  5182. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  5183. return this;
  5184. }
  5185. if ( object instanceof THREE.Object3D ) {
  5186. if ( object.parent !== null ) {
  5187. object.parent.remove( object );
  5188. }
  5189. object.parent = this;
  5190. object.dispatchEvent( { type: 'added' } );
  5191. this.children.push( object );
  5192. } else {
  5193. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  5194. }
  5195. return this;
  5196. },
  5197. remove: function ( object ) {
  5198. if ( arguments.length > 1 ) {
  5199. for ( var i = 0; i < arguments.length; i ++ ) {
  5200. this.remove( arguments[ i ] );
  5201. }
  5202. }
  5203. var index = this.children.indexOf( object );
  5204. if ( index !== - 1 ) {
  5205. object.parent = null;
  5206. object.dispatchEvent( { type: 'removed' } );
  5207. this.children.splice( index, 1 );
  5208. }
  5209. },
  5210. getObjectById: function ( id ) {
  5211. return this.getObjectByProperty( 'id', id );
  5212. },
  5213. getObjectByName: function ( name ) {
  5214. return this.getObjectByProperty( 'name', name );
  5215. },
  5216. getObjectByProperty: function ( name, value ) {
  5217. if ( this[ name ] === value ) return this;
  5218. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5219. var child = this.children[ i ];
  5220. var object = child.getObjectByProperty( name, value );
  5221. if ( object !== undefined ) {
  5222. return object;
  5223. }
  5224. }
  5225. return undefined;
  5226. },
  5227. getWorldPosition: function ( optionalTarget ) {
  5228. var result = optionalTarget || new THREE.Vector3();
  5229. this.updateMatrixWorld( true );
  5230. return result.setFromMatrixPosition( this.matrixWorld );
  5231. },
  5232. getWorldQuaternion: function () {
  5233. var position = new THREE.Vector3();
  5234. var scale = new THREE.Vector3();
  5235. return function ( optionalTarget ) {
  5236. var result = optionalTarget || new THREE.Quaternion();
  5237. this.updateMatrixWorld( true );
  5238. this.matrixWorld.decompose( position, result, scale );
  5239. return result;
  5240. };
  5241. }(),
  5242. getWorldRotation: function () {
  5243. var quaternion = new THREE.Quaternion();
  5244. return function ( optionalTarget ) {
  5245. var result = optionalTarget || new THREE.Euler();
  5246. this.getWorldQuaternion( quaternion );
  5247. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  5248. };
  5249. }(),
  5250. getWorldScale: function () {
  5251. var position = new THREE.Vector3();
  5252. var quaternion = new THREE.Quaternion();
  5253. return function ( optionalTarget ) {
  5254. var result = optionalTarget || new THREE.Vector3();
  5255. this.updateMatrixWorld( true );
  5256. this.matrixWorld.decompose( position, quaternion, result );
  5257. return result;
  5258. };
  5259. }(),
  5260. getWorldDirection: function () {
  5261. var quaternion = new THREE.Quaternion();
  5262. return function ( optionalTarget ) {
  5263. var result = optionalTarget || new THREE.Vector3();
  5264. this.getWorldQuaternion( quaternion );
  5265. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  5266. };
  5267. }(),
  5268. raycast: function () {},
  5269. traverse: function ( callback ) {
  5270. callback( this );
  5271. var children = this.children;
  5272. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5273. children[ i ].traverse( callback );
  5274. }
  5275. },
  5276. traverseVisible: function ( callback ) {
  5277. if ( this.visible === false ) return;
  5278. callback( this );
  5279. var children = this.children;
  5280. for ( var i = 0, l = children.length; i < l; i ++ ) {
  5281. children[ i ].traverseVisible( callback );
  5282. }
  5283. },
  5284. traverseAncestors: function ( callback ) {
  5285. var parent = this.parent;
  5286. if ( parent !== null ) {
  5287. callback( parent );
  5288. parent.traverseAncestors( callback );
  5289. }
  5290. },
  5291. updateMatrix: function () {
  5292. this.matrix.compose( this.position, this.quaternion, this.scale );
  5293. this.matrixWorldNeedsUpdate = true;
  5294. },
  5295. updateMatrixWorld: function ( force ) {
  5296. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  5297. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  5298. if ( this.parent === null ) {
  5299. this.matrixWorld.copy( this.matrix );
  5300. } else {
  5301. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  5302. }
  5303. this.matrixWorldNeedsUpdate = false;
  5304. force = true;
  5305. }
  5306. // update children
  5307. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  5308. this.children[ i ].updateMatrixWorld( force );
  5309. }
  5310. },
  5311. toJSON: function ( meta ) {
  5312. // meta is '' when called from JSON.stringify
  5313. var isRootObject = ( meta === undefined || meta === '' );
  5314. var output = {};
  5315. // meta is a hash used to collect geometries, materials.
  5316. // not providing it implies that this is the root object
  5317. // being serialized.
  5318. if ( isRootObject ) {
  5319. // initialize meta obj
  5320. meta = {
  5321. geometries: {},
  5322. materials: {},
  5323. textures: {},
  5324. images: {}
  5325. };
  5326. output.metadata = {
  5327. version: 4.4,
  5328. type: 'Object',
  5329. generator: 'Object3D.toJSON'
  5330. };
  5331. }
  5332. // standard Object3D serialization
  5333. var object = {};
  5334. object.uuid = this.uuid;
  5335. object.type = this.type;
  5336. if ( this.name !== '' ) object.name = this.name;
  5337. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  5338. if ( this.castShadow === true ) object.castShadow = true;
  5339. if ( this.receiveShadow === true ) object.receiveShadow = true;
  5340. if ( this.visible === false ) object.visible = false;
  5341. object.matrix = this.matrix.toArray();
  5342. //
  5343. if ( this.geometry !== undefined ) {
  5344. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  5345. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  5346. }
  5347. object.geometry = this.geometry.uuid;
  5348. }
  5349. if ( this.material !== undefined ) {
  5350. if ( meta.materials[ this.material.uuid ] === undefined ) {
  5351. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  5352. }
  5353. object.material = this.material.uuid;
  5354. }
  5355. //
  5356. if ( this.children.length > 0 ) {
  5357. object.children = [];
  5358. for ( var i = 0; i < this.children.length; i ++ ) {
  5359. object.children.push( this.children[ i ].toJSON( meta ).object );
  5360. }
  5361. }
  5362. if ( isRootObject ) {
  5363. var geometries = extractFromCache( meta.geometries );
  5364. var materials = extractFromCache( meta.materials );
  5365. var textures = extractFromCache( meta.textures );
  5366. var images = extractFromCache( meta.images );
  5367. if ( geometries.length > 0 ) output.geometries = geometries;
  5368. if ( materials.length > 0 ) output.materials = materials;
  5369. if ( textures.length > 0 ) output.textures = textures;
  5370. if ( images.length > 0 ) output.images = images;
  5371. }
  5372. output.object = object;
  5373. return output;
  5374. // extract data from the cache hash
  5375. // remove metadata on each item
  5376. // and return as array
  5377. function extractFromCache ( cache ) {
  5378. var values = [];
  5379. for ( var key in cache ) {
  5380. var data = cache[ key ];
  5381. delete data.metadata;
  5382. values.push( data );
  5383. }
  5384. return values;
  5385. }
  5386. },
  5387. clone: function ( recursive ) {
  5388. return new this.constructor().copy( this, recursive );
  5389. },
  5390. copy: function ( source, recursive ) {
  5391. if ( recursive === undefined ) recursive = true;
  5392. this.name = source.name;
  5393. this.up.copy( source.up );
  5394. this.position.copy( source.position );
  5395. this.quaternion.copy( source.quaternion );
  5396. this.scale.copy( source.scale );
  5397. this.rotationAutoUpdate = source.rotationAutoUpdate;
  5398. this.matrix.copy( source.matrix );
  5399. this.matrixWorld.copy( source.matrixWorld );
  5400. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5401. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  5402. this.visible = source.visible;
  5403. this.castShadow = source.castShadow;
  5404. this.receiveShadow = source.receiveShadow;
  5405. this.frustumCulled = source.frustumCulled;
  5406. this.renderOrder = source.renderOrder;
  5407. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5408. if ( recursive === true ) {
  5409. for ( var i = 0; i < source.children.length; i ++ ) {
  5410. var child = source.children[ i ];
  5411. this.add( child.clone() );
  5412. }
  5413. }
  5414. return this;
  5415. }
  5416. };
  5417. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  5418. THREE.Object3DIdCount = 0;
  5419. // File:src/core/Face3.js
  5420. /**
  5421. * @author mrdoob / http://mrdoob.com/
  5422. * @author alteredq / http://alteredqualia.com/
  5423. */
  5424. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5425. this.a = a;
  5426. this.b = b;
  5427. this.c = c;
  5428. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5429. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  5430. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5431. this.vertexColors = Array.isArray( color ) ? color : [];
  5432. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5433. };
  5434. THREE.Face3.prototype = {
  5435. constructor: THREE.Face3,
  5436. clone: function () {
  5437. return new this.constructor().copy( this );
  5438. },
  5439. copy: function ( source ) {
  5440. this.a = source.a;
  5441. this.b = source.b;
  5442. this.c = source.c;
  5443. this.normal.copy( source.normal );
  5444. this.color.copy( source.color );
  5445. this.materialIndex = source.materialIndex;
  5446. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  5447. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  5448. }
  5449. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  5450. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  5451. }
  5452. return this;
  5453. }
  5454. };
  5455. // File:src/core/BufferAttribute.js
  5456. /**
  5457. * @author mrdoob / http://mrdoob.com/
  5458. */
  5459. THREE.BufferAttribute = function ( array, itemSize, normalized ) {
  5460. this.uuid = THREE.Math.generateUUID();
  5461. this.array = array;
  5462. this.itemSize = itemSize;
  5463. this.dynamic = false;
  5464. this.updateRange = { offset: 0, count: - 1 };
  5465. this.version = 0;
  5466. this.normalized = normalized === true;
  5467. };
  5468. THREE.BufferAttribute.prototype = {
  5469. constructor: THREE.BufferAttribute,
  5470. get count() {
  5471. return this.array.length / this.itemSize;
  5472. },
  5473. set needsUpdate( value ) {
  5474. if ( value === true ) this.version ++;
  5475. },
  5476. setDynamic: function ( value ) {
  5477. this.dynamic = value;
  5478. return this;
  5479. },
  5480. copy: function ( source ) {
  5481. this.array = new source.array.constructor( source.array );
  5482. this.itemSize = source.itemSize;
  5483. this.dynamic = source.dynamic;
  5484. return this;
  5485. },
  5486. copyAt: function ( index1, attribute, index2 ) {
  5487. index1 *= this.itemSize;
  5488. index2 *= attribute.itemSize;
  5489. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  5490. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5491. }
  5492. return this;
  5493. },
  5494. copyArray: function ( array ) {
  5495. this.array.set( array );
  5496. return this;
  5497. },
  5498. copyColorsArray: function ( colors ) {
  5499. var array = this.array, offset = 0;
  5500. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  5501. var color = colors[ i ];
  5502. if ( color === undefined ) {
  5503. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  5504. color = new THREE.Color();
  5505. }
  5506. array[ offset ++ ] = color.r;
  5507. array[ offset ++ ] = color.g;
  5508. array[ offset ++ ] = color.b;
  5509. }
  5510. return this;
  5511. },
  5512. copyIndicesArray: function ( indices ) {
  5513. var array = this.array, offset = 0;
  5514. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  5515. var index = indices[ i ];
  5516. array[ offset ++ ] = index.a;
  5517. array[ offset ++ ] = index.b;
  5518. array[ offset ++ ] = index.c;
  5519. }
  5520. return this;
  5521. },
  5522. copyVector2sArray: function ( vectors ) {
  5523. var array = this.array, offset = 0;
  5524. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5525. var vector = vectors[ i ];
  5526. if ( vector === undefined ) {
  5527. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  5528. vector = new THREE.Vector2();
  5529. }
  5530. array[ offset ++ ] = vector.x;
  5531. array[ offset ++ ] = vector.y;
  5532. }
  5533. return this;
  5534. },
  5535. copyVector3sArray: function ( vectors ) {
  5536. var array = this.array, offset = 0;
  5537. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5538. var vector = vectors[ i ];
  5539. if ( vector === undefined ) {
  5540. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  5541. vector = new THREE.Vector3();
  5542. }
  5543. array[ offset ++ ] = vector.x;
  5544. array[ offset ++ ] = vector.y;
  5545. array[ offset ++ ] = vector.z;
  5546. }
  5547. return this;
  5548. },
  5549. copyVector4sArray: function ( vectors ) {
  5550. var array = this.array, offset = 0;
  5551. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  5552. var vector = vectors[ i ];
  5553. if ( vector === undefined ) {
  5554. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  5555. vector = new THREE.Vector4();
  5556. }
  5557. array[ offset ++ ] = vector.x;
  5558. array[ offset ++ ] = vector.y;
  5559. array[ offset ++ ] = vector.z;
  5560. array[ offset ++ ] = vector.w;
  5561. }
  5562. return this;
  5563. },
  5564. set: function ( value, offset ) {
  5565. if ( offset === undefined ) offset = 0;
  5566. this.array.set( value, offset );
  5567. return this;
  5568. },
  5569. getX: function ( index ) {
  5570. return this.array[ index * this.itemSize ];
  5571. },
  5572. setX: function ( index, x ) {
  5573. this.array[ index * this.itemSize ] = x;
  5574. return this;
  5575. },
  5576. getY: function ( index ) {
  5577. return this.array[ index * this.itemSize + 1 ];
  5578. },
  5579. setY: function ( index, y ) {
  5580. this.array[ index * this.itemSize + 1 ] = y;
  5581. return this;
  5582. },
  5583. getZ: function ( index ) {
  5584. return this.array[ index * this.itemSize + 2 ];
  5585. },
  5586. setZ: function ( index, z ) {
  5587. this.array[ index * this.itemSize + 2 ] = z;
  5588. return this;
  5589. },
  5590. getW: function ( index ) {
  5591. return this.array[ index * this.itemSize + 3 ];
  5592. },
  5593. setW: function ( index, w ) {
  5594. this.array[ index * this.itemSize + 3 ] = w;
  5595. return this;
  5596. },
  5597. setXY: function ( index, x, y ) {
  5598. index *= this.itemSize;
  5599. this.array[ index + 0 ] = x;
  5600. this.array[ index + 1 ] = y;
  5601. return this;
  5602. },
  5603. setXYZ: function ( index, x, y, z ) {
  5604. index *= this.itemSize;
  5605. this.array[ index + 0 ] = x;
  5606. this.array[ index + 1 ] = y;
  5607. this.array[ index + 2 ] = z;
  5608. return this;
  5609. },
  5610. setXYZW: function ( index, x, y, z, w ) {
  5611. index *= this.itemSize;
  5612. this.array[ index + 0 ] = x;
  5613. this.array[ index + 1 ] = y;
  5614. this.array[ index + 2 ] = z;
  5615. this.array[ index + 3 ] = w;
  5616. return this;
  5617. },
  5618. clone: function () {
  5619. return new this.constructor().copy( this );
  5620. }
  5621. };
  5622. //
  5623. THREE.Int8Attribute = function ( array, itemSize ) {
  5624. return new THREE.BufferAttribute( new Int8Array( array ), itemSize );
  5625. };
  5626. THREE.Uint8Attribute = function ( array, itemSize ) {
  5627. return new THREE.BufferAttribute( new Uint8Array( array ), itemSize );
  5628. };
  5629. THREE.Uint8ClampedAttribute = function ( array, itemSize ) {
  5630. return new THREE.BufferAttribute( new Uint8ClampedArray( array ), itemSize );
  5631. };
  5632. THREE.Int16Attribute = function ( array, itemSize ) {
  5633. return new THREE.BufferAttribute( new Int16Array( array ), itemSize );
  5634. };
  5635. THREE.Uint16Attribute = function ( array, itemSize ) {
  5636. return new THREE.BufferAttribute( new Uint16Array( array ), itemSize );
  5637. };
  5638. THREE.Int32Attribute = function ( array, itemSize ) {
  5639. return new THREE.BufferAttribute( new Int32Array( array ), itemSize );
  5640. };
  5641. THREE.Uint32Attribute = function ( array, itemSize ) {
  5642. return new THREE.BufferAttribute( new Uint32Array( array ), itemSize );
  5643. };
  5644. THREE.Float32Attribute = function ( array, itemSize ) {
  5645. return new THREE.BufferAttribute( new Float32Array( array ), itemSize );
  5646. };
  5647. THREE.Float64Attribute = function ( array, itemSize ) {
  5648. return new THREE.BufferAttribute( new Float64Array( array ), itemSize );
  5649. };
  5650. // Deprecated
  5651. THREE.DynamicBufferAttribute = function ( array, itemSize ) {
  5652. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  5653. return new THREE.BufferAttribute( array, itemSize ).setDynamic( true );
  5654. };
  5655. // File:src/core/InstancedBufferAttribute.js
  5656. /**
  5657. * @author benaadams / https://twitter.com/ben_a_adams
  5658. */
  5659. THREE.InstancedBufferAttribute = function ( array, itemSize, meshPerAttribute ) {
  5660. THREE.BufferAttribute.call( this, array, itemSize );
  5661. this.meshPerAttribute = meshPerAttribute || 1;
  5662. };
  5663. THREE.InstancedBufferAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5664. THREE.InstancedBufferAttribute.prototype.constructor = THREE.InstancedBufferAttribute;
  5665. THREE.InstancedBufferAttribute.prototype.copy = function ( source ) {
  5666. THREE.BufferAttribute.prototype.copy.call( this, source );
  5667. this.meshPerAttribute = source.meshPerAttribute;
  5668. return this;
  5669. };
  5670. // File:src/core/InterleavedBuffer.js
  5671. /**
  5672. * @author benaadams / https://twitter.com/ben_a_adams
  5673. */
  5674. THREE.InterleavedBuffer = function ( array, stride ) {
  5675. this.uuid = THREE.Math.generateUUID();
  5676. this.array = array;
  5677. this.stride = stride;
  5678. this.dynamic = false;
  5679. this.updateRange = { offset: 0, count: - 1 };
  5680. this.version = 0;
  5681. };
  5682. THREE.InterleavedBuffer.prototype = {
  5683. constructor: THREE.InterleavedBuffer,
  5684. get length () {
  5685. return this.array.length;
  5686. },
  5687. get count () {
  5688. return this.array.length / this.stride;
  5689. },
  5690. set needsUpdate( value ) {
  5691. if ( value === true ) this.version ++;
  5692. },
  5693. setDynamic: function ( value ) {
  5694. this.dynamic = value;
  5695. return this;
  5696. },
  5697. copy: function ( source ) {
  5698. this.array = new source.array.constructor( source.array );
  5699. this.stride = source.stride;
  5700. this.dynamic = source.dynamic;
  5701. return this;
  5702. },
  5703. copyAt: function ( index1, attribute, index2 ) {
  5704. index1 *= this.stride;
  5705. index2 *= attribute.stride;
  5706. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  5707. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  5708. }
  5709. return this;
  5710. },
  5711. set: function ( value, offset ) {
  5712. if ( offset === undefined ) offset = 0;
  5713. this.array.set( value, offset );
  5714. return this;
  5715. },
  5716. clone: function () {
  5717. return new this.constructor().copy( this );
  5718. }
  5719. };
  5720. // File:src/core/InstancedInterleavedBuffer.js
  5721. /**
  5722. * @author benaadams / https://twitter.com/ben_a_adams
  5723. */
  5724. THREE.InstancedInterleavedBuffer = function ( array, stride, meshPerAttribute ) {
  5725. THREE.InterleavedBuffer.call( this, array, stride );
  5726. this.meshPerAttribute = meshPerAttribute || 1;
  5727. };
  5728. THREE.InstancedInterleavedBuffer.prototype = Object.create( THREE.InterleavedBuffer.prototype );
  5729. THREE.InstancedInterleavedBuffer.prototype.constructor = THREE.InstancedInterleavedBuffer;
  5730. THREE.InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  5731. THREE.InterleavedBuffer.prototype.copy.call( this, source );
  5732. this.meshPerAttribute = source.meshPerAttribute;
  5733. return this;
  5734. };
  5735. // File:src/core/InterleavedBufferAttribute.js
  5736. /**
  5737. * @author benaadams / https://twitter.com/ben_a_adams
  5738. */
  5739. THREE.InterleavedBufferAttribute = function ( interleavedBuffer, itemSize, offset ) {
  5740. this.uuid = THREE.Math.generateUUID();
  5741. this.data = interleavedBuffer;
  5742. this.itemSize = itemSize;
  5743. this.offset = offset;
  5744. };
  5745. THREE.InterleavedBufferAttribute.prototype = {
  5746. constructor: THREE.InterleavedBufferAttribute,
  5747. get length() {
  5748. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  5749. return this.array.length;
  5750. },
  5751. get count() {
  5752. return this.data.count;
  5753. },
  5754. setX: function ( index, x ) {
  5755. this.data.array[ index * this.data.stride + this.offset ] = x;
  5756. return this;
  5757. },
  5758. setY: function ( index, y ) {
  5759. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  5760. return this;
  5761. },
  5762. setZ: function ( index, z ) {
  5763. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  5764. return this;
  5765. },
  5766. setW: function ( index, w ) {
  5767. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  5768. return this;
  5769. },
  5770. getX: function ( index ) {
  5771. return this.data.array[ index * this.data.stride + this.offset ];
  5772. },
  5773. getY: function ( index ) {
  5774. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  5775. },
  5776. getZ: function ( index ) {
  5777. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  5778. },
  5779. getW: function ( index ) {
  5780. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  5781. },
  5782. setXY: function ( index, x, y ) {
  5783. index = index * this.data.stride + this.offset;
  5784. this.data.array[ index + 0 ] = x;
  5785. this.data.array[ index + 1 ] = y;
  5786. return this;
  5787. },
  5788. setXYZ: function ( index, x, y, z ) {
  5789. index = index * this.data.stride + this.offset;
  5790. this.data.array[ index + 0 ] = x;
  5791. this.data.array[ index + 1 ] = y;
  5792. this.data.array[ index + 2 ] = z;
  5793. return this;
  5794. },
  5795. setXYZW: function ( index, x, y, z, w ) {
  5796. index = index * this.data.stride + this.offset;
  5797. this.data.array[ index + 0 ] = x;
  5798. this.data.array[ index + 1 ] = y;
  5799. this.data.array[ index + 2 ] = z;
  5800. this.data.array[ index + 3 ] = w;
  5801. return this;
  5802. }
  5803. };
  5804. // File:src/core/Geometry.js
  5805. /**
  5806. * @author mrdoob / http://mrdoob.com/
  5807. * @author kile / http://kile.stravaganza.org/
  5808. * @author alteredq / http://alteredqualia.com/
  5809. * @author mikael emtinger / http://gomo.se/
  5810. * @author zz85 / http://www.lab4games.net/zz85/blog
  5811. * @author bhouston / http://clara.io
  5812. */
  5813. THREE.Geometry = function () {
  5814. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  5815. this.uuid = THREE.Math.generateUUID();
  5816. this.name = '';
  5817. this.type = 'Geometry';
  5818. this.vertices = [];
  5819. this.colors = [];
  5820. this.faces = [];
  5821. this.faceVertexUvs = [ [] ];
  5822. this.morphTargets = [];
  5823. this.morphNormals = [];
  5824. this.skinWeights = [];
  5825. this.skinIndices = [];
  5826. this.lineDistances = [];
  5827. this.boundingBox = null;
  5828. this.boundingSphere = null;
  5829. // update flags
  5830. this.verticesNeedUpdate = false;
  5831. this.elementsNeedUpdate = false;
  5832. this.uvsNeedUpdate = false;
  5833. this.normalsNeedUpdate = false;
  5834. this.colorsNeedUpdate = false;
  5835. this.lineDistancesNeedUpdate = false;
  5836. this.groupsNeedUpdate = false;
  5837. };
  5838. THREE.Geometry.prototype = {
  5839. constructor: THREE.Geometry,
  5840. applyMatrix: function ( matrix ) {
  5841. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5842. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5843. var vertex = this.vertices[ i ];
  5844. vertex.applyMatrix4( matrix );
  5845. }
  5846. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5847. var face = this.faces[ i ];
  5848. face.normal.applyMatrix3( normalMatrix ).normalize();
  5849. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5850. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5851. }
  5852. }
  5853. if ( this.boundingBox !== null ) {
  5854. this.computeBoundingBox();
  5855. }
  5856. if ( this.boundingSphere !== null ) {
  5857. this.computeBoundingSphere();
  5858. }
  5859. this.verticesNeedUpdate = true;
  5860. this.normalsNeedUpdate = true;
  5861. return this;
  5862. },
  5863. rotateX: function () {
  5864. // rotate geometry around world x-axis
  5865. var m1;
  5866. return function rotateX( angle ) {
  5867. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5868. m1.makeRotationX( angle );
  5869. this.applyMatrix( m1 );
  5870. return this;
  5871. };
  5872. }(),
  5873. rotateY: function () {
  5874. // rotate geometry around world y-axis
  5875. var m1;
  5876. return function rotateY( angle ) {
  5877. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5878. m1.makeRotationY( angle );
  5879. this.applyMatrix( m1 );
  5880. return this;
  5881. };
  5882. }(),
  5883. rotateZ: function () {
  5884. // rotate geometry around world z-axis
  5885. var m1;
  5886. return function rotateZ( angle ) {
  5887. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5888. m1.makeRotationZ( angle );
  5889. this.applyMatrix( m1 );
  5890. return this;
  5891. };
  5892. }(),
  5893. translate: function () {
  5894. // translate geometry
  5895. var m1;
  5896. return function translate( x, y, z ) {
  5897. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5898. m1.makeTranslation( x, y, z );
  5899. this.applyMatrix( m1 );
  5900. return this;
  5901. };
  5902. }(),
  5903. scale: function () {
  5904. // scale geometry
  5905. var m1;
  5906. return function scale( x, y, z ) {
  5907. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  5908. m1.makeScale( x, y, z );
  5909. this.applyMatrix( m1 );
  5910. return this;
  5911. };
  5912. }(),
  5913. lookAt: function () {
  5914. var obj;
  5915. return function lookAt( vector ) {
  5916. if ( obj === undefined ) obj = new THREE.Object3D();
  5917. obj.lookAt( vector );
  5918. obj.updateMatrix();
  5919. this.applyMatrix( obj.matrix );
  5920. };
  5921. }(),
  5922. fromBufferGeometry: function ( geometry ) {
  5923. var scope = this;
  5924. var indices = geometry.index !== null ? geometry.index.array : undefined;
  5925. var attributes = geometry.attributes;
  5926. var positions = attributes.position.array;
  5927. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  5928. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  5929. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  5930. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  5931. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  5932. var tempNormals = [];
  5933. var tempUVs = [];
  5934. var tempUVs2 = [];
  5935. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  5936. scope.vertices.push( new THREE.Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  5937. if ( normals !== undefined ) {
  5938. tempNormals.push( new THREE.Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  5939. }
  5940. if ( colors !== undefined ) {
  5941. scope.colors.push( new THREE.Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  5942. }
  5943. if ( uvs !== undefined ) {
  5944. tempUVs.push( new THREE.Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  5945. }
  5946. if ( uvs2 !== undefined ) {
  5947. tempUVs2.push( new THREE.Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  5948. }
  5949. }
  5950. function addFace( a, b, c, materialIndex ) {
  5951. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  5952. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  5953. var face = new THREE.Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  5954. scope.faces.push( face );
  5955. if ( uvs !== undefined ) {
  5956. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  5957. }
  5958. if ( uvs2 !== undefined ) {
  5959. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  5960. }
  5961. }
  5962. if ( indices !== undefined ) {
  5963. var groups = geometry.groups;
  5964. if ( groups.length > 0 ) {
  5965. for ( var i = 0; i < groups.length; i ++ ) {
  5966. var group = groups[ i ];
  5967. var start = group.start;
  5968. var count = group.count;
  5969. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  5970. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  5971. }
  5972. }
  5973. } else {
  5974. for ( var i = 0; i < indices.length; i += 3 ) {
  5975. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  5976. }
  5977. }
  5978. } else {
  5979. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  5980. addFace( i, i + 1, i + 2 );
  5981. }
  5982. }
  5983. this.computeFaceNormals();
  5984. if ( geometry.boundingBox !== null ) {
  5985. this.boundingBox = geometry.boundingBox.clone();
  5986. }
  5987. if ( geometry.boundingSphere !== null ) {
  5988. this.boundingSphere = geometry.boundingSphere.clone();
  5989. }
  5990. return this;
  5991. },
  5992. center: function () {
  5993. this.computeBoundingBox();
  5994. var offset = this.boundingBox.center().negate();
  5995. this.translate( offset.x, offset.y, offset.z );
  5996. return offset;
  5997. },
  5998. normalize: function () {
  5999. this.computeBoundingSphere();
  6000. var center = this.boundingSphere.center;
  6001. var radius = this.boundingSphere.radius;
  6002. var s = radius === 0 ? 1 : 1.0 / radius;
  6003. var matrix = new THREE.Matrix4();
  6004. matrix.set(
  6005. s, 0, 0, - s * center.x,
  6006. 0, s, 0, - s * center.y,
  6007. 0, 0, s, - s * center.z,
  6008. 0, 0, 0, 1
  6009. );
  6010. this.applyMatrix( matrix );
  6011. return this;
  6012. },
  6013. computeFaceNormals: function () {
  6014. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  6015. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6016. var face = this.faces[ f ];
  6017. var vA = this.vertices[ face.a ];
  6018. var vB = this.vertices[ face.b ];
  6019. var vC = this.vertices[ face.c ];
  6020. cb.subVectors( vC, vB );
  6021. ab.subVectors( vA, vB );
  6022. cb.cross( ab );
  6023. cb.normalize();
  6024. face.normal.copy( cb );
  6025. }
  6026. },
  6027. computeVertexNormals: function ( areaWeighted ) {
  6028. if ( areaWeighted === undefined ) areaWeighted = true;
  6029. var v, vl, f, fl, face, vertices;
  6030. vertices = new Array( this.vertices.length );
  6031. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6032. vertices[ v ] = new THREE.Vector3();
  6033. }
  6034. if ( areaWeighted ) {
  6035. // vertex normals weighted by triangle areas
  6036. // http://www.iquilezles.org/www/articles/normals/normals.htm
  6037. var vA, vB, vC;
  6038. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  6039. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6040. face = this.faces[ f ];
  6041. vA = this.vertices[ face.a ];
  6042. vB = this.vertices[ face.b ];
  6043. vC = this.vertices[ face.c ];
  6044. cb.subVectors( vC, vB );
  6045. ab.subVectors( vA, vB );
  6046. cb.cross( ab );
  6047. vertices[ face.a ].add( cb );
  6048. vertices[ face.b ].add( cb );
  6049. vertices[ face.c ].add( cb );
  6050. }
  6051. } else {
  6052. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6053. face = this.faces[ f ];
  6054. vertices[ face.a ].add( face.normal );
  6055. vertices[ face.b ].add( face.normal );
  6056. vertices[ face.c ].add( face.normal );
  6057. }
  6058. }
  6059. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6060. vertices[ v ].normalize();
  6061. }
  6062. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6063. face = this.faces[ f ];
  6064. var vertexNormals = face.vertexNormals;
  6065. if ( vertexNormals.length === 3 ) {
  6066. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  6067. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  6068. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  6069. } else {
  6070. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  6071. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  6072. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  6073. }
  6074. }
  6075. if ( this.faces.length > 0 ) {
  6076. this.normalsNeedUpdate = true;
  6077. }
  6078. },
  6079. computeMorphNormals: function () {
  6080. var i, il, f, fl, face;
  6081. // save original normals
  6082. // - create temp variables on first access
  6083. // otherwise just copy (for faster repeated calls)
  6084. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6085. face = this.faces[ f ];
  6086. if ( ! face.__originalFaceNormal ) {
  6087. face.__originalFaceNormal = face.normal.clone();
  6088. } else {
  6089. face.__originalFaceNormal.copy( face.normal );
  6090. }
  6091. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  6092. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  6093. if ( ! face.__originalVertexNormals[ i ] ) {
  6094. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  6095. } else {
  6096. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6097. }
  6098. }
  6099. }
  6100. // use temp geometry to compute face and vertex normals for each morph
  6101. var tmpGeo = new THREE.Geometry();
  6102. tmpGeo.faces = this.faces;
  6103. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6104. // create on first access
  6105. if ( ! this.morphNormals[ i ] ) {
  6106. this.morphNormals[ i ] = {};
  6107. this.morphNormals[ i ].faceNormals = [];
  6108. this.morphNormals[ i ].vertexNormals = [];
  6109. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6110. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6111. var faceNormal, vertexNormals;
  6112. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6113. faceNormal = new THREE.Vector3();
  6114. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  6115. dstNormalsFace.push( faceNormal );
  6116. dstNormalsVertex.push( vertexNormals );
  6117. }
  6118. }
  6119. var morphNormals = this.morphNormals[ i ];
  6120. // set vertices to morph target
  6121. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6122. // compute morph normals
  6123. tmpGeo.computeFaceNormals();
  6124. tmpGeo.computeVertexNormals();
  6125. // store morph normals
  6126. var faceNormal, vertexNormals;
  6127. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6128. face = this.faces[ f ];
  6129. faceNormal = morphNormals.faceNormals[ f ];
  6130. vertexNormals = morphNormals.vertexNormals[ f ];
  6131. faceNormal.copy( face.normal );
  6132. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  6133. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  6134. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  6135. }
  6136. }
  6137. // restore original normals
  6138. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6139. face = this.faces[ f ];
  6140. face.normal = face.__originalFaceNormal;
  6141. face.vertexNormals = face.__originalVertexNormals;
  6142. }
  6143. },
  6144. computeTangents: function () {
  6145. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  6146. },
  6147. computeLineDistances: function () {
  6148. var d = 0;
  6149. var vertices = this.vertices;
  6150. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6151. if ( i > 0 ) {
  6152. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6153. }
  6154. this.lineDistances[ i ] = d;
  6155. }
  6156. },
  6157. computeBoundingBox: function () {
  6158. if ( this.boundingBox === null ) {
  6159. this.boundingBox = new THREE.Box3();
  6160. }
  6161. this.boundingBox.setFromPoints( this.vertices );
  6162. },
  6163. computeBoundingSphere: function () {
  6164. if ( this.boundingSphere === null ) {
  6165. this.boundingSphere = new THREE.Sphere();
  6166. }
  6167. this.boundingSphere.setFromPoints( this.vertices );
  6168. },
  6169. merge: function ( geometry, matrix, materialIndexOffset ) {
  6170. if ( geometry instanceof THREE.Geometry === false ) {
  6171. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  6172. return;
  6173. }
  6174. var normalMatrix,
  6175. vertexOffset = this.vertices.length,
  6176. vertices1 = this.vertices,
  6177. vertices2 = geometry.vertices,
  6178. faces1 = this.faces,
  6179. faces2 = geometry.faces,
  6180. uvs1 = this.faceVertexUvs[ 0 ],
  6181. uvs2 = geometry.faceVertexUvs[ 0 ];
  6182. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  6183. if ( matrix !== undefined ) {
  6184. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6185. }
  6186. // vertices
  6187. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  6188. var vertex = vertices2[ i ];
  6189. var vertexCopy = vertex.clone();
  6190. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  6191. vertices1.push( vertexCopy );
  6192. }
  6193. // faces
  6194. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  6195. var face = faces2[ i ], faceCopy, normal, color,
  6196. faceVertexNormals = face.vertexNormals,
  6197. faceVertexColors = face.vertexColors;
  6198. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  6199. faceCopy.normal.copy( face.normal );
  6200. if ( normalMatrix !== undefined ) {
  6201. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  6202. }
  6203. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  6204. normal = faceVertexNormals[ j ].clone();
  6205. if ( normalMatrix !== undefined ) {
  6206. normal.applyMatrix3( normalMatrix ).normalize();
  6207. }
  6208. faceCopy.vertexNormals.push( normal );
  6209. }
  6210. faceCopy.color.copy( face.color );
  6211. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  6212. color = faceVertexColors[ j ];
  6213. faceCopy.vertexColors.push( color.clone() );
  6214. }
  6215. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  6216. faces1.push( faceCopy );
  6217. }
  6218. // uvs
  6219. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  6220. var uv = uvs2[ i ], uvCopy = [];
  6221. if ( uv === undefined ) {
  6222. continue;
  6223. }
  6224. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6225. uvCopy.push( uv[ j ].clone() );
  6226. }
  6227. uvs1.push( uvCopy );
  6228. }
  6229. },
  6230. mergeMesh: function ( mesh ) {
  6231. if ( mesh instanceof THREE.Mesh === false ) {
  6232. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  6233. return;
  6234. }
  6235. mesh.matrixAutoUpdate && mesh.updateMatrix();
  6236. this.merge( mesh.geometry, mesh.matrix );
  6237. },
  6238. /*
  6239. * Checks for duplicate vertices with hashmap.
  6240. * Duplicated vertices are removed
  6241. * and faces' vertices are updated.
  6242. */
  6243. mergeVertices: function () {
  6244. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  6245. var unique = [], changes = [];
  6246. var v, key;
  6247. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  6248. var precision = Math.pow( 10, precisionPoints );
  6249. var i, il, face;
  6250. var indices, j, jl;
  6251. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6252. v = this.vertices[ i ];
  6253. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6254. if ( verticesMap[ key ] === undefined ) {
  6255. verticesMap[ key ] = i;
  6256. unique.push( this.vertices[ i ] );
  6257. changes[ i ] = unique.length - 1;
  6258. } else {
  6259. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6260. changes[ i ] = changes[ verticesMap[ key ] ];
  6261. }
  6262. }
  6263. // if faces are completely degenerate after merging vertices, we
  6264. // have to remove them from the geometry.
  6265. var faceIndicesToRemove = [];
  6266. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  6267. face = this.faces[ i ];
  6268. face.a = changes[ face.a ];
  6269. face.b = changes[ face.b ];
  6270. face.c = changes[ face.c ];
  6271. indices = [ face.a, face.b, face.c ];
  6272. var dupIndex = - 1;
  6273. // if any duplicate vertices are found in a Face3
  6274. // we have to remove the face as nothing can be saved
  6275. for ( var n = 0; n < 3; n ++ ) {
  6276. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  6277. dupIndex = n;
  6278. faceIndicesToRemove.push( i );
  6279. break;
  6280. }
  6281. }
  6282. }
  6283. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6284. var idx = faceIndicesToRemove[ i ];
  6285. this.faces.splice( idx, 1 );
  6286. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6287. this.faceVertexUvs[ j ].splice( idx, 1 );
  6288. }
  6289. }
  6290. // Use unique set of vertices
  6291. var diff = this.vertices.length - unique.length;
  6292. this.vertices = unique;
  6293. return diff;
  6294. },
  6295. sortFacesByMaterialIndex: function () {
  6296. var faces = this.faces;
  6297. var length = faces.length;
  6298. // tag faces
  6299. for ( var i = 0; i < length; i ++ ) {
  6300. faces[ i ]._id = i;
  6301. }
  6302. // sort faces
  6303. function materialIndexSort( a, b ) {
  6304. return a.materialIndex - b.materialIndex;
  6305. }
  6306. faces.sort( materialIndexSort );
  6307. // sort uvs
  6308. var uvs1 = this.faceVertexUvs[ 0 ];
  6309. var uvs2 = this.faceVertexUvs[ 1 ];
  6310. var newUvs1, newUvs2;
  6311. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  6312. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  6313. for ( var i = 0; i < length; i ++ ) {
  6314. var id = faces[ i ]._id;
  6315. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  6316. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  6317. }
  6318. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  6319. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  6320. },
  6321. toJSON: function () {
  6322. var data = {
  6323. metadata: {
  6324. version: 4.4,
  6325. type: 'Geometry',
  6326. generator: 'Geometry.toJSON'
  6327. }
  6328. };
  6329. // standard Geometry serialization
  6330. data.uuid = this.uuid;
  6331. data.type = this.type;
  6332. if ( this.name !== '' ) data.name = this.name;
  6333. if ( this.parameters !== undefined ) {
  6334. var parameters = this.parameters;
  6335. for ( var key in parameters ) {
  6336. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  6337. }
  6338. return data;
  6339. }
  6340. var vertices = [];
  6341. for ( var i = 0; i < this.vertices.length; i ++ ) {
  6342. var vertex = this.vertices[ i ];
  6343. vertices.push( vertex.x, vertex.y, vertex.z );
  6344. }
  6345. var faces = [];
  6346. var normals = [];
  6347. var normalsHash = {};
  6348. var colors = [];
  6349. var colorsHash = {};
  6350. var uvs = [];
  6351. var uvsHash = {};
  6352. for ( var i = 0; i < this.faces.length; i ++ ) {
  6353. var face = this.faces[ i ];
  6354. var hasMaterial = true;
  6355. var hasFaceUv = false; // deprecated
  6356. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  6357. var hasFaceNormal = face.normal.length() > 0;
  6358. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  6359. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  6360. var hasFaceVertexColor = face.vertexColors.length > 0;
  6361. var faceType = 0;
  6362. faceType = setBit( faceType, 0, 0 ); // isQuad
  6363. faceType = setBit( faceType, 1, hasMaterial );
  6364. faceType = setBit( faceType, 2, hasFaceUv );
  6365. faceType = setBit( faceType, 3, hasFaceVertexUv );
  6366. faceType = setBit( faceType, 4, hasFaceNormal );
  6367. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  6368. faceType = setBit( faceType, 6, hasFaceColor );
  6369. faceType = setBit( faceType, 7, hasFaceVertexColor );
  6370. faces.push( faceType );
  6371. faces.push( face.a, face.b, face.c );
  6372. faces.push( face.materialIndex );
  6373. if ( hasFaceVertexUv ) {
  6374. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  6375. faces.push(
  6376. getUvIndex( faceVertexUvs[ 0 ] ),
  6377. getUvIndex( faceVertexUvs[ 1 ] ),
  6378. getUvIndex( faceVertexUvs[ 2 ] )
  6379. );
  6380. }
  6381. if ( hasFaceNormal ) {
  6382. faces.push( getNormalIndex( face.normal ) );
  6383. }
  6384. if ( hasFaceVertexNormal ) {
  6385. var vertexNormals = face.vertexNormals;
  6386. faces.push(
  6387. getNormalIndex( vertexNormals[ 0 ] ),
  6388. getNormalIndex( vertexNormals[ 1 ] ),
  6389. getNormalIndex( vertexNormals[ 2 ] )
  6390. );
  6391. }
  6392. if ( hasFaceColor ) {
  6393. faces.push( getColorIndex( face.color ) );
  6394. }
  6395. if ( hasFaceVertexColor ) {
  6396. var vertexColors = face.vertexColors;
  6397. faces.push(
  6398. getColorIndex( vertexColors[ 0 ] ),
  6399. getColorIndex( vertexColors[ 1 ] ),
  6400. getColorIndex( vertexColors[ 2 ] )
  6401. );
  6402. }
  6403. }
  6404. function setBit( value, position, enabled ) {
  6405. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  6406. }
  6407. function getNormalIndex( normal ) {
  6408. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  6409. if ( normalsHash[ hash ] !== undefined ) {
  6410. return normalsHash[ hash ];
  6411. }
  6412. normalsHash[ hash ] = normals.length / 3;
  6413. normals.push( normal.x, normal.y, normal.z );
  6414. return normalsHash[ hash ];
  6415. }
  6416. function getColorIndex( color ) {
  6417. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  6418. if ( colorsHash[ hash ] !== undefined ) {
  6419. return colorsHash[ hash ];
  6420. }
  6421. colorsHash[ hash ] = colors.length;
  6422. colors.push( color.getHex() );
  6423. return colorsHash[ hash ];
  6424. }
  6425. function getUvIndex( uv ) {
  6426. var hash = uv.x.toString() + uv.y.toString();
  6427. if ( uvsHash[ hash ] !== undefined ) {
  6428. return uvsHash[ hash ];
  6429. }
  6430. uvsHash[ hash ] = uvs.length / 2;
  6431. uvs.push( uv.x, uv.y );
  6432. return uvsHash[ hash ];
  6433. }
  6434. data.data = {};
  6435. data.data.vertices = vertices;
  6436. data.data.normals = normals;
  6437. if ( colors.length > 0 ) data.data.colors = colors;
  6438. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  6439. data.data.faces = faces;
  6440. return data;
  6441. },
  6442. clone: function () {
  6443. /*
  6444. // Handle primitives
  6445. var parameters = this.parameters;
  6446. if ( parameters !== undefined ) {
  6447. var values = [];
  6448. for ( var key in parameters ) {
  6449. values.push( parameters[ key ] );
  6450. }
  6451. var geometry = Object.create( this.constructor.prototype );
  6452. this.constructor.apply( geometry, values );
  6453. return geometry;
  6454. }
  6455. return new this.constructor().copy( this );
  6456. */
  6457. return new THREE.Geometry().copy( this );
  6458. },
  6459. copy: function ( source ) {
  6460. this.vertices = [];
  6461. this.faces = [];
  6462. this.faceVertexUvs = [ [] ];
  6463. var vertices = source.vertices;
  6464. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6465. this.vertices.push( vertices[ i ].clone() );
  6466. }
  6467. var faces = source.faces;
  6468. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6469. this.faces.push( faces[ i ].clone() );
  6470. }
  6471. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  6472. var faceVertexUvs = source.faceVertexUvs[ i ];
  6473. if ( this.faceVertexUvs[ i ] === undefined ) {
  6474. this.faceVertexUvs[ i ] = [];
  6475. }
  6476. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  6477. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  6478. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  6479. var uv = uvs[ k ];
  6480. uvsCopy.push( uv.clone() );
  6481. }
  6482. this.faceVertexUvs[ i ].push( uvsCopy );
  6483. }
  6484. }
  6485. return this;
  6486. },
  6487. dispose: function () {
  6488. this.dispatchEvent( { type: 'dispose' } );
  6489. }
  6490. };
  6491. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6492. THREE.GeometryIdCount = 0;
  6493. // File:src/core/DirectGeometry.js
  6494. /**
  6495. * @author mrdoob / http://mrdoob.com/
  6496. */
  6497. THREE.DirectGeometry = function () {
  6498. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6499. this.uuid = THREE.Math.generateUUID();
  6500. this.name = '';
  6501. this.type = 'DirectGeometry';
  6502. this.indices = [];
  6503. this.vertices = [];
  6504. this.normals = [];
  6505. this.colors = [];
  6506. this.uvs = [];
  6507. this.uvs2 = [];
  6508. this.groups = [];
  6509. this.morphTargets = {};
  6510. this.skinWeights = [];
  6511. this.skinIndices = [];
  6512. // this.lineDistances = [];
  6513. this.boundingBox = null;
  6514. this.boundingSphere = null;
  6515. // update flags
  6516. this.verticesNeedUpdate = false;
  6517. this.normalsNeedUpdate = false;
  6518. this.colorsNeedUpdate = false;
  6519. this.uvsNeedUpdate = false;
  6520. this.groupsNeedUpdate = false;
  6521. };
  6522. THREE.DirectGeometry.prototype = {
  6523. constructor: THREE.DirectGeometry,
  6524. computeBoundingBox: THREE.Geometry.prototype.computeBoundingBox,
  6525. computeBoundingSphere: THREE.Geometry.prototype.computeBoundingSphere,
  6526. computeFaceNormals: function () {
  6527. console.warn( 'THREE.DirectGeometry: computeFaceNormals() is not a method of this type of geometry.' );
  6528. },
  6529. computeVertexNormals: function () {
  6530. console.warn( 'THREE.DirectGeometry: computeVertexNormals() is not a method of this type of geometry.' );
  6531. },
  6532. computeGroups: function ( geometry ) {
  6533. var group;
  6534. var groups = [];
  6535. var materialIndex;
  6536. var faces = geometry.faces;
  6537. for ( var i = 0; i < faces.length; i ++ ) {
  6538. var face = faces[ i ];
  6539. // materials
  6540. if ( face.materialIndex !== materialIndex ) {
  6541. materialIndex = face.materialIndex;
  6542. if ( group !== undefined ) {
  6543. group.count = ( i * 3 ) - group.start;
  6544. groups.push( group );
  6545. }
  6546. group = {
  6547. start: i * 3,
  6548. materialIndex: materialIndex
  6549. };
  6550. }
  6551. }
  6552. if ( group !== undefined ) {
  6553. group.count = ( i * 3 ) - group.start;
  6554. groups.push( group );
  6555. }
  6556. this.groups = groups;
  6557. },
  6558. fromGeometry: function ( geometry ) {
  6559. var faces = geometry.faces;
  6560. var vertices = geometry.vertices;
  6561. var faceVertexUvs = geometry.faceVertexUvs;
  6562. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  6563. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  6564. // morphs
  6565. var morphTargets = geometry.morphTargets;
  6566. var morphTargetsLength = morphTargets.length;
  6567. var morphTargetsPosition;
  6568. if ( morphTargetsLength > 0 ) {
  6569. morphTargetsPosition = [];
  6570. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  6571. morphTargetsPosition[ i ] = [];
  6572. }
  6573. this.morphTargets.position = morphTargetsPosition;
  6574. }
  6575. var morphNormals = geometry.morphNormals;
  6576. var morphNormalsLength = morphNormals.length;
  6577. var morphTargetsNormal;
  6578. if ( morphNormalsLength > 0 ) {
  6579. morphTargetsNormal = [];
  6580. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  6581. morphTargetsNormal[ i ] = [];
  6582. }
  6583. this.morphTargets.normal = morphTargetsNormal;
  6584. }
  6585. // skins
  6586. var skinIndices = geometry.skinIndices;
  6587. var skinWeights = geometry.skinWeights;
  6588. var hasSkinIndices = skinIndices.length === vertices.length;
  6589. var hasSkinWeights = skinWeights.length === vertices.length;
  6590. //
  6591. for ( var i = 0; i < faces.length; i ++ ) {
  6592. var face = faces[ i ];
  6593. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  6594. var vertexNormals = face.vertexNormals;
  6595. if ( vertexNormals.length === 3 ) {
  6596. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  6597. } else {
  6598. var normal = face.normal;
  6599. this.normals.push( normal, normal, normal );
  6600. }
  6601. var vertexColors = face.vertexColors;
  6602. if ( vertexColors.length === 3 ) {
  6603. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  6604. } else {
  6605. var color = face.color;
  6606. this.colors.push( color, color, color );
  6607. }
  6608. if ( hasFaceVertexUv === true ) {
  6609. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  6610. if ( vertexUvs !== undefined ) {
  6611. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6612. } else {
  6613. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  6614. this.uvs.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6615. }
  6616. }
  6617. if ( hasFaceVertexUv2 === true ) {
  6618. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  6619. if ( vertexUvs !== undefined ) {
  6620. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  6621. } else {
  6622. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  6623. this.uvs2.push( new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() );
  6624. }
  6625. }
  6626. // morphs
  6627. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  6628. var morphTarget = morphTargets[ j ].vertices;
  6629. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  6630. }
  6631. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  6632. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  6633. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  6634. }
  6635. // skins
  6636. if ( hasSkinIndices ) {
  6637. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  6638. }
  6639. if ( hasSkinWeights ) {
  6640. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  6641. }
  6642. }
  6643. this.computeGroups( geometry );
  6644. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6645. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6646. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6647. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6648. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6649. return this;
  6650. },
  6651. dispose: function () {
  6652. this.dispatchEvent( { type: 'dispose' } );
  6653. }
  6654. };
  6655. THREE.EventDispatcher.prototype.apply( THREE.DirectGeometry.prototype );
  6656. // File:src/core/BufferGeometry.js
  6657. /**
  6658. * @author alteredq / http://alteredqualia.com/
  6659. * @author mrdoob / http://mrdoob.com/
  6660. */
  6661. THREE.BufferGeometry = function () {
  6662. Object.defineProperty( this, 'id', { value: THREE.GeometryIdCount ++ } );
  6663. this.uuid = THREE.Math.generateUUID();
  6664. this.name = '';
  6665. this.type = 'BufferGeometry';
  6666. this.index = null;
  6667. this.attributes = {};
  6668. this.morphAttributes = {};
  6669. this.groups = [];
  6670. this.boundingBox = null;
  6671. this.boundingSphere = null;
  6672. this.drawRange = { start: 0, count: Infinity };
  6673. };
  6674. THREE.BufferGeometry.prototype = {
  6675. constructor: THREE.BufferGeometry,
  6676. getIndex: function () {
  6677. return this.index;
  6678. },
  6679. setIndex: function ( index ) {
  6680. this.index = index;
  6681. },
  6682. addAttribute: function ( name, attribute ) {
  6683. if ( attribute instanceof THREE.BufferAttribute === false && attribute instanceof THREE.InterleavedBufferAttribute === false ) {
  6684. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  6685. this.addAttribute( name, new THREE.BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  6686. return;
  6687. }
  6688. if ( name === 'index' ) {
  6689. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  6690. this.setIndex( attribute );
  6691. return;
  6692. }
  6693. this.attributes[ name ] = attribute;
  6694. return this;
  6695. },
  6696. getAttribute: function ( name ) {
  6697. return this.attributes[ name ];
  6698. },
  6699. removeAttribute: function ( name ) {
  6700. delete this.attributes[ name ];
  6701. return this;
  6702. },
  6703. addGroup: function ( start, count, materialIndex ) {
  6704. this.groups.push( {
  6705. start: start,
  6706. count: count,
  6707. materialIndex: materialIndex !== undefined ? materialIndex : 0
  6708. } );
  6709. },
  6710. clearGroups: function () {
  6711. this.groups = [];
  6712. },
  6713. setDrawRange: function ( start, count ) {
  6714. this.drawRange.start = start;
  6715. this.drawRange.count = count;
  6716. },
  6717. applyMatrix: function ( matrix ) {
  6718. var position = this.attributes.position;
  6719. if ( position !== undefined ) {
  6720. matrix.applyToVector3Array( position.array );
  6721. position.needsUpdate = true;
  6722. }
  6723. var normal = this.attributes.normal;
  6724. if ( normal !== undefined ) {
  6725. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  6726. normalMatrix.applyToVector3Array( normal.array );
  6727. normal.needsUpdate = true;
  6728. }
  6729. if ( this.boundingBox !== null ) {
  6730. this.computeBoundingBox();
  6731. }
  6732. if ( this.boundingSphere !== null ) {
  6733. this.computeBoundingSphere();
  6734. }
  6735. return this;
  6736. },
  6737. rotateX: function () {
  6738. // rotate geometry around world x-axis
  6739. var m1;
  6740. return function rotateX( angle ) {
  6741. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6742. m1.makeRotationX( angle );
  6743. this.applyMatrix( m1 );
  6744. return this;
  6745. };
  6746. }(),
  6747. rotateY: function () {
  6748. // rotate geometry around world y-axis
  6749. var m1;
  6750. return function rotateY( angle ) {
  6751. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6752. m1.makeRotationY( angle );
  6753. this.applyMatrix( m1 );
  6754. return this;
  6755. };
  6756. }(),
  6757. rotateZ: function () {
  6758. // rotate geometry around world z-axis
  6759. var m1;
  6760. return function rotateZ( angle ) {
  6761. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6762. m1.makeRotationZ( angle );
  6763. this.applyMatrix( m1 );
  6764. return this;
  6765. };
  6766. }(),
  6767. translate: function () {
  6768. // translate geometry
  6769. var m1;
  6770. return function translate( x, y, z ) {
  6771. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6772. m1.makeTranslation( x, y, z );
  6773. this.applyMatrix( m1 );
  6774. return this;
  6775. };
  6776. }(),
  6777. scale: function () {
  6778. // scale geometry
  6779. var m1;
  6780. return function scale( x, y, z ) {
  6781. if ( m1 === undefined ) m1 = new THREE.Matrix4();
  6782. m1.makeScale( x, y, z );
  6783. this.applyMatrix( m1 );
  6784. return this;
  6785. };
  6786. }(),
  6787. lookAt: function () {
  6788. var obj;
  6789. return function lookAt( vector ) {
  6790. if ( obj === undefined ) obj = new THREE.Object3D();
  6791. obj.lookAt( vector );
  6792. obj.updateMatrix();
  6793. this.applyMatrix( obj.matrix );
  6794. };
  6795. }(),
  6796. center: function () {
  6797. this.computeBoundingBox();
  6798. var offset = this.boundingBox.center().negate();
  6799. this.translate( offset.x, offset.y, offset.z );
  6800. return offset;
  6801. },
  6802. setFromObject: function ( object ) {
  6803. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  6804. var geometry = object.geometry;
  6805. if ( object instanceof THREE.Points || object instanceof THREE.Line ) {
  6806. var positions = new THREE.Float32Attribute( geometry.vertices.length * 3, 3 );
  6807. var colors = new THREE.Float32Attribute( geometry.colors.length * 3, 3 );
  6808. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  6809. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  6810. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  6811. var lineDistances = new THREE.Float32Attribute( geometry.lineDistances.length, 1 );
  6812. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  6813. }
  6814. if ( geometry.boundingSphere !== null ) {
  6815. this.boundingSphere = geometry.boundingSphere.clone();
  6816. }
  6817. if ( geometry.boundingBox !== null ) {
  6818. this.boundingBox = geometry.boundingBox.clone();
  6819. }
  6820. } else if ( object instanceof THREE.Mesh ) {
  6821. if ( geometry instanceof THREE.Geometry ) {
  6822. this.fromGeometry( geometry );
  6823. }
  6824. }
  6825. return this;
  6826. },
  6827. updateFromObject: function ( object ) {
  6828. var geometry = object.geometry;
  6829. if ( object instanceof THREE.Mesh ) {
  6830. var direct = geometry.__directGeometry;
  6831. if ( direct === undefined ) {
  6832. return this.fromGeometry( geometry );
  6833. }
  6834. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  6835. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  6836. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  6837. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  6838. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  6839. geometry.verticesNeedUpdate = false;
  6840. geometry.normalsNeedUpdate = false;
  6841. geometry.colorsNeedUpdate = false;
  6842. geometry.uvsNeedUpdate = false;
  6843. geometry.groupsNeedUpdate = false;
  6844. geometry = direct;
  6845. }
  6846. if ( geometry.verticesNeedUpdate === true ) {
  6847. var attribute = this.attributes.position;
  6848. if ( attribute !== undefined ) {
  6849. attribute.copyVector3sArray( geometry.vertices );
  6850. attribute.needsUpdate = true;
  6851. }
  6852. geometry.verticesNeedUpdate = false;
  6853. }
  6854. if ( geometry.normalsNeedUpdate === true ) {
  6855. var attribute = this.attributes.normal;
  6856. if ( attribute !== undefined ) {
  6857. attribute.copyVector3sArray( geometry.normals );
  6858. attribute.needsUpdate = true;
  6859. }
  6860. geometry.normalsNeedUpdate = false;
  6861. }
  6862. if ( geometry.colorsNeedUpdate === true ) {
  6863. var attribute = this.attributes.color;
  6864. if ( attribute !== undefined ) {
  6865. attribute.copyColorsArray( geometry.colors );
  6866. attribute.needsUpdate = true;
  6867. }
  6868. geometry.colorsNeedUpdate = false;
  6869. }
  6870. if ( geometry.uvsNeedUpdate ) {
  6871. var attribute = this.attributes.uv;
  6872. if ( attribute !== undefined ) {
  6873. attribute.copyVector2sArray( geometry.uvs );
  6874. attribute.needsUpdate = true;
  6875. }
  6876. geometry.uvsNeedUpdate = false;
  6877. }
  6878. if ( geometry.lineDistancesNeedUpdate ) {
  6879. var attribute = this.attributes.lineDistance;
  6880. if ( attribute !== undefined ) {
  6881. attribute.copyArray( geometry.lineDistances );
  6882. attribute.needsUpdate = true;
  6883. }
  6884. geometry.lineDistancesNeedUpdate = false;
  6885. }
  6886. if ( geometry.groupsNeedUpdate ) {
  6887. geometry.computeGroups( object.geometry );
  6888. this.groups = geometry.groups;
  6889. geometry.groupsNeedUpdate = false;
  6890. }
  6891. return this;
  6892. },
  6893. fromGeometry: function ( geometry ) {
  6894. geometry.__directGeometry = new THREE.DirectGeometry().fromGeometry( geometry );
  6895. return this.fromDirectGeometry( geometry.__directGeometry );
  6896. },
  6897. fromDirectGeometry: function ( geometry ) {
  6898. var positions = new Float32Array( geometry.vertices.length * 3 );
  6899. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  6900. if ( geometry.normals.length > 0 ) {
  6901. var normals = new Float32Array( geometry.normals.length * 3 );
  6902. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  6903. }
  6904. if ( geometry.colors.length > 0 ) {
  6905. var colors = new Float32Array( geometry.colors.length * 3 );
  6906. this.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  6907. }
  6908. if ( geometry.uvs.length > 0 ) {
  6909. var uvs = new Float32Array( geometry.uvs.length * 2 );
  6910. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  6911. }
  6912. if ( geometry.uvs2.length > 0 ) {
  6913. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  6914. this.addAttribute( 'uv2', new THREE.BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  6915. }
  6916. if ( geometry.indices.length > 0 ) {
  6917. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  6918. var indices = new TypeArray( geometry.indices.length * 3 );
  6919. this.setIndex( new THREE.BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  6920. }
  6921. // groups
  6922. this.groups = geometry.groups;
  6923. // morphs
  6924. for ( var name in geometry.morphTargets ) {
  6925. var array = [];
  6926. var morphTargets = geometry.morphTargets[ name ];
  6927. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  6928. var morphTarget = morphTargets[ i ];
  6929. var attribute = new THREE.Float32Attribute( morphTarget.length * 3, 3 );
  6930. array.push( attribute.copyVector3sArray( morphTarget ) );
  6931. }
  6932. this.morphAttributes[ name ] = array;
  6933. }
  6934. // skinning
  6935. if ( geometry.skinIndices.length > 0 ) {
  6936. var skinIndices = new THREE.Float32Attribute( geometry.skinIndices.length * 4, 4 );
  6937. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  6938. }
  6939. if ( geometry.skinWeights.length > 0 ) {
  6940. var skinWeights = new THREE.Float32Attribute( geometry.skinWeights.length * 4, 4 );
  6941. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  6942. }
  6943. //
  6944. if ( geometry.boundingSphere !== null ) {
  6945. this.boundingSphere = geometry.boundingSphere.clone();
  6946. }
  6947. if ( geometry.boundingBox !== null ) {
  6948. this.boundingBox = geometry.boundingBox.clone();
  6949. }
  6950. return this;
  6951. },
  6952. computeBoundingBox: function () {
  6953. if ( this.boundingBox === null ) {
  6954. this.boundingBox = new THREE.Box3();
  6955. }
  6956. var positions = this.attributes.position.array;
  6957. if ( positions !== undefined ) {
  6958. this.boundingBox.setFromArray( positions );
  6959. } else {
  6960. this.boundingBox.makeEmpty();
  6961. }
  6962. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  6963. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  6964. }
  6965. },
  6966. computeBoundingSphere: function () {
  6967. var box = new THREE.Box3();
  6968. var vector = new THREE.Vector3();
  6969. return function () {
  6970. if ( this.boundingSphere === null ) {
  6971. this.boundingSphere = new THREE.Sphere();
  6972. }
  6973. var positions = this.attributes.position.array;
  6974. if ( positions ) {
  6975. var center = this.boundingSphere.center;
  6976. box.setFromArray( positions );
  6977. box.center( center );
  6978. // hoping to find a boundingSphere with a radius smaller than the
  6979. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  6980. var maxRadiusSq = 0;
  6981. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  6982. vector.fromArray( positions, i );
  6983. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  6984. }
  6985. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  6986. if ( isNaN( this.boundingSphere.radius ) ) {
  6987. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  6988. }
  6989. }
  6990. };
  6991. }(),
  6992. computeFaceNormals: function () {
  6993. // backwards compatibility
  6994. },
  6995. computeVertexNormals: function () {
  6996. var index = this.index;
  6997. var attributes = this.attributes;
  6998. var groups = this.groups;
  6999. if ( attributes.position ) {
  7000. var positions = attributes.position.array;
  7001. if ( attributes.normal === undefined ) {
  7002. this.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( positions.length ), 3 ) );
  7003. } else {
  7004. // reset existing normals to zero
  7005. var array = attributes.normal.array;
  7006. for ( var i = 0, il = array.length; i < il; i ++ ) {
  7007. array[ i ] = 0;
  7008. }
  7009. }
  7010. var normals = attributes.normal.array;
  7011. var vA, vB, vC,
  7012. pA = new THREE.Vector3(),
  7013. pB = new THREE.Vector3(),
  7014. pC = new THREE.Vector3(),
  7015. cb = new THREE.Vector3(),
  7016. ab = new THREE.Vector3();
  7017. // indexed elements
  7018. if ( index ) {
  7019. var indices = index.array;
  7020. if ( groups.length === 0 ) {
  7021. this.addGroup( 0, indices.length );
  7022. }
  7023. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  7024. var group = groups[ j ];
  7025. var start = group.start;
  7026. var count = group.count;
  7027. for ( var i = start, il = start + count; i < il; i += 3 ) {
  7028. vA = indices[ i + 0 ] * 3;
  7029. vB = indices[ i + 1 ] * 3;
  7030. vC = indices[ i + 2 ] * 3;
  7031. pA.fromArray( positions, vA );
  7032. pB.fromArray( positions, vB );
  7033. pC.fromArray( positions, vC );
  7034. cb.subVectors( pC, pB );
  7035. ab.subVectors( pA, pB );
  7036. cb.cross( ab );
  7037. normals[ vA ] += cb.x;
  7038. normals[ vA + 1 ] += cb.y;
  7039. normals[ vA + 2 ] += cb.z;
  7040. normals[ vB ] += cb.x;
  7041. normals[ vB + 1 ] += cb.y;
  7042. normals[ vB + 2 ] += cb.z;
  7043. normals[ vC ] += cb.x;
  7044. normals[ vC + 1 ] += cb.y;
  7045. normals[ vC + 2 ] += cb.z;
  7046. }
  7047. }
  7048. } else {
  7049. // non-indexed elements (unconnected triangle soup)
  7050. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  7051. pA.fromArray( positions, i );
  7052. pB.fromArray( positions, i + 3 );
  7053. pC.fromArray( positions, i + 6 );
  7054. cb.subVectors( pC, pB );
  7055. ab.subVectors( pA, pB );
  7056. cb.cross( ab );
  7057. normals[ i ] = cb.x;
  7058. normals[ i + 1 ] = cb.y;
  7059. normals[ i + 2 ] = cb.z;
  7060. normals[ i + 3 ] = cb.x;
  7061. normals[ i + 4 ] = cb.y;
  7062. normals[ i + 5 ] = cb.z;
  7063. normals[ i + 6 ] = cb.x;
  7064. normals[ i + 7 ] = cb.y;
  7065. normals[ i + 8 ] = cb.z;
  7066. }
  7067. }
  7068. this.normalizeNormals();
  7069. attributes.normal.needsUpdate = true;
  7070. }
  7071. },
  7072. merge: function ( geometry, offset ) {
  7073. if ( geometry instanceof THREE.BufferGeometry === false ) {
  7074. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  7075. return;
  7076. }
  7077. if ( offset === undefined ) offset = 0;
  7078. var attributes = this.attributes;
  7079. for ( var key in attributes ) {
  7080. if ( geometry.attributes[ key ] === undefined ) continue;
  7081. var attribute1 = attributes[ key ];
  7082. var attributeArray1 = attribute1.array;
  7083. var attribute2 = geometry.attributes[ key ];
  7084. var attributeArray2 = attribute2.array;
  7085. var attributeSize = attribute2.itemSize;
  7086. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  7087. attributeArray1[ j ] = attributeArray2[ i ];
  7088. }
  7089. }
  7090. return this;
  7091. },
  7092. normalizeNormals: function () {
  7093. var normals = this.attributes.normal.array;
  7094. var x, y, z, n;
  7095. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  7096. x = normals[ i ];
  7097. y = normals[ i + 1 ];
  7098. z = normals[ i + 2 ];
  7099. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  7100. normals[ i ] *= n;
  7101. normals[ i + 1 ] *= n;
  7102. normals[ i + 2 ] *= n;
  7103. }
  7104. },
  7105. toNonIndexed: function () {
  7106. if ( this.index === null ) {
  7107. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  7108. return this;
  7109. }
  7110. var geometry2 = new THREE.BufferGeometry();
  7111. var indices = this.index.array;
  7112. var attributes = this.attributes;
  7113. for ( var name in attributes ) {
  7114. var attribute = attributes[ name ];
  7115. var array = attribute.array;
  7116. var itemSize = attribute.itemSize;
  7117. var array2 = new array.constructor( indices.length * itemSize );
  7118. var index = 0, index2 = 0;
  7119. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  7120. index = indices[ i ] * itemSize;
  7121. for ( var j = 0; j < itemSize; j ++ ) {
  7122. array2[ index2 ++ ] = array[ index ++ ];
  7123. }
  7124. }
  7125. geometry2.addAttribute( name, new THREE.BufferAttribute( array2, itemSize ) );
  7126. }
  7127. return geometry2;
  7128. },
  7129. toJSON: function () {
  7130. var data = {
  7131. metadata: {
  7132. version: 4.4,
  7133. type: 'BufferGeometry',
  7134. generator: 'BufferGeometry.toJSON'
  7135. }
  7136. };
  7137. // standard BufferGeometry serialization
  7138. data.uuid = this.uuid;
  7139. data.type = this.type;
  7140. if ( this.name !== '' ) data.name = this.name;
  7141. if ( this.parameters !== undefined ) {
  7142. var parameters = this.parameters;
  7143. for ( var key in parameters ) {
  7144. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  7145. }
  7146. return data;
  7147. }
  7148. data.data = { attributes: {} };
  7149. var index = this.index;
  7150. if ( index !== null ) {
  7151. var array = Array.prototype.slice.call( index.array );
  7152. data.data.index = {
  7153. type: index.array.constructor.name,
  7154. array: array
  7155. };
  7156. }
  7157. var attributes = this.attributes;
  7158. for ( var key in attributes ) {
  7159. var attribute = attributes[ key ];
  7160. var array = Array.prototype.slice.call( attribute.array );
  7161. data.data.attributes[ key ] = {
  7162. itemSize: attribute.itemSize,
  7163. type: attribute.array.constructor.name,
  7164. array: array,
  7165. normalized: attribute.normalized
  7166. };
  7167. }
  7168. var groups = this.groups;
  7169. if ( groups.length > 0 ) {
  7170. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  7171. }
  7172. var boundingSphere = this.boundingSphere;
  7173. if ( boundingSphere !== null ) {
  7174. data.data.boundingSphere = {
  7175. center: boundingSphere.center.toArray(),
  7176. radius: boundingSphere.radius
  7177. };
  7178. }
  7179. return data;
  7180. },
  7181. clone: function () {
  7182. /*
  7183. // Handle primitives
  7184. var parameters = this.parameters;
  7185. if ( parameters !== undefined ) {
  7186. var values = [];
  7187. for ( var key in parameters ) {
  7188. values.push( parameters[ key ] );
  7189. }
  7190. var geometry = Object.create( this.constructor.prototype );
  7191. this.constructor.apply( geometry, values );
  7192. return geometry;
  7193. }
  7194. return new this.constructor().copy( this );
  7195. */
  7196. return new THREE.BufferGeometry().copy( this );
  7197. },
  7198. copy: function ( source ) {
  7199. var index = source.index;
  7200. if ( index !== null ) {
  7201. this.setIndex( index.clone() );
  7202. }
  7203. var attributes = source.attributes;
  7204. for ( var name in attributes ) {
  7205. var attribute = attributes[ name ];
  7206. this.addAttribute( name, attribute.clone() );
  7207. }
  7208. var groups = source.groups;
  7209. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7210. var group = groups[ i ];
  7211. this.addGroup( group.start, group.count, group.materialIndex );
  7212. }
  7213. return this;
  7214. },
  7215. dispose: function () {
  7216. this.dispatchEvent( { type: 'dispose' } );
  7217. }
  7218. };
  7219. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  7220. THREE.BufferGeometry.MaxIndex = 65535;
  7221. // File:src/core/InstancedBufferGeometry.js
  7222. /**
  7223. * @author benaadams / https://twitter.com/ben_a_adams
  7224. */
  7225. THREE.InstancedBufferGeometry = function () {
  7226. THREE.BufferGeometry.call( this );
  7227. this.type = 'InstancedBufferGeometry';
  7228. this.maxInstancedCount = undefined;
  7229. };
  7230. THREE.InstancedBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  7231. THREE.InstancedBufferGeometry.prototype.constructor = THREE.InstancedBufferGeometry;
  7232. THREE.InstancedBufferGeometry.prototype.addGroup = function ( start, count, instances ) {
  7233. this.groups.push( {
  7234. start: start,
  7235. count: count,
  7236. instances: instances
  7237. } );
  7238. };
  7239. THREE.InstancedBufferGeometry.prototype.copy = function ( source ) {
  7240. var index = source.index;
  7241. if ( index !== null ) {
  7242. this.setIndex( index.clone() );
  7243. }
  7244. var attributes = source.attributes;
  7245. for ( var name in attributes ) {
  7246. var attribute = attributes[ name ];
  7247. this.addAttribute( name, attribute.clone() );
  7248. }
  7249. var groups = source.groups;
  7250. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  7251. var group = groups[ i ];
  7252. this.addGroup( group.start, group.count, group.instances );
  7253. }
  7254. return this;
  7255. };
  7256. THREE.EventDispatcher.prototype.apply( THREE.InstancedBufferGeometry.prototype );
  7257. // File:src/core/Uniform.js
  7258. /**
  7259. * @author mrdoob / http://mrdoob.com/
  7260. */
  7261. THREE.Uniform = function ( value ) {
  7262. if ( typeof value === 'string' ) {
  7263. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  7264. value = arguments[ 1 ];
  7265. }
  7266. this.value = value;
  7267. this.dynamic = false;
  7268. };
  7269. THREE.Uniform.prototype = {
  7270. constructor: THREE.Uniform,
  7271. onUpdate: function ( callback ) {
  7272. this.dynamic = true;
  7273. this.onUpdateCallback = callback;
  7274. return this;
  7275. }
  7276. };
  7277. // File:src/animation/AnimationClip.js
  7278. /**
  7279. *
  7280. * Reusable set of Tracks that represent an animation.
  7281. *
  7282. * @author Ben Houston / http://clara.io/
  7283. * @author David Sarno / http://lighthaus.us/
  7284. */
  7285. THREE.AnimationClip = function ( name, duration, tracks ) {
  7286. this.name = name || THREE.Math.generateUUID();
  7287. this.tracks = tracks;
  7288. this.duration = ( duration !== undefined ) ? duration : -1;
  7289. // this means it should figure out its duration by scanning the tracks
  7290. if ( this.duration < 0 ) {
  7291. this.resetDuration();
  7292. }
  7293. // maybe only do these on demand, as doing them here could potentially slow down loading
  7294. // but leaving these here during development as this ensures a lot of testing of these functions
  7295. this.trim();
  7296. this.optimize();
  7297. };
  7298. THREE.AnimationClip.prototype = {
  7299. constructor: THREE.AnimationClip,
  7300. resetDuration: function() {
  7301. var tracks = this.tracks,
  7302. duration = 0;
  7303. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  7304. var track = this.tracks[ i ];
  7305. duration = Math.max(
  7306. duration, track.times[ track.times.length - 1 ] );
  7307. }
  7308. this.duration = duration;
  7309. },
  7310. trim: function() {
  7311. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7312. this.tracks[ i ].trim( 0, this.duration );
  7313. }
  7314. return this;
  7315. },
  7316. optimize: function() {
  7317. for ( var i = 0; i < this.tracks.length; i ++ ) {
  7318. this.tracks[ i ].optimize();
  7319. }
  7320. return this;
  7321. }
  7322. };
  7323. // Static methods:
  7324. Object.assign( THREE.AnimationClip, {
  7325. parse: function( json ) {
  7326. var tracks = [],
  7327. jsonTracks = json.tracks,
  7328. frameTime = 1.0 / ( json.fps || 1.0 );
  7329. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  7330. tracks.push( THREE.KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  7331. }
  7332. return new THREE.AnimationClip( json.name, json.duration, tracks );
  7333. },
  7334. toJSON: function( clip ) {
  7335. var tracks = [],
  7336. clipTracks = clip.tracks;
  7337. var json = {
  7338. 'name': clip.name,
  7339. 'duration': clip.duration,
  7340. 'tracks': tracks
  7341. };
  7342. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  7343. tracks.push( THREE.KeyframeTrack.toJSON( clipTracks[ i ] ) );
  7344. }
  7345. return json;
  7346. },
  7347. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  7348. var numMorphTargets = morphTargetSequence.length;
  7349. var tracks = [];
  7350. for ( var i = 0; i < numMorphTargets; i ++ ) {
  7351. var times = [];
  7352. var values = [];
  7353. times.push(
  7354. ( i + numMorphTargets - 1 ) % numMorphTargets,
  7355. i,
  7356. ( i + 1 ) % numMorphTargets );
  7357. values.push( 0, 1, 0 );
  7358. var order = THREE.AnimationUtils.getKeyframeOrder( times );
  7359. times = THREE.AnimationUtils.sortedArray( times, 1, order );
  7360. values = THREE.AnimationUtils.sortedArray( values, 1, order );
  7361. // if there is a key at the first frame, duplicate it as the
  7362. // last frame as well for perfect loop.
  7363. if ( ! noLoop && times[ 0 ] === 0 ) {
  7364. times.push( numMorphTargets );
  7365. values.push( values[ 0 ] );
  7366. }
  7367. tracks.push(
  7368. new THREE.NumberKeyframeTrack(
  7369. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  7370. times, values
  7371. ).scale( 1.0 / fps ) );
  7372. }
  7373. return new THREE.AnimationClip( name, -1, tracks );
  7374. },
  7375. findByName: function( clipArray, name ) {
  7376. for ( var i = 0; i < clipArray.length; i ++ ) {
  7377. if ( clipArray[ i ].name === name ) {
  7378. return clipArray[ i ];
  7379. }
  7380. }
  7381. return null;
  7382. },
  7383. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  7384. var animationToMorphTargets = {};
  7385. // tested with https://regex101.com/ on trick sequences
  7386. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  7387. var pattern = /^([\w-]*?)([\d]+)$/;
  7388. // sort morph target names into animation groups based
  7389. // patterns like Walk_001, Walk_002, Run_001, Run_002
  7390. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  7391. var morphTarget = morphTargets[ i ];
  7392. var parts = morphTarget.name.match( pattern );
  7393. if ( parts && parts.length > 1 ) {
  7394. var name = parts[ 1 ];
  7395. var animationMorphTargets = animationToMorphTargets[ name ];
  7396. if ( ! animationMorphTargets ) {
  7397. animationToMorphTargets[ name ] = animationMorphTargets = [];
  7398. }
  7399. animationMorphTargets.push( morphTarget );
  7400. }
  7401. }
  7402. var clips = [];
  7403. for ( var name in animationToMorphTargets ) {
  7404. clips.push( THREE.AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  7405. }
  7406. return clips;
  7407. },
  7408. // parse the animation.hierarchy format
  7409. parseAnimation: function( animation, bones, nodeName ) {
  7410. if ( ! animation ) {
  7411. console.error( " no animation in JSONLoader data" );
  7412. return null;
  7413. }
  7414. var addNonemptyTrack = function(
  7415. trackType, trackName, animationKeys, propertyName, destTracks ) {
  7416. // only return track if there are actually keys.
  7417. if ( animationKeys.length !== 0 ) {
  7418. var times = [];
  7419. var values = [];
  7420. THREE.AnimationUtils.flattenJSON(
  7421. animationKeys, times, values, propertyName );
  7422. // empty keys are filtered out, so check again
  7423. if ( times.length !== 0 ) {
  7424. destTracks.push( new trackType( trackName, times, values ) );
  7425. }
  7426. }
  7427. };
  7428. var tracks = [];
  7429. var clipName = animation.name || 'default';
  7430. // automatic length determination in AnimationClip.
  7431. var duration = animation.length || -1;
  7432. var fps = animation.fps || 30;
  7433. var hierarchyTracks = animation.hierarchy || [];
  7434. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  7435. var animationKeys = hierarchyTracks[ h ].keys;
  7436. // skip empty tracks
  7437. if ( ! animationKeys || animationKeys.length == 0 ) continue;
  7438. // process morph targets in a way exactly compatible
  7439. // with AnimationHandler.init( animation )
  7440. if ( animationKeys[0].morphTargets ) {
  7441. // figure out all morph targets used in this track
  7442. var morphTargetNames = {};
  7443. for ( var k = 0; k < animationKeys.length; k ++ ) {
  7444. if ( animationKeys[k].morphTargets ) {
  7445. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  7446. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  7447. }
  7448. }
  7449. }
  7450. // create a track for each morph target with all zero
  7451. // morphTargetInfluences except for the keys in which
  7452. // the morphTarget is named.
  7453. for ( var morphTargetName in morphTargetNames ) {
  7454. var times = [];
  7455. var values = [];
  7456. for ( var m = 0;
  7457. m !== animationKeys[k].morphTargets.length; ++ m ) {
  7458. var animationKey = animationKeys[k];
  7459. times.push( animationKey.time );
  7460. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 )
  7461. }
  7462. tracks.push( new THREE.NumberKeyframeTrack(
  7463. '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  7464. }
  7465. duration = morphTargetNames.length * ( fps || 1.0 );
  7466. } else {
  7467. // ...assume skeletal animation
  7468. var boneName = '.bones[' + bones[ h ].name + ']';
  7469. addNonemptyTrack(
  7470. THREE.VectorKeyframeTrack, boneName + '.position',
  7471. animationKeys, 'pos', tracks );
  7472. addNonemptyTrack(
  7473. THREE.QuaternionKeyframeTrack, boneName + '.quaternion',
  7474. animationKeys, 'rot', tracks );
  7475. addNonemptyTrack(
  7476. THREE.VectorKeyframeTrack, boneName + '.scale',
  7477. animationKeys, 'scl', tracks );
  7478. }
  7479. }
  7480. if ( tracks.length === 0 ) {
  7481. return null;
  7482. }
  7483. var clip = new THREE.AnimationClip( clipName, duration, tracks );
  7484. return clip;
  7485. }
  7486. } );
  7487. // File:src/animation/AnimationMixer.js
  7488. /**
  7489. *
  7490. * Player for AnimationClips.
  7491. *
  7492. *
  7493. * @author Ben Houston / http://clara.io/
  7494. * @author David Sarno / http://lighthaus.us/
  7495. * @author tschw
  7496. */
  7497. THREE.AnimationMixer = function( root ) {
  7498. this._root = root;
  7499. this._initMemoryManager();
  7500. this._accuIndex = 0;
  7501. this.time = 0;
  7502. this.timeScale = 1.0;
  7503. };
  7504. THREE.AnimationMixer.prototype = {
  7505. constructor: THREE.AnimationMixer,
  7506. // return an action for a clip optionally using a custom root target
  7507. // object (this method allocates a lot of dynamic memory in case a
  7508. // previously unknown clip/root combination is specified)
  7509. clipAction: function( clip, optionalRoot ) {
  7510. var root = optionalRoot || this._root,
  7511. rootUuid = root.uuid,
  7512. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7513. clipObject = ( clip !== clipName ) ? clip : null,
  7514. actionsForClip = this._actionsByClip[ clipName ],
  7515. prototypeAction;
  7516. if ( actionsForClip !== undefined ) {
  7517. var existingAction =
  7518. actionsForClip.actionByRoot[ rootUuid ];
  7519. if ( existingAction !== undefined ) {
  7520. return existingAction;
  7521. }
  7522. // we know the clip, so we don't have to parse all
  7523. // the bindings again but can just copy
  7524. prototypeAction = actionsForClip.knownActions[ 0 ];
  7525. // also, take the clip from the prototype action
  7526. clipObject = prototypeAction._clip;
  7527. if ( clip !== clipName && clip !== clipObject ) {
  7528. throw new Error(
  7529. "Different clips with the same name detected!" );
  7530. }
  7531. }
  7532. // clip must be known when specified via string
  7533. if ( clipObject === null ) return null;
  7534. // allocate all resources required to run it
  7535. var newAction = new THREE.
  7536. AnimationMixer._Action( this, clipObject, optionalRoot );
  7537. this._bindAction( newAction, prototypeAction );
  7538. // and make the action known to the memory manager
  7539. this._addInactiveAction( newAction, clipName, rootUuid );
  7540. return newAction;
  7541. },
  7542. // get an existing action
  7543. existingAction: function( clip, optionalRoot ) {
  7544. var root = optionalRoot || this._root,
  7545. rootUuid = root.uuid,
  7546. clipName = ( typeof clip === 'string' ) ? clip : clip.name,
  7547. actionsForClip = this._actionsByClip[ clipName ];
  7548. if ( actionsForClip !== undefined ) {
  7549. return actionsForClip.actionByRoot[ rootUuid ] || null;
  7550. }
  7551. return null;
  7552. },
  7553. // deactivates all previously scheduled actions
  7554. stopAllAction: function() {
  7555. var actions = this._actions,
  7556. nActions = this._nActiveActions,
  7557. bindings = this._bindings,
  7558. nBindings = this._nActiveBindings;
  7559. this._nActiveActions = 0;
  7560. this._nActiveBindings = 0;
  7561. for ( var i = 0; i !== nActions; ++ i ) {
  7562. actions[ i ].reset();
  7563. }
  7564. for ( var i = 0; i !== nBindings; ++ i ) {
  7565. bindings[ i ].useCount = 0;
  7566. }
  7567. return this;
  7568. },
  7569. // advance the time and update apply the animation
  7570. update: function( deltaTime ) {
  7571. deltaTime *= this.timeScale;
  7572. var actions = this._actions,
  7573. nActions = this._nActiveActions,
  7574. time = this.time += deltaTime,
  7575. timeDirection = Math.sign( deltaTime ),
  7576. accuIndex = this._accuIndex ^= 1;
  7577. // run active actions
  7578. for ( var i = 0; i !== nActions; ++ i ) {
  7579. var action = actions[ i ];
  7580. if ( action.enabled ) {
  7581. action._update( time, deltaTime, timeDirection, accuIndex );
  7582. }
  7583. }
  7584. // update scene graph
  7585. var bindings = this._bindings,
  7586. nBindings = this._nActiveBindings;
  7587. for ( var i = 0; i !== nBindings; ++ i ) {
  7588. bindings[ i ].apply( accuIndex );
  7589. }
  7590. return this;
  7591. },
  7592. // return this mixer's root target object
  7593. getRoot: function() {
  7594. return this._root;
  7595. },
  7596. // free all resources specific to a particular clip
  7597. uncacheClip: function( clip ) {
  7598. var actions = this._actions,
  7599. clipName = clip.name,
  7600. actionsByClip = this._actionsByClip,
  7601. actionsForClip = actionsByClip[ clipName ];
  7602. if ( actionsForClip !== undefined ) {
  7603. // note: just calling _removeInactiveAction would mess up the
  7604. // iteration state and also require updating the state we can
  7605. // just throw away
  7606. var actionsToRemove = actionsForClip.knownActions;
  7607. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  7608. var action = actionsToRemove[ i ];
  7609. this._deactivateAction( action );
  7610. var cacheIndex = action._cacheIndex,
  7611. lastInactiveAction = actions[ actions.length - 1 ];
  7612. action._cacheIndex = null;
  7613. action._byClipCacheIndex = null;
  7614. lastInactiveAction._cacheIndex = cacheIndex;
  7615. actions[ cacheIndex ] = lastInactiveAction;
  7616. actions.pop();
  7617. this._removeInactiveBindingsForAction( action );
  7618. }
  7619. delete actionsByClip[ clipName ];
  7620. }
  7621. },
  7622. // free all resources specific to a particular root target object
  7623. uncacheRoot: function( root ) {
  7624. var rootUuid = root.uuid,
  7625. actionsByClip = this._actionsByClip;
  7626. for ( var clipName in actionsByClip ) {
  7627. var actionByRoot = actionsByClip[ clipName ].actionByRoot,
  7628. action = actionByRoot[ rootUuid ];
  7629. if ( action !== undefined ) {
  7630. this._deactivateAction( action );
  7631. this._removeInactiveAction( action );
  7632. }
  7633. }
  7634. var bindingsByRoot = this._bindingsByRootAndName,
  7635. bindingByName = bindingsByRoot[ rootUuid ];
  7636. if ( bindingByName !== undefined ) {
  7637. for ( var trackName in bindingByName ) {
  7638. var binding = bindingByName[ trackName ];
  7639. binding.restoreOriginalState();
  7640. this._removeInactiveBinding( binding );
  7641. }
  7642. }
  7643. },
  7644. // remove a targeted clip from the cache
  7645. uncacheAction: function( clip, optionalRoot ) {
  7646. var action = this.existingAction( clip, optionalRoot );
  7647. if ( action !== null ) {
  7648. this._deactivateAction( action );
  7649. this._removeInactiveAction( action );
  7650. }
  7651. }
  7652. };
  7653. THREE.EventDispatcher.prototype.apply( THREE.AnimationMixer.prototype );
  7654. THREE.AnimationMixer._Action =
  7655. function( mixer, clip, localRoot ) {
  7656. this._mixer = mixer;
  7657. this._clip = clip;
  7658. this._localRoot = localRoot || null;
  7659. var tracks = clip.tracks,
  7660. nTracks = tracks.length,
  7661. interpolants = new Array( nTracks );
  7662. var interpolantSettings = {
  7663. endingStart: THREE.ZeroCurvatureEnding,
  7664. endingEnd: THREE.ZeroCurvatureEnding
  7665. };
  7666. for ( var i = 0; i !== nTracks; ++ i ) {
  7667. var interpolant = tracks[ i ].createInterpolant( null );
  7668. interpolants[ i ] = interpolant;
  7669. interpolant.settings = interpolantSettings
  7670. }
  7671. this._interpolantSettings = interpolantSettings;
  7672. this._interpolants = interpolants; // bound by the mixer
  7673. // inside: PropertyMixer (managed by the mixer)
  7674. this._propertyBindings = new Array( nTracks );
  7675. this._cacheIndex = null; // for the memory manager
  7676. this._byClipCacheIndex = null; // for the memory manager
  7677. this._timeScaleInterpolant = null;
  7678. this._weightInterpolant = null;
  7679. this.loop = THREE.LoopRepeat;
  7680. this._loopCount = -1;
  7681. // global mixer time when the action is to be started
  7682. // it's set back to 'null' upon start of the action
  7683. this._startTime = null;
  7684. // scaled local time of the action
  7685. // gets clamped or wrapped to 0..clip.duration according to loop
  7686. this.time = 0;
  7687. this.timeScale = 1;
  7688. this._effectiveTimeScale = 1;
  7689. this.weight = 1;
  7690. this._effectiveWeight = 1;
  7691. this.repetitions = Infinity; // no. of repetitions when looping
  7692. this.paused = false; // false -> zero effective time scale
  7693. this.enabled = true; // true -> zero effective weight
  7694. this.clampWhenFinished = false; // keep feeding the last frame?
  7695. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  7696. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  7697. };
  7698. THREE.AnimationMixer._Action.prototype = {
  7699. constructor: THREE.AnimationMixer._Action,
  7700. // State & Scheduling
  7701. play: function() {
  7702. this._mixer._activateAction( this );
  7703. return this;
  7704. },
  7705. stop: function() {
  7706. this._mixer._deactivateAction( this );
  7707. return this.reset();
  7708. },
  7709. reset: function() {
  7710. this.paused = false;
  7711. this.enabled = true;
  7712. this.time = 0; // restart clip
  7713. this._loopCount = -1; // forget previous loops
  7714. this._startTime = null; // forget scheduling
  7715. return this.stopFading().stopWarping();
  7716. },
  7717. isRunning: function() {
  7718. var start = this._startTime;
  7719. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  7720. this._startTime === null && this._mixer._isActiveAction( this )
  7721. },
  7722. // return true when play has been called
  7723. isScheduled: function() {
  7724. return this._mixer._isActiveAction( this );
  7725. },
  7726. startAt: function( time ) {
  7727. this._startTime = time;
  7728. return this;
  7729. },
  7730. setLoop: function( mode, repetitions ) {
  7731. this.loop = mode;
  7732. this.repetitions = repetitions;
  7733. return this;
  7734. },
  7735. // Weight
  7736. // set the weight stopping any scheduled fading
  7737. // although .enabled = false yields an effective weight of zero, this
  7738. // method does *not* change .enabled, because it would be confusing
  7739. setEffectiveWeight: function( weight ) {
  7740. this.weight = weight;
  7741. // note: same logic as when updated at runtime
  7742. this._effectiveWeight = this.enabled ? weight : 0;
  7743. return this.stopFading();
  7744. },
  7745. // return the weight considering fading and .enabled
  7746. getEffectiveWeight: function() {
  7747. return this._effectiveWeight;
  7748. },
  7749. fadeIn: function( duration ) {
  7750. return this._scheduleFading( duration, 0, 1 );
  7751. },
  7752. fadeOut: function( duration ) {
  7753. return this._scheduleFading( duration, 1, 0 );
  7754. },
  7755. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  7756. var mixer = this._mixer;
  7757. fadeOutAction.fadeOut( duration );
  7758. this.fadeIn( duration );
  7759. if( warp ) {
  7760. var fadeInDuration = this._clip.duration,
  7761. fadeOutDuration = fadeOutAction._clip.duration,
  7762. startEndRatio = fadeOutDuration / fadeInDuration,
  7763. endStartRatio = fadeInDuration / fadeOutDuration;
  7764. fadeOutAction.warp( 1.0, startEndRatio, duration );
  7765. this.warp( endStartRatio, 1.0, duration );
  7766. }
  7767. return this;
  7768. },
  7769. crossFadeTo: function( fadeInAction, duration, warp ) {
  7770. return fadeInAction.crossFadeFrom( this, duration, warp );
  7771. },
  7772. stopFading: function() {
  7773. var weightInterpolant = this._weightInterpolant;
  7774. if ( weightInterpolant !== null ) {
  7775. this._weightInterpolant = null;
  7776. this._mixer._takeBackControlInterpolant( weightInterpolant );
  7777. }
  7778. return this;
  7779. },
  7780. // Time Scale Control
  7781. // set the weight stopping any scheduled warping
  7782. // although .paused = true yields an effective time scale of zero, this
  7783. // method does *not* change .paused, because it would be confusing
  7784. setEffectiveTimeScale: function( timeScale ) {
  7785. this.timeScale = timeScale;
  7786. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  7787. return this.stopWarping();
  7788. },
  7789. // return the time scale considering warping and .paused
  7790. getEffectiveTimeScale: function() {
  7791. return this._effectiveTimeScale;
  7792. },
  7793. setDuration: function( duration ) {
  7794. this.timeScale = this._clip.duration / duration;
  7795. return this.stopWarping();
  7796. },
  7797. syncWith: function( action ) {
  7798. this.time = action.time;
  7799. this.timeScale = action.timeScale;
  7800. return this.stopWarping();
  7801. },
  7802. halt: function( duration ) {
  7803. return this.warp( this._currentTimeScale, 0, duration );
  7804. },
  7805. warp: function( startTimeScale, endTimeScale, duration ) {
  7806. var mixer = this._mixer, now = mixer.time,
  7807. interpolant = this._timeScaleInterpolant,
  7808. timeScale = this.timeScale;
  7809. if ( interpolant === null ) {
  7810. interpolant = mixer._lendControlInterpolant(),
  7811. this._timeScaleInterpolant = interpolant;
  7812. }
  7813. var times = interpolant.parameterPositions,
  7814. values = interpolant.sampleValues;
  7815. times[ 0 ] = now;
  7816. times[ 1 ] = now + duration;
  7817. values[ 0 ] = startTimeScale / timeScale;
  7818. values[ 1 ] = endTimeScale / timeScale;
  7819. return this;
  7820. },
  7821. stopWarping: function() {
  7822. var timeScaleInterpolant = this._timeScaleInterpolant;
  7823. if ( timeScaleInterpolant !== null ) {
  7824. this._timeScaleInterpolant = null;
  7825. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  7826. }
  7827. return this;
  7828. },
  7829. // Object Accessors
  7830. getMixer: function() {
  7831. return this._mixer;
  7832. },
  7833. getClip: function() {
  7834. return this._clip;
  7835. },
  7836. getRoot: function() {
  7837. return this._localRoot || this._mixer._root;
  7838. },
  7839. // Interna
  7840. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  7841. // called by the mixer
  7842. var startTime = this._startTime;
  7843. if ( startTime !== null ) {
  7844. // check for scheduled start of action
  7845. var timeRunning = ( time - startTime ) * timeDirection;
  7846. if ( timeRunning < 0 || timeDirection === 0 ) {
  7847. return; // yet to come / don't decide when delta = 0
  7848. }
  7849. // start
  7850. this._startTime = null; // unschedule
  7851. deltaTime = timeDirection * timeRunning;
  7852. }
  7853. // apply time scale and advance time
  7854. deltaTime *= this._updateTimeScale( time );
  7855. var clipTime = this._updateTime( deltaTime );
  7856. // note: _updateTime may disable the action resulting in
  7857. // an effective weight of 0
  7858. var weight = this._updateWeight( time );
  7859. if ( weight > 0 ) {
  7860. var interpolants = this._interpolants;
  7861. var propertyMixers = this._propertyBindings;
  7862. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  7863. interpolants[ j ].evaluate( clipTime );
  7864. propertyMixers[ j ].accumulate( accuIndex, weight );
  7865. }
  7866. }
  7867. },
  7868. _updateWeight: function( time ) {
  7869. var weight = 0;
  7870. if ( this.enabled ) {
  7871. weight = this.weight;
  7872. var interpolant = this._weightInterpolant;
  7873. if ( interpolant !== null ) {
  7874. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7875. weight *= interpolantValue;
  7876. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7877. this.stopFading();
  7878. if ( interpolantValue === 0 ) {
  7879. // faded out, disable
  7880. this.enabled = false;
  7881. }
  7882. }
  7883. }
  7884. }
  7885. this._effectiveWeight = weight;
  7886. return weight;
  7887. },
  7888. _updateTimeScale: function( time ) {
  7889. var timeScale = 0;
  7890. if ( ! this.paused ) {
  7891. timeScale = this.timeScale;
  7892. var interpolant = this._timeScaleInterpolant;
  7893. if ( interpolant !== null ) {
  7894. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  7895. timeScale *= interpolantValue;
  7896. if ( time > interpolant.parameterPositions[ 1 ] ) {
  7897. this.stopWarping();
  7898. if ( timeScale === 0 ) {
  7899. // motion has halted, pause
  7900. this.pause = true;
  7901. } else {
  7902. // warp done - apply final time scale
  7903. this.timeScale = timeScale;
  7904. }
  7905. }
  7906. }
  7907. }
  7908. this._effectiveTimeScale = timeScale;
  7909. return timeScale;
  7910. },
  7911. _updateTime: function( deltaTime ) {
  7912. var time = this.time + deltaTime;
  7913. if ( deltaTime === 0 ) return time;
  7914. var duration = this._clip.duration,
  7915. loop = this.loop,
  7916. loopCount = this._loopCount,
  7917. pingPong = false;
  7918. switch ( loop ) {
  7919. case THREE.LoopOnce:
  7920. if ( loopCount === -1 ) {
  7921. // just started
  7922. this.loopCount = 0;
  7923. this._setEndings( true, true, false );
  7924. }
  7925. if ( time >= duration ) {
  7926. time = duration;
  7927. } else if ( time < 0 ) {
  7928. time = 0;
  7929. } else break;
  7930. // reached the end
  7931. if ( this.clampWhenFinished ) this.pause = true;
  7932. else this.enabled = false;
  7933. this._mixer.dispatchEvent( {
  7934. type: 'finished', action: this,
  7935. direction: deltaTime < 0 ? -1 : 1
  7936. } );
  7937. break;
  7938. case THREE.LoopPingPong:
  7939. pingPong = true;
  7940. case THREE.LoopRepeat:
  7941. if ( loopCount === -1 ) {
  7942. // just started
  7943. if ( deltaTime > 0 ) {
  7944. loopCount = 0;
  7945. this._setEndings(
  7946. true, this.repetitions === 0, pingPong );
  7947. } else {
  7948. // when looping in reverse direction, the initial
  7949. // transition through zero counts as a repetition,
  7950. // so leave loopCount at -1
  7951. this._setEndings(
  7952. this.repetitions === 0, true, pingPong );
  7953. }
  7954. }
  7955. if ( time >= duration || time < 0 ) {
  7956. // wrap around
  7957. var loopDelta = Math.floor( time / duration ); // signed
  7958. time -= duration * loopDelta;
  7959. loopCount += Math.abs( loopDelta );
  7960. var pending = this.repetitions - loopCount;
  7961. if ( pending < 0 ) {
  7962. // stop (switch state, clamp time, fire event)
  7963. if ( this.clampWhenFinished ) this.paused = true;
  7964. else this.enabled = false;
  7965. time = deltaTime > 0 ? duration : 0;
  7966. this._mixer.dispatchEvent( {
  7967. type: 'finished', action: this,
  7968. direction: deltaTime > 0 ? 1 : -1
  7969. } );
  7970. break;
  7971. } else if ( pending === 0 ) {
  7972. // transition to last round
  7973. var atStart = deltaTime < 0;
  7974. this._setEndings( atStart, ! atStart, pingPong );
  7975. } else {
  7976. this._setEndings( false, false, pingPong );
  7977. }
  7978. this._loopCount = loopCount;
  7979. this._mixer.dispatchEvent( {
  7980. type: 'loop', action: this, loopDelta: loopDelta
  7981. } );
  7982. }
  7983. if ( loop === THREE.LoopPingPong && ( loopCount & 1 ) === 1 ) {
  7984. // invert time for the "pong round"
  7985. this.time = time;
  7986. return duration - time;
  7987. }
  7988. break;
  7989. }
  7990. this.time = time;
  7991. return time;
  7992. },
  7993. _setEndings: function( atStart, atEnd, pingPong ) {
  7994. var settings = this._interpolantSettings;
  7995. if ( pingPong ) {
  7996. settings.endingStart = THREE.ZeroSlopeEnding;
  7997. settings.endingEnd = THREE.ZeroSlopeEnding;
  7998. } else {
  7999. // assuming for LoopOnce atStart == atEnd == true
  8000. if ( atStart ) {
  8001. settings.endingStart = this.zeroSlopeAtStart ?
  8002. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  8003. } else {
  8004. settings.endingStart = THREE.WrapAroundEnding;
  8005. }
  8006. if ( atEnd ) {
  8007. settings.endingEnd = this.zeroSlopeAtEnd ?
  8008. THREE.ZeroSlopeEnding : THREE.ZeroCurvatureEnding;
  8009. } else {
  8010. settings.endingEnd = THREE.WrapAroundEnding;
  8011. }
  8012. }
  8013. },
  8014. _scheduleFading: function( duration, weightNow, weightThen ) {
  8015. var mixer = this._mixer, now = mixer.time,
  8016. interpolant = this._weightInterpolant;
  8017. if ( interpolant === null ) {
  8018. interpolant = mixer._lendControlInterpolant(),
  8019. this._weightInterpolant = interpolant;
  8020. }
  8021. var times = interpolant.parameterPositions,
  8022. values = interpolant.sampleValues;
  8023. times[ 0 ] = now; values[ 0 ] = weightNow;
  8024. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  8025. return this;
  8026. }
  8027. };
  8028. // Implementation details:
  8029. Object.assign( THREE.AnimationMixer.prototype, {
  8030. _bindAction: function( action, prototypeAction ) {
  8031. var root = action._localRoot || this._root,
  8032. tracks = action._clip.tracks,
  8033. nTracks = tracks.length,
  8034. bindings = action._propertyBindings,
  8035. interpolants = action._interpolants,
  8036. rootUuid = root.uuid,
  8037. bindingsByRoot = this._bindingsByRootAndName,
  8038. bindingsByName = bindingsByRoot[ rootUuid ];
  8039. if ( bindingsByName === undefined ) {
  8040. bindingsByName = {};
  8041. bindingsByRoot[ rootUuid ] = bindingsByName;
  8042. }
  8043. for ( var i = 0; i !== nTracks; ++ i ) {
  8044. var track = tracks[ i ],
  8045. trackName = track.name,
  8046. binding = bindingsByName[ trackName ];
  8047. if ( binding !== undefined ) {
  8048. bindings[ i ] = binding;
  8049. } else {
  8050. binding = bindings[ i ];
  8051. if ( binding !== undefined ) {
  8052. // existing binding, make sure the cache knows
  8053. if ( binding._cacheIndex === null ) {
  8054. ++ binding.referenceCount;
  8055. this._addInactiveBinding( binding, rootUuid, trackName );
  8056. }
  8057. continue;
  8058. }
  8059. var path = prototypeAction && prototypeAction.
  8060. _propertyBindings[ i ].binding.parsedPath;
  8061. binding = new THREE.PropertyMixer(
  8062. THREE.PropertyBinding.create( root, trackName, path ),
  8063. track.ValueTypeName, track.getValueSize() );
  8064. ++ binding.referenceCount;
  8065. this._addInactiveBinding( binding, rootUuid, trackName );
  8066. bindings[ i ] = binding;
  8067. }
  8068. interpolants[ i ].resultBuffer = binding.buffer;
  8069. }
  8070. },
  8071. _activateAction: function( action ) {
  8072. if ( ! this._isActiveAction( action ) ) {
  8073. if ( action._cacheIndex === null ) {
  8074. // this action has been forgotten by the cache, but the user
  8075. // appears to be still using it -> rebind
  8076. var rootUuid = ( action._localRoot || this._root ).uuid,
  8077. clipName = action._clip.name,
  8078. actionsForClip = this._actionsByClip[ clipName ];
  8079. this._bindAction( action,
  8080. actionsForClip && actionsForClip.knownActions[ 0 ] );
  8081. this._addInactiveAction( action, clipName, rootUuid );
  8082. }
  8083. var bindings = action._propertyBindings;
  8084. // increment reference counts / sort out state
  8085. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8086. var binding = bindings[ i ];
  8087. if ( binding.useCount ++ === 0 ) {
  8088. this._lendBinding( binding );
  8089. binding.saveOriginalState();
  8090. }
  8091. }
  8092. this._lendAction( action );
  8093. }
  8094. },
  8095. _deactivateAction: function( action ) {
  8096. if ( this._isActiveAction( action ) ) {
  8097. var bindings = action._propertyBindings;
  8098. // decrement reference counts / sort out state
  8099. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8100. var binding = bindings[ i ];
  8101. if ( -- binding.useCount === 0 ) {
  8102. binding.restoreOriginalState();
  8103. this._takeBackBinding( binding );
  8104. }
  8105. }
  8106. this._takeBackAction( action );
  8107. }
  8108. },
  8109. // Memory manager
  8110. _initMemoryManager: function() {
  8111. this._actions = []; // 'nActiveActions' followed by inactive ones
  8112. this._nActiveActions = 0;
  8113. this._actionsByClip = {};
  8114. // inside:
  8115. // {
  8116. // knownActions: Array< _Action > - used as prototypes
  8117. // actionByRoot: _Action - lookup
  8118. // }
  8119. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  8120. this._nActiveBindings = 0;
  8121. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  8122. this._controlInterpolants = []; // same game as above
  8123. this._nActiveControlInterpolants = 0;
  8124. var scope = this;
  8125. this.stats = {
  8126. actions: {
  8127. get total() { return scope._actions.length; },
  8128. get inUse() { return scope._nActiveActions; }
  8129. },
  8130. bindings: {
  8131. get total() { return scope._bindings.length; },
  8132. get inUse() { return scope._nActiveBindings; }
  8133. },
  8134. controlInterpolants: {
  8135. get total() { return scope._controlInterpolants.length; },
  8136. get inUse() { return scope._nActiveControlInterpolants; }
  8137. }
  8138. };
  8139. },
  8140. // Memory management for _Action objects
  8141. _isActiveAction: function( action ) {
  8142. var index = action._cacheIndex;
  8143. return index !== null && index < this._nActiveActions;
  8144. },
  8145. _addInactiveAction: function( action, clipName, rootUuid ) {
  8146. var actions = this._actions,
  8147. actionsByClip = this._actionsByClip,
  8148. actionsForClip = actionsByClip[ clipName ];
  8149. if ( actionsForClip === undefined ) {
  8150. actionsForClip = {
  8151. knownActions: [ action ],
  8152. actionByRoot: {}
  8153. };
  8154. action._byClipCacheIndex = 0;
  8155. actionsByClip[ clipName ] = actionsForClip;
  8156. } else {
  8157. var knownActions = actionsForClip.knownActions;
  8158. action._byClipCacheIndex = knownActions.length;
  8159. knownActions.push( action );
  8160. }
  8161. action._cacheIndex = actions.length;
  8162. actions.push( action );
  8163. actionsForClip.actionByRoot[ rootUuid ] = action;
  8164. },
  8165. _removeInactiveAction: function( action ) {
  8166. var actions = this._actions,
  8167. lastInactiveAction = actions[ actions.length - 1 ],
  8168. cacheIndex = action._cacheIndex;
  8169. lastInactiveAction._cacheIndex = cacheIndex;
  8170. actions[ cacheIndex ] = lastInactiveAction;
  8171. actions.pop();
  8172. action._cacheIndex = null;
  8173. var clipName = action._clip.name,
  8174. actionsByClip = this._actionsByClip,
  8175. actionsForClip = actionsByClip[ clipName ],
  8176. knownActionsForClip = actionsForClip.knownActions,
  8177. lastKnownAction =
  8178. knownActionsForClip[ knownActionsForClip.length - 1 ],
  8179. byClipCacheIndex = action._byClipCacheIndex;
  8180. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  8181. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  8182. knownActionsForClip.pop();
  8183. action._byClipCacheIndex = null;
  8184. var actionByRoot = actionsForClip.actionByRoot,
  8185. rootUuid = ( actions._localRoot || this._root ).uuid;
  8186. delete actionByRoot[ rootUuid ];
  8187. if ( knownActionsForClip.length === 0 ) {
  8188. delete actionsByClip[ clipName ];
  8189. }
  8190. this._removeInactiveBindingsForAction( action );
  8191. },
  8192. _removeInactiveBindingsForAction: function( action ) {
  8193. var bindings = action._propertyBindings;
  8194. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  8195. var binding = bindings[ i ];
  8196. if ( -- binding.referenceCount === 0 ) {
  8197. this._removeInactiveBinding( binding );
  8198. }
  8199. }
  8200. },
  8201. _lendAction: function( action ) {
  8202. // [ active actions | inactive actions ]
  8203. // [ active actions >| inactive actions ]
  8204. // s a
  8205. // <-swap->
  8206. // a s
  8207. var actions = this._actions,
  8208. prevIndex = action._cacheIndex,
  8209. lastActiveIndex = this._nActiveActions ++,
  8210. firstInactiveAction = actions[ lastActiveIndex ];
  8211. action._cacheIndex = lastActiveIndex;
  8212. actions[ lastActiveIndex ] = action;
  8213. firstInactiveAction._cacheIndex = prevIndex;
  8214. actions[ prevIndex ] = firstInactiveAction;
  8215. },
  8216. _takeBackAction: function( action ) {
  8217. // [ active actions | inactive actions ]
  8218. // [ active actions |< inactive actions ]
  8219. // a s
  8220. // <-swap->
  8221. // s a
  8222. var actions = this._actions,
  8223. prevIndex = action._cacheIndex,
  8224. firstInactiveIndex = -- this._nActiveActions,
  8225. lastActiveAction = actions[ firstInactiveIndex ];
  8226. action._cacheIndex = firstInactiveIndex;
  8227. actions[ firstInactiveIndex ] = action;
  8228. lastActiveAction._cacheIndex = prevIndex;
  8229. actions[ prevIndex ] = lastActiveAction;
  8230. },
  8231. // Memory management for PropertyMixer objects
  8232. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  8233. var bindingsByRoot = this._bindingsByRootAndName,
  8234. bindingByName = bindingsByRoot[ rootUuid ],
  8235. bindings = this._bindings;
  8236. if ( bindingByName === undefined ) {
  8237. bindingByName = {};
  8238. bindingsByRoot[ rootUuid ] = bindingByName;
  8239. }
  8240. bindingByName[ trackName ] = binding;
  8241. binding._cacheIndex = bindings.length;
  8242. bindings.push( binding );
  8243. },
  8244. _removeInactiveBinding: function( binding ) {
  8245. var bindings = this._bindings,
  8246. propBinding = binding.binding,
  8247. rootUuid = propBinding.rootNode.uuid,
  8248. trackName = propBinding.path,
  8249. bindingsByRoot = this._bindingsByRootAndName,
  8250. bindingByName = bindingsByRoot[ rootUuid ],
  8251. lastInactiveBinding = bindings[ bindings.length - 1 ],
  8252. cacheIndex = binding._cacheIndex;
  8253. lastInactiveBinding._cacheIndex = cacheIndex;
  8254. bindings[ cacheIndex ] = lastInactiveBinding;
  8255. bindings.pop();
  8256. delete bindingByName[ trackName ];
  8257. remove_empty_map: {
  8258. for ( var _ in bindingByName ) break remove_empty_map;
  8259. delete bindingsByRoot[ rootUuid ];
  8260. }
  8261. },
  8262. _lendBinding: function( binding ) {
  8263. var bindings = this._bindings,
  8264. prevIndex = binding._cacheIndex,
  8265. lastActiveIndex = this._nActiveBindings ++,
  8266. firstInactiveBinding = bindings[ lastActiveIndex ];
  8267. binding._cacheIndex = lastActiveIndex;
  8268. bindings[ lastActiveIndex ] = binding;
  8269. firstInactiveBinding._cacheIndex = prevIndex;
  8270. bindings[ prevIndex ] = firstInactiveBinding;
  8271. },
  8272. _takeBackBinding: function( binding ) {
  8273. var bindings = this._bindings,
  8274. prevIndex = binding._cacheIndex,
  8275. firstInactiveIndex = -- this._nActiveBindings,
  8276. lastActiveBinding = bindings[ firstInactiveIndex ];
  8277. binding._cacheIndex = firstInactiveIndex;
  8278. bindings[ firstInactiveIndex ] = binding;
  8279. lastActiveBinding._cacheIndex = prevIndex;
  8280. bindings[ prevIndex ] = lastActiveBinding;
  8281. },
  8282. // Memory management of Interpolants for weight and time scale
  8283. _lendControlInterpolant: function() {
  8284. var interpolants = this._controlInterpolants,
  8285. lastActiveIndex = this._nActiveControlInterpolants ++,
  8286. interpolant = interpolants[ lastActiveIndex ];
  8287. if ( interpolant === undefined ) {
  8288. interpolant = new THREE.LinearInterpolant(
  8289. new Float32Array( 2 ), new Float32Array( 2 ),
  8290. 1, this._controlInterpolantsResultBuffer );
  8291. interpolant.__cacheIndex = lastActiveIndex;
  8292. interpolants[ lastActiveIndex ] = interpolant;
  8293. }
  8294. return interpolant;
  8295. },
  8296. _takeBackControlInterpolant: function( interpolant ) {
  8297. var interpolants = this._controlInterpolants,
  8298. prevIndex = interpolant.__cacheIndex,
  8299. firstInactiveIndex = -- this._nActiveControlInterpolants,
  8300. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  8301. interpolant.__cacheIndex = firstInactiveIndex;
  8302. interpolants[ firstInactiveIndex ] = interpolant;
  8303. lastActiveInterpolant.__cacheIndex = prevIndex;
  8304. interpolants[ prevIndex ] = lastActiveInterpolant;
  8305. },
  8306. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  8307. } );
  8308. // File:src/animation/AnimationObjectGroup.js
  8309. /**
  8310. *
  8311. * A group of objects that receives a shared animation state.
  8312. *
  8313. * Usage:
  8314. *
  8315. * - Add objects you would otherwise pass as 'root' to the
  8316. * constructor or the .clipAction method of AnimationMixer.
  8317. *
  8318. * - Instead pass this object as 'root'.
  8319. *
  8320. * - You can also add and remove objects later when the mixer
  8321. * is running.
  8322. *
  8323. * Note:
  8324. *
  8325. * Objects of this class appear as one object to the mixer,
  8326. * so cache control of the individual objects must be done
  8327. * on the group.
  8328. *
  8329. * Limitation:
  8330. *
  8331. * - The animated properties must be compatible among the
  8332. * all objects in the group.
  8333. *
  8334. * - A single property can either be controlled through a
  8335. * target group or directly, but not both.
  8336. *
  8337. * @author tschw
  8338. */
  8339. THREE.AnimationObjectGroup = function( var_args ) {
  8340. this.uuid = THREE.Math.generateUUID();
  8341. // cached objects followed by the active ones
  8342. this._objects = Array.prototype.slice.call( arguments );
  8343. this.nCachedObjects_ = 0; // threshold
  8344. // note: read by PropertyBinding.Composite
  8345. var indices = {};
  8346. this._indicesByUUID = indices; // for bookkeeping
  8347. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8348. indices[ arguments[ i ].uuid ] = i;
  8349. }
  8350. this._paths = []; // inside: string
  8351. this._parsedPaths = []; // inside: { we don't care, here }
  8352. this._bindings = []; // inside: Array< PropertyBinding >
  8353. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  8354. var scope = this;
  8355. this.stats = {
  8356. objects: {
  8357. get total() { return scope._objects.length; },
  8358. get inUse() { return this.total - scope.nCachedObjects_; }
  8359. },
  8360. get bindingsPerObject() { return scope._bindings.length; }
  8361. };
  8362. };
  8363. THREE.AnimationObjectGroup.prototype = {
  8364. constructor: THREE.AnimationObjectGroup,
  8365. add: function( var_args ) {
  8366. var objects = this._objects,
  8367. nObjects = objects.length,
  8368. nCachedObjects = this.nCachedObjects_,
  8369. indicesByUUID = this._indicesByUUID,
  8370. paths = this._paths,
  8371. parsedPaths = this._parsedPaths,
  8372. bindings = this._bindings,
  8373. nBindings = bindings.length;
  8374. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8375. var object = arguments[ i ],
  8376. uuid = object.uuid,
  8377. index = indicesByUUID[ uuid ];
  8378. if ( index === undefined ) {
  8379. // unknown object -> add it to the ACTIVE region
  8380. index = nObjects ++;
  8381. indicesByUUID[ uuid ] = index;
  8382. objects.push( object );
  8383. // accounting is done, now do the same for all bindings
  8384. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8385. bindings[ j ].push(
  8386. new THREE.PropertyBinding(
  8387. object, paths[ j ], parsedPaths[ j ] ) );
  8388. }
  8389. } else if ( index < nCachedObjects ) {
  8390. var knownObject = objects[ index ];
  8391. // move existing object to the ACTIVE region
  8392. var firstActiveIndex = -- nCachedObjects,
  8393. lastCachedObject = objects[ firstActiveIndex ];
  8394. indicesByUUID[ lastCachedObject.uuid ] = index;
  8395. objects[ index ] = lastCachedObject;
  8396. indicesByUUID[ uuid ] = firstActiveIndex;
  8397. objects[ firstActiveIndex ] = object;
  8398. // accounting is done, now do the same for all bindings
  8399. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8400. var bindingsForPath = bindings[ j ],
  8401. lastCached = bindingsForPath[ firstActiveIndex ],
  8402. binding = bindingsForPath[ index ];
  8403. bindingsForPath[ index ] = lastCached;
  8404. if ( binding === undefined ) {
  8405. // since we do not bother to create new bindings
  8406. // for objects that are cached, the binding may
  8407. // or may not exist
  8408. binding = new THREE.PropertyBinding(
  8409. object, paths[ j ], parsedPaths[ j ] );
  8410. }
  8411. bindingsForPath[ firstActiveIndex ] = binding;
  8412. }
  8413. } else if ( objects[ index ] !== knownObject) {
  8414. console.error( "Different objects with the same UUID " +
  8415. "detected. Clean the caches or recreate your " +
  8416. "infrastructure when reloading scenes..." );
  8417. } // else the object is already where we want it to be
  8418. } // for arguments
  8419. this.nCachedObjects_ = nCachedObjects;
  8420. },
  8421. remove: function( var_args ) {
  8422. var objects = this._objects,
  8423. nObjects = objects.length,
  8424. nCachedObjects = this.nCachedObjects_,
  8425. indicesByUUID = this._indicesByUUID,
  8426. bindings = this._bindings,
  8427. nBindings = bindings.length;
  8428. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8429. var object = arguments[ i ],
  8430. uuid = object.uuid,
  8431. index = indicesByUUID[ uuid ];
  8432. if ( index !== undefined && index >= nCachedObjects ) {
  8433. // move existing object into the CACHED region
  8434. var lastCachedIndex = nCachedObjects ++,
  8435. firstActiveObject = objects[ lastCachedIndex ];
  8436. indicesByUUID[ firstActiveObject.uuid ] = index;
  8437. objects[ index ] = firstActiveObject;
  8438. indicesByUUID[ uuid ] = lastCachedIndex;
  8439. objects[ lastCachedIndex ] = object;
  8440. // accounting is done, now do the same for all bindings
  8441. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8442. var bindingsForPath = bindings[ j ],
  8443. firstActive = bindingsForPath[ lastCachedIndex ],
  8444. binding = bindingsForPath[ index ];
  8445. bindingsForPath[ index ] = firstActive;
  8446. bindingsForPath[ lastCachedIndex ] = binding;
  8447. }
  8448. }
  8449. } // for arguments
  8450. this.nCachedObjects_ = nCachedObjects;
  8451. },
  8452. // remove & forget
  8453. uncache: function( var_args ) {
  8454. var objects = this._objects,
  8455. nObjects = objects.length,
  8456. nCachedObjects = this.nCachedObjects_,
  8457. indicesByUUID = this._indicesByUUID,
  8458. bindings = this._bindings,
  8459. nBindings = bindings.length;
  8460. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  8461. var object = arguments[ i ],
  8462. uuid = object.uuid,
  8463. index = indicesByUUID[ uuid ];
  8464. if ( index !== undefined ) {
  8465. delete indicesByUUID[ uuid ];
  8466. if ( index < nCachedObjects ) {
  8467. // object is cached, shrink the CACHED region
  8468. var firstActiveIndex = -- nCachedObjects,
  8469. lastCachedObject = objects[ firstActiveIndex ],
  8470. lastIndex = -- nObjects,
  8471. lastObject = objects[ lastIndex ];
  8472. // last cached object takes this object's place
  8473. indicesByUUID[ lastCachedObject.uuid ] = index;
  8474. objects[ index ] = lastCachedObject;
  8475. // last object goes to the activated slot and pop
  8476. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  8477. objects[ firstActiveIndex ] = lastObject;
  8478. objects.pop();
  8479. // accounting is done, now do the same for all bindings
  8480. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8481. var bindingsForPath = bindings[ j ],
  8482. lastCached = bindingsForPath[ firstActiveIndex ],
  8483. last = bindingsForPath[ lastIndex ];
  8484. bindingsForPath[ index ] = lastCached;
  8485. bindingsForPath[ firstActiveIndex ] = last;
  8486. bindingsForPath.pop();
  8487. }
  8488. } else {
  8489. // object is active, just swap with the last and pop
  8490. var lastIndex = -- nObjects,
  8491. lastObject = objects[ lastIndex ];
  8492. indicesByUUID[ lastObject.uuid ] = index;
  8493. objects[ index ] = lastObject;
  8494. objects.pop();
  8495. // accounting is done, now do the same for all bindings
  8496. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  8497. var bindingsForPath = bindings[ j ];
  8498. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  8499. bindingsForPath.pop();
  8500. }
  8501. } // cached or active
  8502. } // if object is known
  8503. } // for arguments
  8504. this.nCachedObjects_ = nCachedObjects;
  8505. },
  8506. // Internal interface used by befriended PropertyBinding.Composite:
  8507. subscribe_: function( path, parsedPath ) {
  8508. // returns an array of bindings for the given path that is changed
  8509. // according to the contained objects in the group
  8510. var indicesByPath = this._bindingsIndicesByPath,
  8511. index = indicesByPath[ path ],
  8512. bindings = this._bindings;
  8513. if ( index !== undefined ) return bindings[ index ];
  8514. var paths = this._paths,
  8515. parsedPaths = this._parsedPaths,
  8516. objects = this._objects,
  8517. nObjects = objects.length,
  8518. nCachedObjects = this.nCachedObjects_,
  8519. bindingsForPath = new Array( nObjects );
  8520. index = bindings.length;
  8521. indicesByPath[ path ] = index;
  8522. paths.push( path );
  8523. parsedPaths.push( parsedPath );
  8524. bindings.push( bindingsForPath );
  8525. for ( var i = nCachedObjects,
  8526. n = objects.length; i !== n; ++ i ) {
  8527. var object = objects[ i ];
  8528. bindingsForPath[ i ] =
  8529. new THREE.PropertyBinding( object, path, parsedPath );
  8530. }
  8531. return bindingsForPath;
  8532. },
  8533. unsubscribe_: function( path ) {
  8534. // tells the group to forget about a property path and no longer
  8535. // update the array previously obtained with 'subscribe_'
  8536. var indicesByPath = this._bindingsIndicesByPath,
  8537. index = indicesByPath[ path ];
  8538. if ( index !== undefined ) {
  8539. var paths = this._paths,
  8540. parsedPaths = this._parsedPaths,
  8541. bindings = this._bindings,
  8542. lastBindingsIndex = bindings.length - 1,
  8543. lastBindings = bindings[ lastBindingsIndex ],
  8544. lastBindingsPath = path[ lastBindingsIndex ];
  8545. indicesByPath[ lastBindingsPath ] = index;
  8546. bindings[ index ] = lastBindings;
  8547. bindings.pop();
  8548. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  8549. parsedPaths.pop();
  8550. paths[ index ] = paths[ lastBindingsIndex ];
  8551. paths.pop();
  8552. }
  8553. }
  8554. };
  8555. // File:src/animation/AnimationUtils.js
  8556. /**
  8557. * @author tschw
  8558. * @author Ben Houston / http://clara.io/
  8559. * @author David Sarno / http://lighthaus.us/
  8560. */
  8561. THREE.AnimationUtils = {
  8562. // same as Array.prototype.slice, but also works on typed arrays
  8563. arraySlice: function( array, from, to ) {
  8564. if ( THREE.AnimationUtils.isTypedArray( array ) ) {
  8565. return new array.constructor( array.subarray( from, to ) );
  8566. }
  8567. return array.slice( from, to );
  8568. },
  8569. // converts an array to a specific type
  8570. convertArray: function( array, type, forceClone ) {
  8571. if ( ! array || // let 'undefined' and 'null' pass
  8572. ! forceClone && array.constructor === type ) return array;
  8573. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  8574. return new type( array ); // create typed array
  8575. }
  8576. return Array.prototype.slice.call( array ); // create Array
  8577. },
  8578. isTypedArray: function( object ) {
  8579. return ArrayBuffer.isView( object ) &&
  8580. ! ( object instanceof DataView );
  8581. },
  8582. // returns an array by which times and values can be sorted
  8583. getKeyframeOrder: function( times ) {
  8584. function compareTime( i, j ) {
  8585. return times[ i ] - times[ j ];
  8586. }
  8587. var n = times.length;
  8588. var result = new Array( n );
  8589. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  8590. result.sort( compareTime );
  8591. return result;
  8592. },
  8593. // uses the array previously returned by 'getKeyframeOrder' to sort data
  8594. sortedArray: function( values, stride, order ) {
  8595. var nValues = values.length;
  8596. var result = new values.constructor( nValues );
  8597. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  8598. var srcOffset = order[ i ] * stride;
  8599. for ( var j = 0; j !== stride; ++ j ) {
  8600. result[ dstOffset ++ ] = values[ srcOffset + j ];
  8601. }
  8602. }
  8603. return result;
  8604. },
  8605. // function for parsing AOS keyframe formats
  8606. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  8607. var i = 1, key = jsonKeys[ 0 ];
  8608. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  8609. key = jsonKeys[ i ++ ];
  8610. }
  8611. if ( key === undefined ) return; // no data
  8612. var value = key[ valuePropertyName ];
  8613. if ( value === undefined ) return; // no data
  8614. if ( Array.isArray( value ) ) {
  8615. do {
  8616. value = key[ valuePropertyName ];
  8617. if ( value !== undefined ) {
  8618. times.push( key.time );
  8619. values.push.apply( values, value ); // push all elements
  8620. }
  8621. key = jsonKeys[ i ++ ];
  8622. } while ( key !== undefined );
  8623. } else if ( value.toArray !== undefined ) {
  8624. // ...assume THREE.Math-ish
  8625. do {
  8626. value = key[ valuePropertyName ];
  8627. if ( value !== undefined ) {
  8628. times.push( key.time );
  8629. value.toArray( values, values.length );
  8630. }
  8631. key = jsonKeys[ i ++ ];
  8632. } while ( key !== undefined );
  8633. } else {
  8634. // otherwise push as-is
  8635. do {
  8636. value = key[ valuePropertyName ];
  8637. if ( value !== undefined ) {
  8638. times.push( key.time );
  8639. values.push( value );
  8640. }
  8641. key = jsonKeys[ i ++ ];
  8642. } while ( key !== undefined );
  8643. }
  8644. }
  8645. };
  8646. // File:src/animation/KeyframeTrack.js
  8647. /**
  8648. *
  8649. * A timed sequence of keyframes for a specific property.
  8650. *
  8651. *
  8652. * @author Ben Houston / http://clara.io/
  8653. * @author David Sarno / http://lighthaus.us/
  8654. * @author tschw
  8655. */
  8656. THREE.KeyframeTrack = function ( name, times, values, interpolation ) {
  8657. if( name === undefined ) throw new Error( "track name is undefined" );
  8658. if( times === undefined || times.length === 0 ) {
  8659. throw new Error( "no keyframes in track named " + name );
  8660. }
  8661. this.name = name;
  8662. this.times = THREE.AnimationUtils.convertArray( times, this.TimeBufferType );
  8663. this.values = THREE.AnimationUtils.convertArray( values, this.ValueBufferType );
  8664. this.setInterpolation( interpolation || this.DefaultInterpolation );
  8665. this.validate();
  8666. this.optimize();
  8667. };
  8668. THREE.KeyframeTrack.prototype = {
  8669. constructor: THREE.KeyframeTrack,
  8670. TimeBufferType: Float32Array,
  8671. ValueBufferType: Float32Array,
  8672. DefaultInterpolation: THREE.InterpolateLinear,
  8673. InterpolantFactoryMethodDiscrete: function( result ) {
  8674. return new THREE.DiscreteInterpolant(
  8675. this.times, this.values, this.getValueSize(), result );
  8676. },
  8677. InterpolantFactoryMethodLinear: function( result ) {
  8678. return new THREE.LinearInterpolant(
  8679. this.times, this.values, this.getValueSize(), result );
  8680. },
  8681. InterpolantFactoryMethodSmooth: function( result ) {
  8682. return new THREE.CubicInterpolant(
  8683. this.times, this.values, this.getValueSize(), result );
  8684. },
  8685. setInterpolation: function( interpolation ) {
  8686. var factoryMethod = undefined;
  8687. switch ( interpolation ) {
  8688. case THREE.InterpolateDiscrete:
  8689. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  8690. break;
  8691. case THREE.InterpolateLinear:
  8692. factoryMethod = this.InterpolantFactoryMethodLinear;
  8693. break;
  8694. case THREE.InterpolateSmooth:
  8695. factoryMethod = this.InterpolantFactoryMethodSmooth;
  8696. break;
  8697. }
  8698. if ( factoryMethod === undefined ) {
  8699. var message = "unsupported interpolation for " +
  8700. this.ValueTypeName + " keyframe track named " + this.name;
  8701. if ( this.createInterpolant === undefined ) {
  8702. // fall back to default, unless the default itself is messed up
  8703. if ( interpolation !== this.DefaultInterpolation ) {
  8704. this.setInterpolation( this.DefaultInterpolation );
  8705. } else {
  8706. throw new Error( message ); // fatal, in this case
  8707. }
  8708. }
  8709. console.warn( message );
  8710. return;
  8711. }
  8712. this.createInterpolant = factoryMethod;
  8713. },
  8714. getInterpolation: function() {
  8715. switch ( this.createInterpolant ) {
  8716. case this.InterpolantFactoryMethodDiscrete:
  8717. return THREE.InterpolateDiscrete;
  8718. case this.InterpolantFactoryMethodLinear:
  8719. return THREE.InterpolateLinear;
  8720. case this.InterpolantFactoryMethodSmooth:
  8721. return THREE.InterpolateSmooth;
  8722. }
  8723. },
  8724. getValueSize: function() {
  8725. return this.values.length / this.times.length;
  8726. },
  8727. // move all keyframes either forwards or backwards in time
  8728. shift: function( timeOffset ) {
  8729. if( timeOffset !== 0.0 ) {
  8730. var times = this.times;
  8731. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8732. times[ i ] += timeOffset;
  8733. }
  8734. }
  8735. return this;
  8736. },
  8737. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  8738. scale: function( timeScale ) {
  8739. if( timeScale !== 1.0 ) {
  8740. var times = this.times;
  8741. for( var i = 0, n = times.length; i !== n; ++ i ) {
  8742. times[ i ] *= timeScale;
  8743. }
  8744. }
  8745. return this;
  8746. },
  8747. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  8748. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  8749. trim: function( startTime, endTime ) {
  8750. var times = this.times,
  8751. nKeys = times.length,
  8752. from = 0,
  8753. to = nKeys - 1;
  8754. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  8755. while ( to !== -1 && times[ to ] > endTime ) -- to;
  8756. ++ to; // inclusive -> exclusive bound
  8757. if( from !== 0 || to !== nKeys ) {
  8758. // empty tracks are forbidden, so keep at least one keyframe
  8759. if ( from >= to ) to = Math.max( to , 1 ), from = to - 1;
  8760. var stride = this.getValueSize();
  8761. this.times = THREE.AnimationUtils.arraySlice( times, from, to );
  8762. this.values = THREE.AnimationUtils.
  8763. arraySlice( this.values, from * stride, to * stride );
  8764. }
  8765. return this;
  8766. },
  8767. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  8768. validate: function() {
  8769. var valid = true;
  8770. var valueSize = this.getValueSize();
  8771. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  8772. console.error( "invalid value size in track", this );
  8773. valid = false;
  8774. }
  8775. var times = this.times,
  8776. values = this.values,
  8777. nKeys = times.length;
  8778. if( nKeys === 0 ) {
  8779. console.error( "track is empty", this );
  8780. valid = false;
  8781. }
  8782. var prevTime = null;
  8783. for( var i = 0; i !== nKeys; i ++ ) {
  8784. var currTime = times[ i ];
  8785. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  8786. console.error( "time is not a valid number", this, i, currTime );
  8787. valid = false;
  8788. break;
  8789. }
  8790. if( prevTime !== null && prevTime > currTime ) {
  8791. console.error( "out of order keys", this, i, currTime, prevTime );
  8792. valid = false;
  8793. break;
  8794. }
  8795. prevTime = currTime;
  8796. }
  8797. if ( values !== undefined ) {
  8798. if ( THREE.AnimationUtils.isTypedArray( values ) ) {
  8799. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  8800. var value = values[ i ];
  8801. if ( isNaN( value ) ) {
  8802. console.error( "value is not a valid number", this, i, value );
  8803. valid = false;
  8804. break;
  8805. }
  8806. }
  8807. }
  8808. }
  8809. return valid;
  8810. },
  8811. // removes equivalent sequential keys as common in morph target sequences
  8812. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  8813. optimize: function() {
  8814. var times = this.times,
  8815. values = this.values,
  8816. stride = this.getValueSize(),
  8817. writeIndex = 1;
  8818. for( var i = 1, n = times.length - 1; i <= n; ++ i ) {
  8819. var keep = false;
  8820. var time = times[ i ];
  8821. var timeNext = times[ i + 1 ];
  8822. // remove adjacent keyframes scheduled at the same time
  8823. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  8824. // remove unnecessary keyframes same as their neighbors
  8825. var offset = i * stride,
  8826. offsetP = offset - stride,
  8827. offsetN = offset + stride;
  8828. for ( var j = 0; j !== stride; ++ j ) {
  8829. var value = values[ offset + j ];
  8830. if ( value !== values[ offsetP + j ] ||
  8831. value !== values[ offsetN + j ] ) {
  8832. keep = true;
  8833. break;
  8834. }
  8835. }
  8836. }
  8837. // in-place compaction
  8838. if ( keep ) {
  8839. if ( i !== writeIndex ) {
  8840. times[ writeIndex ] = times[ i ];
  8841. var readOffset = i * stride,
  8842. writeOffset = writeIndex * stride;
  8843. for ( var j = 0; j !== stride; ++ j ) {
  8844. values[ writeOffset + j ] = values[ readOffset + j ];
  8845. }
  8846. }
  8847. ++ writeIndex;
  8848. }
  8849. }
  8850. if ( writeIndex !== times.length ) {
  8851. this.times = THREE.AnimationUtils.arraySlice( times, 0, writeIndex );
  8852. this.values = THREE.AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  8853. }
  8854. return this;
  8855. }
  8856. };
  8857. // Static methods:
  8858. Object.assign( THREE.KeyframeTrack, {
  8859. // Serialization (in static context, because of constructor invocation
  8860. // and automatic invocation of .toJSON):
  8861. parse: function( json ) {
  8862. if( json.type === undefined ) {
  8863. throw new Error( "track type undefined, can not parse" );
  8864. }
  8865. var trackType = THREE.KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  8866. if ( json.times === undefined ) {
  8867. console.warn( "legacy JSON format detected, converting" );
  8868. var times = [], values = [];
  8869. THREE.AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  8870. json.times = times;
  8871. json.values = values;
  8872. }
  8873. // derived classes can define a static parse method
  8874. if ( trackType.parse !== undefined ) {
  8875. return trackType.parse( json );
  8876. } else {
  8877. // by default, we asssume a constructor compatible with the base
  8878. return new trackType(
  8879. json.name, json.times, json.values, json.interpolation );
  8880. }
  8881. },
  8882. toJSON: function( track ) {
  8883. var trackType = track.constructor;
  8884. var json;
  8885. // derived classes can define a static toJSON method
  8886. if ( trackType.toJSON !== undefined ) {
  8887. json = trackType.toJSON( track );
  8888. } else {
  8889. // by default, we assume the data can be serialized as-is
  8890. json = {
  8891. 'name': track.name,
  8892. 'times': THREE.AnimationUtils.convertArray( track.times, Array ),
  8893. 'values': THREE.AnimationUtils.convertArray( track.values, Array )
  8894. };
  8895. var interpolation = track.getInterpolation();
  8896. if ( interpolation !== track.DefaultInterpolation ) {
  8897. json.interpolation = interpolation;
  8898. }
  8899. }
  8900. json.type = track.ValueTypeName; // mandatory
  8901. return json;
  8902. },
  8903. _getTrackTypeForValueTypeName: function( typeName ) {
  8904. switch( typeName.toLowerCase() ) {
  8905. case "scalar":
  8906. case "double":
  8907. case "float":
  8908. case "number":
  8909. case "integer":
  8910. return THREE.NumberKeyframeTrack;
  8911. case "vector":
  8912. case "vector2":
  8913. case "vector3":
  8914. case "vector4":
  8915. return THREE.VectorKeyframeTrack;
  8916. case "color":
  8917. return THREE.ColorKeyframeTrack;
  8918. case "quaternion":
  8919. return THREE.QuaternionKeyframeTrack;
  8920. case "bool":
  8921. case "boolean":
  8922. return THREE.BooleanKeyframeTrack;
  8923. case "string":
  8924. return THREE.StringKeyframeTrack;
  8925. };
  8926. throw new Error( "Unsupported typeName: " + typeName );
  8927. }
  8928. } );
  8929. // File:src/animation/PropertyBinding.js
  8930. /**
  8931. *
  8932. * A reference to a real property in the scene graph.
  8933. *
  8934. *
  8935. * @author Ben Houston / http://clara.io/
  8936. * @author David Sarno / http://lighthaus.us/
  8937. * @author tschw
  8938. */
  8939. THREE.PropertyBinding = function ( rootNode, path, parsedPath ) {
  8940. this.path = path;
  8941. this.parsedPath = parsedPath ||
  8942. THREE.PropertyBinding.parseTrackName( path );
  8943. this.node = THREE.PropertyBinding.findNode(
  8944. rootNode, this.parsedPath.nodeName ) || rootNode;
  8945. this.rootNode = rootNode;
  8946. };
  8947. THREE.PropertyBinding.prototype = {
  8948. constructor: THREE.PropertyBinding,
  8949. getValue: function getValue_unbound( targetArray, offset ) {
  8950. this.bind();
  8951. this.getValue( targetArray, offset );
  8952. // Note: This class uses a State pattern on a per-method basis:
  8953. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  8954. // prototype version of these methods with one that represents
  8955. // the bound state. When the property is not found, the methods
  8956. // become no-ops.
  8957. },
  8958. setValue: function getValue_unbound( sourceArray, offset ) {
  8959. this.bind();
  8960. this.setValue( sourceArray, offset );
  8961. },
  8962. // create getter / setter pair for a property in the scene graph
  8963. bind: function() {
  8964. var targetObject = this.node,
  8965. parsedPath = this.parsedPath,
  8966. objectName = parsedPath.objectName,
  8967. propertyName = parsedPath.propertyName,
  8968. propertyIndex = parsedPath.propertyIndex;
  8969. if ( ! targetObject ) {
  8970. targetObject = THREE.PropertyBinding.findNode(
  8971. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  8972. this.node = targetObject;
  8973. }
  8974. // set fail state so we can just 'return' on error
  8975. this.getValue = this._getValue_unavailable;
  8976. this.setValue = this._setValue_unavailable;
  8977. // ensure there is a value node
  8978. if ( ! targetObject ) {
  8979. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  8980. return;
  8981. }
  8982. if( objectName ) {
  8983. var objectIndex = parsedPath.objectIndex;
  8984. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  8985. switch ( objectName ) {
  8986. case 'materials':
  8987. if( ! targetObject.material ) {
  8988. console.error( ' can not bind to material as node does not have a material', this );
  8989. return;
  8990. }
  8991. if( ! targetObject.material.materials ) {
  8992. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  8993. return;
  8994. }
  8995. targetObject = targetObject.material.materials;
  8996. break;
  8997. case 'bones':
  8998. if( ! targetObject.skeleton ) {
  8999. console.error( ' can not bind to bones as node does not have a skeleton', this );
  9000. return;
  9001. }
  9002. // potential future optimization: skip this if propertyIndex is already an integer
  9003. // and convert the integer string to a true integer.
  9004. targetObject = targetObject.skeleton.bones;
  9005. // support resolving morphTarget names into indices.
  9006. for ( var i = 0; i < targetObject.length; i ++ ) {
  9007. if ( targetObject[i].name === objectIndex ) {
  9008. objectIndex = i;
  9009. break;
  9010. }
  9011. }
  9012. break;
  9013. default:
  9014. if ( targetObject[ objectName ] === undefined ) {
  9015. console.error( ' can not bind to objectName of node, undefined', this );
  9016. return;
  9017. }
  9018. targetObject = targetObject[ objectName ];
  9019. }
  9020. if ( objectIndex !== undefined ) {
  9021. if( targetObject[ objectIndex ] === undefined ) {
  9022. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  9023. return;
  9024. }
  9025. targetObject = targetObject[ objectIndex ];
  9026. }
  9027. }
  9028. // resolve property
  9029. var nodeProperty = targetObject[ propertyName ];
  9030. if ( ! nodeProperty ) {
  9031. var nodeName = parsedPath.nodeName;
  9032. console.error( " trying to update property for track: " + nodeName +
  9033. '.' + propertyName + " but it wasn't found.", targetObject );
  9034. return;
  9035. }
  9036. // determine versioning scheme
  9037. var versioning = this.Versioning.None;
  9038. if ( targetObject.needsUpdate !== undefined ) { // material
  9039. versioning = this.Versioning.NeedsUpdate;
  9040. this.targetObject = targetObject;
  9041. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  9042. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  9043. this.targetObject = targetObject;
  9044. }
  9045. // determine how the property gets bound
  9046. var bindingType = this.BindingType.Direct;
  9047. if ( propertyIndex !== undefined ) {
  9048. // access a sub element of the property array (only primitives are supported right now)
  9049. if ( propertyName === "morphTargetInfluences" ) {
  9050. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  9051. // support resolving morphTarget names into indices.
  9052. if ( ! targetObject.geometry ) {
  9053. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  9054. return;
  9055. }
  9056. if ( ! targetObject.geometry.morphTargets ) {
  9057. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  9058. return;
  9059. }
  9060. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  9061. if ( targetObject.geometry.morphTargets[i].name === propertyIndex ) {
  9062. propertyIndex = i;
  9063. break;
  9064. }
  9065. }
  9066. }
  9067. bindingType = this.BindingType.ArrayElement;
  9068. this.resolvedProperty = nodeProperty;
  9069. this.propertyIndex = propertyIndex;
  9070. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  9071. // must use copy for Object3D.Euler/Quaternion
  9072. bindingType = this.BindingType.HasFromToArray;
  9073. this.resolvedProperty = nodeProperty;
  9074. } else if ( nodeProperty.length !== undefined ) {
  9075. bindingType = this.BindingType.EntireArray;
  9076. this.resolvedProperty = nodeProperty;
  9077. } else {
  9078. this.propertyName = propertyName;
  9079. }
  9080. // select getter / setter
  9081. this.getValue = this.GetterByBindingType[ bindingType ];
  9082. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  9083. },
  9084. unbind: function() {
  9085. this.node = null;
  9086. // back to the prototype version of getValue / setValue
  9087. // note: avoiding to mutate the shape of 'this' via 'delete'
  9088. this.getValue = this._getValue_unbound;
  9089. this.setValue = this._setValue_unbound;
  9090. }
  9091. };
  9092. Object.assign( THREE.PropertyBinding.prototype, { // prototype, continued
  9093. // these are used to "bind" a nonexistent property
  9094. _getValue_unavailable: function() {},
  9095. _setValue_unavailable: function() {},
  9096. // initial state of these methods that calls 'bind'
  9097. _getValue_unbound: THREE.PropertyBinding.prototype.getValue,
  9098. _setValue_unbound: THREE.PropertyBinding.prototype.setValue,
  9099. BindingType: {
  9100. Direct: 0,
  9101. EntireArray: 1,
  9102. ArrayElement: 2,
  9103. HasFromToArray: 3
  9104. },
  9105. Versioning: {
  9106. None: 0,
  9107. NeedsUpdate: 1,
  9108. MatrixWorldNeedsUpdate: 2
  9109. },
  9110. GetterByBindingType: [
  9111. function getValue_direct( buffer, offset ) {
  9112. buffer[ offset ] = this.node[ this.propertyName ];
  9113. },
  9114. function getValue_array( buffer, offset ) {
  9115. var source = this.resolvedProperty;
  9116. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  9117. buffer[ offset ++ ] = source[ i ];
  9118. }
  9119. },
  9120. function getValue_arrayElement( buffer, offset ) {
  9121. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  9122. },
  9123. function getValue_toArray( buffer, offset ) {
  9124. this.resolvedProperty.toArray( buffer, offset );
  9125. }
  9126. ],
  9127. SetterByBindingTypeAndVersioning: [
  9128. [
  9129. // Direct
  9130. function setValue_direct( buffer, offset ) {
  9131. this.node[ this.propertyName ] = buffer[ offset ];
  9132. },
  9133. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  9134. this.node[ this.propertyName ] = buffer[ offset ];
  9135. this.targetObject.needsUpdate = true;
  9136. },
  9137. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9138. this.node[ this.propertyName ] = buffer[ offset ];
  9139. this.targetObject.matrixWorldNeedsUpdate = true;
  9140. }
  9141. ], [
  9142. // EntireArray
  9143. function setValue_array( buffer, offset ) {
  9144. var dest = this.resolvedProperty;
  9145. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9146. dest[ i ] = buffer[ offset ++ ];
  9147. }
  9148. },
  9149. function setValue_array_setNeedsUpdate( buffer, offset ) {
  9150. var dest = this.resolvedProperty;
  9151. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9152. dest[ i ] = buffer[ offset ++ ];
  9153. }
  9154. this.targetObject.needsUpdate = true;
  9155. },
  9156. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9157. var dest = this.resolvedProperty;
  9158. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  9159. dest[ i ] = buffer[ offset ++ ];
  9160. }
  9161. this.targetObject.matrixWorldNeedsUpdate = true;
  9162. }
  9163. ], [
  9164. // ArrayElement
  9165. function setValue_arrayElement( buffer, offset ) {
  9166. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9167. },
  9168. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  9169. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9170. this.targetObject.needsUpdate = true;
  9171. },
  9172. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9173. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  9174. this.targetObject.matrixWorldNeedsUpdate = true;
  9175. }
  9176. ], [
  9177. // HasToFromArray
  9178. function setValue_fromArray( buffer, offset ) {
  9179. this.resolvedProperty.fromArray( buffer, offset );
  9180. },
  9181. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  9182. this.resolvedProperty.fromArray( buffer, offset );
  9183. this.targetObject.needsUpdate = true;
  9184. },
  9185. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  9186. this.resolvedProperty.fromArray( buffer, offset );
  9187. this.targetObject.matrixWorldNeedsUpdate = true;
  9188. }
  9189. ]
  9190. ]
  9191. } );
  9192. THREE.PropertyBinding.Composite =
  9193. function( targetGroup, path, optionalParsedPath ) {
  9194. var parsedPath = optionalParsedPath ||
  9195. THREE.PropertyBinding.parseTrackName( path );
  9196. this._targetGroup = targetGroup;
  9197. this._bindings = targetGroup.subscribe_( path, parsedPath );
  9198. };
  9199. THREE.PropertyBinding.Composite.prototype = {
  9200. constructor: THREE.PropertyBinding.Composite,
  9201. getValue: function( array, offset ) {
  9202. this.bind(); // bind all binding
  9203. var firstValidIndex = this._targetGroup.nCachedObjects_,
  9204. binding = this._bindings[ firstValidIndex ];
  9205. // and only call .getValue on the first
  9206. if ( binding !== undefined ) binding.getValue( array, offset );
  9207. },
  9208. setValue: function( array, offset ) {
  9209. var bindings = this._bindings;
  9210. for ( var i = this._targetGroup.nCachedObjects_,
  9211. n = bindings.length; i !== n; ++ i ) {
  9212. bindings[ i ].setValue( array, offset );
  9213. }
  9214. },
  9215. bind: function() {
  9216. var bindings = this._bindings;
  9217. for ( var i = this._targetGroup.nCachedObjects_,
  9218. n = bindings.length; i !== n; ++ i ) {
  9219. bindings[ i ].bind();
  9220. }
  9221. },
  9222. unbind: function() {
  9223. var bindings = this._bindings;
  9224. for ( var i = this._targetGroup.nCachedObjects_,
  9225. n = bindings.length; i !== n; ++ i ) {
  9226. bindings[ i ].unbind();
  9227. }
  9228. }
  9229. };
  9230. THREE.PropertyBinding.create = function( root, path, parsedPath ) {
  9231. if ( ! ( root instanceof THREE.AnimationObjectGroup ) ) {
  9232. return new THREE.PropertyBinding( root, path, parsedPath );
  9233. } else {
  9234. return new THREE.PropertyBinding.Composite( root, path, parsedPath );
  9235. }
  9236. };
  9237. THREE.PropertyBinding.parseTrackName = function( trackName ) {
  9238. // matches strings in the form of:
  9239. // nodeName.property
  9240. // nodeName.property[accessor]
  9241. // nodeName.material.property[accessor]
  9242. // uuid.property[accessor]
  9243. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  9244. // parentName/nodeName.property
  9245. // parentName/parentName/nodeName.property[index]
  9246. // .bone[Armature.DEF_cog].position
  9247. // created and tested via https://regex101.com/#javascript
  9248. var re = /^(([\w]+\/)*)([\w-\d]+)?(\.([\w]+)(\[([\w\d\[\]\_.:\- ]+)\])?)?(\.([\w.]+)(\[([\w\d\[\]\_. ]+)\])?)$/;
  9249. var matches = re.exec(trackName);
  9250. if( ! matches ) {
  9251. throw new Error( "cannot parse trackName at all: " + trackName );
  9252. }
  9253. if (matches.index === re.lastIndex) {
  9254. re.lastIndex++;
  9255. }
  9256. var results = {
  9257. // directoryName: matches[1], // (tschw) currently unused
  9258. nodeName: matches[3], // allowed to be null, specified root node.
  9259. objectName: matches[5],
  9260. objectIndex: matches[7],
  9261. propertyName: matches[9],
  9262. propertyIndex: matches[11] // allowed to be null, specifies that the whole property is set.
  9263. };
  9264. if( results.propertyName === null || results.propertyName.length === 0 ) {
  9265. throw new Error( "can not parse propertyName from trackName: " + trackName );
  9266. }
  9267. return results;
  9268. };
  9269. THREE.PropertyBinding.findNode = function( root, nodeName ) {
  9270. if( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  9271. return root;
  9272. }
  9273. // search into skeleton bones.
  9274. if( root.skeleton ) {
  9275. var searchSkeleton = function( skeleton ) {
  9276. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  9277. var bone = skeleton.bones[i];
  9278. if( bone.name === nodeName ) {
  9279. return bone;
  9280. }
  9281. }
  9282. return null;
  9283. };
  9284. var bone = searchSkeleton( root.skeleton );
  9285. if( bone ) {
  9286. return bone;
  9287. }
  9288. }
  9289. // search into node subtree.
  9290. if( root.children ) {
  9291. var searchNodeSubtree = function( children ) {
  9292. for( var i = 0; i < children.length; i ++ ) {
  9293. var childNode = children[i];
  9294. if( childNode.name === nodeName || childNode.uuid === nodeName ) {
  9295. return childNode;
  9296. }
  9297. var result = searchNodeSubtree( childNode.children );
  9298. if( result ) return result;
  9299. }
  9300. return null;
  9301. };
  9302. var subTreeNode = searchNodeSubtree( root.children );
  9303. if( subTreeNode ) {
  9304. return subTreeNode;
  9305. }
  9306. }
  9307. return null;
  9308. }
  9309. // File:src/animation/PropertyMixer.js
  9310. /**
  9311. *
  9312. * Buffered scene graph property that allows weighted accumulation.
  9313. *
  9314. *
  9315. * @author Ben Houston / http://clara.io/
  9316. * @author David Sarno / http://lighthaus.us/
  9317. * @author tschw
  9318. */
  9319. THREE.PropertyMixer = function ( binding, typeName, valueSize ) {
  9320. this.binding = binding;
  9321. this.valueSize = valueSize;
  9322. var bufferType = Float64Array,
  9323. mixFunction;
  9324. switch ( typeName ) {
  9325. case 'quaternion': mixFunction = this._slerp; break;
  9326. case 'string':
  9327. case 'bool':
  9328. bufferType = Array, mixFunction = this._select; break;
  9329. default: mixFunction = this._lerp;
  9330. }
  9331. this.buffer = new bufferType( valueSize * 4 );
  9332. // layout: [ incoming | accu0 | accu1 | orig ]
  9333. //
  9334. // interpolators can use .buffer as their .result
  9335. // the data then goes to 'incoming'
  9336. //
  9337. // 'accu0' and 'accu1' are used frame-interleaved for
  9338. // the cumulative result and are compared to detect
  9339. // changes
  9340. //
  9341. // 'orig' stores the original state of the property
  9342. this._mixBufferRegion = mixFunction;
  9343. this.cumulativeWeight = 0;
  9344. this.useCount = 0;
  9345. this.referenceCount = 0;
  9346. };
  9347. THREE.PropertyMixer.prototype = {
  9348. constructor: THREE.PropertyMixer,
  9349. // accumulate data in the 'incoming' region into 'accu<i>'
  9350. accumulate: function( accuIndex, weight ) {
  9351. // note: happily accumulating nothing when weight = 0, the caller knows
  9352. // the weight and shouldn't have made the call in the first place
  9353. var buffer = this.buffer,
  9354. stride = this.valueSize,
  9355. offset = accuIndex * stride + stride,
  9356. currentWeight = this.cumulativeWeight;
  9357. if ( currentWeight === 0 ) {
  9358. // accuN := incoming * weight
  9359. for ( var i = 0; i !== stride; ++ i ) {
  9360. buffer[ offset + i ] = buffer[ i ];
  9361. }
  9362. currentWeight = weight;
  9363. } else {
  9364. // accuN := accuN + incoming * weight
  9365. currentWeight += weight;
  9366. var mix = weight / currentWeight;
  9367. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  9368. }
  9369. this.cumulativeWeight = currentWeight;
  9370. },
  9371. // apply the state of 'accu<i>' to the binding when accus differ
  9372. apply: function( accuIndex ) {
  9373. var stride = this.valueSize,
  9374. buffer = this.buffer,
  9375. offset = accuIndex * stride + stride,
  9376. weight = this.cumulativeWeight,
  9377. binding = this.binding;
  9378. this.cumulativeWeight = 0;
  9379. if ( weight < 1 ) {
  9380. // accuN := accuN + original * ( 1 - cumulativeWeight )
  9381. var originalValueOffset = stride * 3;
  9382. this._mixBufferRegion(
  9383. buffer, offset, originalValueOffset, 1 - weight, stride );
  9384. }
  9385. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  9386. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  9387. // value has changed -> update scene graph
  9388. binding.setValue( buffer, offset );
  9389. break;
  9390. }
  9391. }
  9392. },
  9393. // remember the state of the bound property and copy it to both accus
  9394. saveOriginalState: function() {
  9395. var binding = this.binding;
  9396. var buffer = this.buffer,
  9397. stride = this.valueSize,
  9398. originalValueOffset = stride * 3;
  9399. binding.getValue( buffer, originalValueOffset );
  9400. // accu[0..1] := orig -- initially detect changes against the original
  9401. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  9402. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  9403. }
  9404. this.cumulativeWeight = 0;
  9405. },
  9406. // apply the state previously taken via 'saveOriginalState' to the binding
  9407. restoreOriginalState: function() {
  9408. var originalValueOffset = this.valueSize * 3;
  9409. this.binding.setValue( this.buffer, originalValueOffset );
  9410. },
  9411. // mix functions
  9412. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  9413. if ( t >= 0.5 ) {
  9414. for ( var i = 0; i !== stride; ++ i ) {
  9415. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  9416. }
  9417. }
  9418. },
  9419. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9420. THREE.Quaternion.slerpFlat( buffer, dstOffset,
  9421. buffer, dstOffset, buffer, srcOffset, t );
  9422. },
  9423. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  9424. var s = 1 - t;
  9425. for ( var i = 0; i !== stride; ++ i ) {
  9426. var j = dstOffset + i;
  9427. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  9428. }
  9429. }
  9430. };
  9431. // File:src/animation/tracks/BooleanKeyframeTrack.js
  9432. /**
  9433. *
  9434. * A Track of Boolean keyframe values.
  9435. *
  9436. *
  9437. * @author Ben Houston / http://clara.io/
  9438. * @author David Sarno / http://lighthaus.us/
  9439. * @author tschw
  9440. */
  9441. THREE.BooleanKeyframeTrack = function ( name, times, values ) {
  9442. THREE.KeyframeTrack.call( this, name, times, values );
  9443. };
  9444. THREE.BooleanKeyframeTrack.prototype =
  9445. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9446. constructor: THREE.BooleanKeyframeTrack,
  9447. ValueTypeName: 'bool',
  9448. ValueBufferType: Array,
  9449. DefaultInterpolation: THREE.InterpolateDiscrete,
  9450. InterpolantFactoryMethodLinear: undefined,
  9451. InterpolantFactoryMethodSmooth: undefined
  9452. // Note: Actually this track could have a optimized / compressed
  9453. // representation of a single value and a custom interpolant that
  9454. // computes "firstValue ^ isOdd( index )".
  9455. } );
  9456. // File:src/animation/tracks/ColorKeyframeTrack.js
  9457. /**
  9458. *
  9459. * A Track of keyframe values that represent color.
  9460. *
  9461. *
  9462. * @author Ben Houston / http://clara.io/
  9463. * @author David Sarno / http://lighthaus.us/
  9464. * @author tschw
  9465. */
  9466. THREE.ColorKeyframeTrack = function ( name, times, values, interpolation ) {
  9467. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9468. };
  9469. THREE.ColorKeyframeTrack.prototype =
  9470. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9471. constructor: THREE.ColorKeyframeTrack,
  9472. ValueTypeName: 'color'
  9473. // ValueBufferType is inherited
  9474. // DefaultInterpolation is inherited
  9475. // Note: Very basic implementation and nothing special yet.
  9476. // However, this is the place for color space parameterization.
  9477. } );
  9478. // File:src/animation/tracks/NumberKeyframeTrack.js
  9479. /**
  9480. *
  9481. * A Track of numeric keyframe values.
  9482. *
  9483. * @author Ben Houston / http://clara.io/
  9484. * @author David Sarno / http://lighthaus.us/
  9485. * @author tschw
  9486. */
  9487. THREE.NumberKeyframeTrack = function ( name, times, values, interpolation ) {
  9488. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9489. };
  9490. THREE.NumberKeyframeTrack.prototype =
  9491. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9492. constructor: THREE.NumberKeyframeTrack,
  9493. ValueTypeName: 'number',
  9494. // ValueBufferType is inherited
  9495. // DefaultInterpolation is inherited
  9496. } );
  9497. // File:src/animation/tracks/QuaternionKeyframeTrack.js
  9498. /**
  9499. *
  9500. * A Track of quaternion keyframe values.
  9501. *
  9502. * @author Ben Houston / http://clara.io/
  9503. * @author David Sarno / http://lighthaus.us/
  9504. * @author tschw
  9505. */
  9506. THREE.QuaternionKeyframeTrack = function ( name, times, values, interpolation ) {
  9507. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9508. };
  9509. THREE.QuaternionKeyframeTrack.prototype =
  9510. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9511. constructor: THREE.QuaternionKeyframeTrack,
  9512. ValueTypeName: 'quaternion',
  9513. // ValueBufferType is inherited
  9514. DefaultInterpolation: THREE.InterpolateLinear,
  9515. InterpolantFactoryMethodLinear: function( result ) {
  9516. return new THREE.QuaternionLinearInterpolant(
  9517. this.times, this.values, this.getValueSize(), result );
  9518. },
  9519. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  9520. } );
  9521. // File:src/animation/tracks/StringKeyframeTrack.js
  9522. /**
  9523. *
  9524. * A Track that interpolates Strings
  9525. *
  9526. *
  9527. * @author Ben Houston / http://clara.io/
  9528. * @author David Sarno / http://lighthaus.us/
  9529. * @author tschw
  9530. */
  9531. THREE.StringKeyframeTrack = function ( name, times, values, interpolation ) {
  9532. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9533. };
  9534. THREE.StringKeyframeTrack.prototype =
  9535. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9536. constructor: THREE.StringKeyframeTrack,
  9537. ValueTypeName: 'string',
  9538. ValueBufferType: Array,
  9539. DefaultInterpolation: THREE.InterpolateDiscrete,
  9540. InterpolantFactoryMethodLinear: undefined,
  9541. InterpolantFactoryMethodSmooth: undefined
  9542. } );
  9543. // File:src/animation/tracks/VectorKeyframeTrack.js
  9544. /**
  9545. *
  9546. * A Track of vectored keyframe values.
  9547. *
  9548. *
  9549. * @author Ben Houston / http://clara.io/
  9550. * @author David Sarno / http://lighthaus.us/
  9551. * @author tschw
  9552. */
  9553. THREE.VectorKeyframeTrack = function ( name, times, values, interpolation ) {
  9554. THREE.KeyframeTrack.call( this, name, times, values, interpolation );
  9555. };
  9556. THREE.VectorKeyframeTrack.prototype =
  9557. Object.assign( Object.create( THREE.KeyframeTrack.prototype ), {
  9558. constructor: THREE.VectorKeyframeTrack,
  9559. ValueTypeName: 'vector'
  9560. // ValueBufferType is inherited
  9561. // DefaultInterpolation is inherited
  9562. } );
  9563. // File:src/audio/Audio.js
  9564. /**
  9565. * @author mrdoob / http://mrdoob.com/
  9566. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  9567. */
  9568. THREE.Audio = function ( listener ) {
  9569. THREE.Object3D.call( this );
  9570. this.type = 'Audio';
  9571. this.context = listener.context;
  9572. this.source = this.context.createBufferSource();
  9573. this.source.onended = this.onEnded.bind( this );
  9574. this.gain = this.context.createGain();
  9575. this.gain.connect( listener.getInput() );
  9576. this.autoplay = false;
  9577. this.startTime = 0;
  9578. this.playbackRate = 1;
  9579. this.isPlaying = false;
  9580. this.hasPlaybackControl = true;
  9581. this.sourceType = 'empty';
  9582. this.filter = null;
  9583. };
  9584. THREE.Audio.prototype = Object.create( THREE.Object3D.prototype );
  9585. THREE.Audio.prototype.constructor = THREE.Audio;
  9586. THREE.Audio.prototype.getOutput = function () {
  9587. return this.gain;
  9588. };
  9589. THREE.Audio.prototype.setNodeSource = function ( audioNode ) {
  9590. this.hasPlaybackControl = false;
  9591. this.sourceType = 'audioNode';
  9592. this.source = audioNode;
  9593. this.connect();
  9594. return this;
  9595. };
  9596. THREE.Audio.prototype.setBuffer = function ( audioBuffer ) {
  9597. var scope = this;
  9598. scope.source.buffer = audioBuffer;
  9599. scope.sourceType = 'buffer';
  9600. if ( scope.autoplay ) scope.play();
  9601. return this;
  9602. };
  9603. THREE.Audio.prototype.play = function () {
  9604. if ( this.isPlaying === true ) {
  9605. console.warn( 'THREE.Audio: Audio is already playing.' );
  9606. return;
  9607. }
  9608. if ( this.hasPlaybackControl === false ) {
  9609. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9610. return;
  9611. }
  9612. var source = this.context.createBufferSource();
  9613. source.buffer = this.source.buffer;
  9614. source.loop = this.source.loop;
  9615. source.onended = this.source.onended;
  9616. source.start( 0, this.startTime );
  9617. source.playbackRate.value = this.playbackRate;
  9618. this.isPlaying = true;
  9619. this.source = source;
  9620. this.connect();
  9621. };
  9622. THREE.Audio.prototype.pause = function () {
  9623. if ( this.hasPlaybackControl === false ) {
  9624. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9625. return;
  9626. }
  9627. this.source.stop();
  9628. this.startTime = this.context.currentTime;
  9629. };
  9630. THREE.Audio.prototype.stop = function () {
  9631. if ( this.hasPlaybackControl === false ) {
  9632. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9633. return;
  9634. }
  9635. this.source.stop();
  9636. this.startTime = 0;
  9637. };
  9638. THREE.Audio.prototype.connect = function () {
  9639. if ( this.filter !== null ) {
  9640. this.source.connect( this.filter );
  9641. this.filter.connect( this.getOutput() );
  9642. } else {
  9643. this.source.connect( this.getOutput() );
  9644. }
  9645. };
  9646. THREE.Audio.prototype.disconnect = function () {
  9647. if ( this.filter !== null ) {
  9648. this.source.disconnect( this.filter );
  9649. this.filter.disconnect( this.getOutput() );
  9650. } else {
  9651. this.source.disconnect( this.getOutput() );
  9652. }
  9653. };
  9654. THREE.Audio.prototype.getFilter = function () {
  9655. return this.filter;
  9656. };
  9657. THREE.Audio.prototype.setFilter = function ( value ) {
  9658. if ( value === undefined ) value = null;
  9659. if ( this.isPlaying === true ) {
  9660. this.disconnect();
  9661. this.filter = value;
  9662. this.connect();
  9663. } else {
  9664. this.filter = value;
  9665. }
  9666. };
  9667. THREE.Audio.prototype.setPlaybackRate = function ( value ) {
  9668. if ( this.hasPlaybackControl === false ) {
  9669. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9670. return;
  9671. }
  9672. this.playbackRate = value;
  9673. if ( this.isPlaying === true ) {
  9674. this.source.playbackRate.value = this.playbackRate;
  9675. }
  9676. };
  9677. THREE.Audio.prototype.getPlaybackRate = function () {
  9678. return this.playbackRate;
  9679. };
  9680. THREE.Audio.prototype.onEnded = function () {
  9681. this.isPlaying = false;
  9682. };
  9683. THREE.Audio.prototype.setLoop = function ( value ) {
  9684. if ( this.hasPlaybackControl === false ) {
  9685. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9686. return;
  9687. }
  9688. this.source.loop = value;
  9689. };
  9690. THREE.Audio.prototype.getLoop = function () {
  9691. if ( this.hasPlaybackControl === false ) {
  9692. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  9693. return false;
  9694. }
  9695. return this.source.loop;
  9696. };
  9697. THREE.Audio.prototype.setVolume = function ( value ) {
  9698. this.gain.gain.value = value;
  9699. };
  9700. THREE.Audio.prototype.getVolume = function () {
  9701. return this.gain.gain.value;
  9702. };
  9703. // File:src/audio/AudioAnalyser.js
  9704. /**
  9705. * @author mrdoob / http://mrdoob.com/
  9706. */
  9707. THREE.AudioAnalyser = function ( audio, fftSize ) {
  9708. this.analyser = audio.context.createAnalyser();
  9709. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  9710. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  9711. audio.getOutput().connect( this.analyser );
  9712. };
  9713. THREE.AudioAnalyser.prototype = {
  9714. constructor: THREE.AudioAnalyser,
  9715. getData: function () {
  9716. this.analyser.getByteFrequencyData( this.data );
  9717. return this.data;
  9718. }
  9719. };
  9720. // File:src/audio/AudioContext.js
  9721. /**
  9722. * @author mrdoob / http://mrdoob.com/
  9723. */
  9724. Object.defineProperty( THREE, 'AudioContext', {
  9725. get: ( function () {
  9726. var context;
  9727. return function () {
  9728. if ( context === undefined ) {
  9729. context = new ( window.AudioContext || window.webkitAudioContext )();
  9730. }
  9731. return context;
  9732. };
  9733. } )()
  9734. } );
  9735. // File:src/audio/PositionalAudio.js
  9736. /**
  9737. * @author mrdoob / http://mrdoob.com/
  9738. */
  9739. THREE.PositionalAudio = function ( listener ) {
  9740. THREE.Audio.call( this, listener );
  9741. this.panner = this.context.createPanner();
  9742. this.panner.connect( this.gain );
  9743. };
  9744. THREE.PositionalAudio.prototype = Object.create( THREE.Audio.prototype );
  9745. THREE.PositionalAudio.prototype.constructor = THREE.PositionalAudio;
  9746. THREE.PositionalAudio.prototype.getOutput = function () {
  9747. return this.panner;
  9748. };
  9749. THREE.PositionalAudio.prototype.setRefDistance = function ( value ) {
  9750. this.panner.refDistance = value;
  9751. };
  9752. THREE.PositionalAudio.prototype.getRefDistance = function () {
  9753. return this.panner.refDistance;
  9754. };
  9755. THREE.PositionalAudio.prototype.setRolloffFactor = function ( value ) {
  9756. this.panner.rolloffFactor = value;
  9757. };
  9758. THREE.PositionalAudio.prototype.getRolloffFactor = function () {
  9759. return this.panner.rolloffFactor;
  9760. };
  9761. THREE.PositionalAudio.prototype.setDistanceModel = function ( value ) {
  9762. this.panner.distanceModel = value;
  9763. };
  9764. THREE.PositionalAudio.prototype.getDistanceModel = function () {
  9765. return this.panner.distanceModel;
  9766. };
  9767. THREE.PositionalAudio.prototype.setMaxDistance = function ( value ) {
  9768. this.panner.maxDistance = value;
  9769. };
  9770. THREE.PositionalAudio.prototype.getMaxDistance = function () {
  9771. return this.panner.maxDistance;
  9772. };
  9773. THREE.PositionalAudio.prototype.updateMatrixWorld = ( function () {
  9774. var position = new THREE.Vector3();
  9775. return function updateMatrixWorld( force ) {
  9776. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9777. position.setFromMatrixPosition( this.matrixWorld );
  9778. this.panner.setPosition( position.x, position.y, position.z );
  9779. };
  9780. } )();
  9781. // File:src/audio/AudioListener.js
  9782. /**
  9783. * @author mrdoob / http://mrdoob.com/
  9784. */
  9785. THREE.AudioListener = function () {
  9786. THREE.Object3D.call( this );
  9787. this.type = 'AudioListener';
  9788. this.context = THREE.AudioContext;
  9789. this.gain = this.context.createGain();
  9790. this.gain.connect( this.context.destination );
  9791. this.filter = null;
  9792. };
  9793. THREE.AudioListener.prototype = Object.create( THREE.Object3D.prototype );
  9794. THREE.AudioListener.prototype.constructor = THREE.AudioListener;
  9795. THREE.AudioListener.prototype.getInput = function () {
  9796. return this.gain;
  9797. };
  9798. THREE.AudioListener.prototype.removeFilter = function ( ) {
  9799. if ( this.filter !== null ) {
  9800. this.gain.disconnect( this.filter );
  9801. this.filter.disconnect( this.context.destination );
  9802. this.gain.connect( this.context.destination );
  9803. this.filter = null;
  9804. }
  9805. };
  9806. THREE.AudioListener.prototype.setFilter = function ( value ) {
  9807. if ( this.filter !== null ) {
  9808. this.gain.disconnect( this.filter );
  9809. this.filter.disconnect( this.context.destination );
  9810. } else {
  9811. this.gain.disconnect( this.context.destination );
  9812. }
  9813. this.filter = value;
  9814. this.gain.connect( this.filter );
  9815. this.filter.connect( this.context.destination );
  9816. };
  9817. THREE.AudioListener.prototype.getFilter = function () {
  9818. return this.filter;
  9819. };
  9820. THREE.AudioListener.prototype.setMasterVolume = function ( value ) {
  9821. this.gain.gain.value = value;
  9822. };
  9823. THREE.AudioListener.prototype.getMasterVolume = function () {
  9824. return this.gain.gain.value;
  9825. };
  9826. THREE.AudioListener.prototype.updateMatrixWorld = ( function () {
  9827. var position = new THREE.Vector3();
  9828. var quaternion = new THREE.Quaternion();
  9829. var scale = new THREE.Vector3();
  9830. var orientation = new THREE.Vector3();
  9831. return function updateMatrixWorld( force ) {
  9832. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  9833. var listener = this.context.listener;
  9834. var up = this.up;
  9835. this.matrixWorld.decompose( position, quaternion, scale );
  9836. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9837. listener.setPosition( position.x, position.y, position.z );
  9838. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  9839. };
  9840. } )();
  9841. // File:src/cameras/Camera.js
  9842. /**
  9843. * @author mrdoob / http://mrdoob.com/
  9844. * @author mikael emtinger / http://gomo.se/
  9845. * @author WestLangley / http://github.com/WestLangley
  9846. */
  9847. THREE.Camera = function () {
  9848. THREE.Object3D.call( this );
  9849. this.type = 'Camera';
  9850. this.matrixWorldInverse = new THREE.Matrix4();
  9851. this.projectionMatrix = new THREE.Matrix4();
  9852. };
  9853. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  9854. THREE.Camera.prototype.constructor = THREE.Camera;
  9855. THREE.Camera.prototype.getWorldDirection = function () {
  9856. var quaternion = new THREE.Quaternion();
  9857. return function ( optionalTarget ) {
  9858. var result = optionalTarget || new THREE.Vector3();
  9859. this.getWorldQuaternion( quaternion );
  9860. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  9861. };
  9862. }();
  9863. THREE.Camera.prototype.lookAt = function () {
  9864. // This routine does not support cameras with rotated and/or translated parent(s)
  9865. var m1 = new THREE.Matrix4();
  9866. return function ( vector ) {
  9867. m1.lookAt( this.position, vector, this.up );
  9868. this.quaternion.setFromRotationMatrix( m1 );
  9869. };
  9870. }();
  9871. THREE.Camera.prototype.clone = function () {
  9872. return new this.constructor().copy( this );
  9873. };
  9874. THREE.Camera.prototype.copy = function ( source ) {
  9875. THREE.Object3D.prototype.copy.call( this, source );
  9876. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  9877. this.projectionMatrix.copy( source.projectionMatrix );
  9878. return this;
  9879. };
  9880. // File:src/cameras/CubeCamera.js
  9881. /**
  9882. * Camera for rendering cube maps
  9883. * - renders scene into axis-aligned cube
  9884. *
  9885. * @author alteredq / http://alteredqualia.com/
  9886. */
  9887. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  9888. THREE.Object3D.call( this );
  9889. this.type = 'CubeCamera';
  9890. var fov = 90, aspect = 1;
  9891. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9892. cameraPX.up.set( 0, - 1, 0 );
  9893. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  9894. this.add( cameraPX );
  9895. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9896. cameraNX.up.set( 0, - 1, 0 );
  9897. cameraNX.lookAt( new THREE.Vector3( - 1, 0, 0 ) );
  9898. this.add( cameraNX );
  9899. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9900. cameraPY.up.set( 0, 0, 1 );
  9901. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  9902. this.add( cameraPY );
  9903. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9904. cameraNY.up.set( 0, 0, - 1 );
  9905. cameraNY.lookAt( new THREE.Vector3( 0, - 1, 0 ) );
  9906. this.add( cameraNY );
  9907. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9908. cameraPZ.up.set( 0, - 1, 0 );
  9909. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  9910. this.add( cameraPZ );
  9911. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  9912. cameraNZ.up.set( 0, - 1, 0 );
  9913. cameraNZ.lookAt( new THREE.Vector3( 0, 0, - 1 ) );
  9914. this.add( cameraNZ );
  9915. var options = { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter };
  9916. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  9917. this.updateCubeMap = function ( renderer, scene ) {
  9918. if ( this.parent === null ) this.updateMatrixWorld();
  9919. var renderTarget = this.renderTarget;
  9920. var generateMipmaps = renderTarget.texture.generateMipmaps;
  9921. renderTarget.texture.generateMipmaps = false;
  9922. renderTarget.activeCubeFace = 0;
  9923. renderer.render( scene, cameraPX, renderTarget );
  9924. renderTarget.activeCubeFace = 1;
  9925. renderer.render( scene, cameraNX, renderTarget );
  9926. renderTarget.activeCubeFace = 2;
  9927. renderer.render( scene, cameraPY, renderTarget );
  9928. renderTarget.activeCubeFace = 3;
  9929. renderer.render( scene, cameraNY, renderTarget );
  9930. renderTarget.activeCubeFace = 4;
  9931. renderer.render( scene, cameraPZ, renderTarget );
  9932. renderTarget.texture.generateMipmaps = generateMipmaps;
  9933. renderTarget.activeCubeFace = 5;
  9934. renderer.render( scene, cameraNZ, renderTarget );
  9935. renderer.setRenderTarget( null );
  9936. };
  9937. };
  9938. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  9939. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  9940. // File:src/cameras/OrthographicCamera.js
  9941. /**
  9942. * @author alteredq / http://alteredqualia.com/
  9943. */
  9944. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  9945. THREE.Camera.call( this );
  9946. this.type = 'OrthographicCamera';
  9947. this.zoom = 1;
  9948. this.left = left;
  9949. this.right = right;
  9950. this.top = top;
  9951. this.bottom = bottom;
  9952. this.near = ( near !== undefined ) ? near : 0.1;
  9953. this.far = ( far !== undefined ) ? far : 2000;
  9954. this.updateProjectionMatrix();
  9955. };
  9956. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  9957. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  9958. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  9959. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  9960. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  9961. var cx = ( this.right + this.left ) / 2;
  9962. var cy = ( this.top + this.bottom ) / 2;
  9963. this.projectionMatrix.makeOrthographic( cx - dx, cx + dx, cy + dy, cy - dy, this.near, this.far );
  9964. };
  9965. THREE.OrthographicCamera.prototype.copy = function ( source ) {
  9966. THREE.Camera.prototype.copy.call( this, source );
  9967. this.left = source.left;
  9968. this.right = source.right;
  9969. this.top = source.top;
  9970. this.bottom = source.bottom;
  9971. this.near = source.near;
  9972. this.far = source.far;
  9973. this.zoom = source.zoom;
  9974. return this;
  9975. };
  9976. THREE.OrthographicCamera.prototype.toJSON = function ( meta ) {
  9977. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  9978. data.object.zoom = this.zoom;
  9979. data.object.left = this.left;
  9980. data.object.right = this.right;
  9981. data.object.top = this.top;
  9982. data.object.bottom = this.bottom;
  9983. data.object.near = this.near;
  9984. data.object.far = this.far;
  9985. return data;
  9986. };
  9987. // File:src/cameras/PerspectiveCamera.js
  9988. /**
  9989. * @author mrdoob / http://mrdoob.com/
  9990. * @author greggman / http://games.greggman.com/
  9991. * @author zz85 / http://www.lab4games.net/zz85/blog
  9992. * @author tschw
  9993. */
  9994. THREE.PerspectiveCamera = function( fov, aspect, near, far ) {
  9995. THREE.Camera.call( this );
  9996. this.type = 'PerspectiveCamera';
  9997. this.fov = fov !== undefined ? fov : 50;
  9998. this.zoom = 1;
  9999. this.near = near !== undefined ? near : 0.1;
  10000. this.far = far !== undefined ? far : 2000;
  10001. this.focus = 10;
  10002. this.aspect = aspect !== undefined ? aspect : 1;
  10003. this.view = null;
  10004. this.filmGauge = 35; // width of the film (default in millimeters)
  10005. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  10006. this.updateProjectionMatrix();
  10007. };
  10008. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  10009. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  10010. /**
  10011. * Sets the FOV by focal length (DEPRECATED).
  10012. *
  10013. * Optionally also sets .filmGauge, otherwise uses it. See .setFocalLength.
  10014. */
  10015. THREE.PerspectiveCamera.prototype.setLens = function( focalLength, filmGauge ) {
  10016. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  10017. "Use .setFocalLength and .filmGauge for a photographic setup." );
  10018. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  10019. this.setFocalLength( focalLength );
  10020. };
  10021. /**
  10022. * Sets the FOV by focal length in respect to the current .filmGauge.
  10023. *
  10024. * The default film gauge is 35, so that the focal length can be specified for
  10025. * a 35mm (full frame) camera.
  10026. *
  10027. * Values for focal length and film gauge must have the same unit.
  10028. */
  10029. THREE.PerspectiveCamera.prototype.setFocalLength = function( focalLength ) {
  10030. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  10031. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  10032. this.fov = THREE.Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  10033. this.updateProjectionMatrix();
  10034. };
  10035. /**
  10036. * Calculates the focal length from the current .fov and .filmGauge.
  10037. */
  10038. THREE.PerspectiveCamera.prototype.getFocalLength = function() {
  10039. var vExtentSlope = Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov );
  10040. return 0.5 * this.getFilmHeight() / vExtentSlope;
  10041. };
  10042. THREE.PerspectiveCamera.prototype.getEffectiveFOV = function() {
  10043. return THREE.Math.RAD2DEG * 2 * Math.atan(
  10044. Math.tan( THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  10045. };
  10046. THREE.PerspectiveCamera.prototype.getFilmWidth = function() {
  10047. // film not completely covered in portrait format (aspect < 1)
  10048. return this.filmGauge * Math.min( this.aspect, 1 );
  10049. };
  10050. THREE.PerspectiveCamera.prototype.getFilmHeight = function() {
  10051. // film not completely covered in landscape format (aspect > 1)
  10052. return this.filmGauge / Math.max( this.aspect, 1 );
  10053. };
  10054. /**
  10055. * Sets an offset in a larger frustum. This is useful for multi-window or
  10056. * multi-monitor/multi-machine setups.
  10057. *
  10058. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  10059. * the monitors are in grid like this
  10060. *
  10061. * +---+---+---+
  10062. * | A | B | C |
  10063. * +---+---+---+
  10064. * | D | E | F |
  10065. * +---+---+---+
  10066. *
  10067. * then for each monitor you would call it like this
  10068. *
  10069. * var w = 1920;
  10070. * var h = 1080;
  10071. * var fullWidth = w * 3;
  10072. * var fullHeight = h * 2;
  10073. *
  10074. * --A--
  10075. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  10076. * --B--
  10077. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  10078. * --C--
  10079. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  10080. * --D--
  10081. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  10082. * --E--
  10083. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  10084. * --F--
  10085. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  10086. *
  10087. * Note there is no reason monitors have to be the same size or in a grid.
  10088. */
  10089. THREE.PerspectiveCamera.prototype.setViewOffset = function( fullWidth, fullHeight, x, y, width, height ) {
  10090. this.aspect = fullWidth / fullHeight;
  10091. this.view = {
  10092. fullWidth: fullWidth,
  10093. fullHeight: fullHeight,
  10094. offsetX: x,
  10095. offsetY: y,
  10096. width: width,
  10097. height: height
  10098. };
  10099. this.updateProjectionMatrix();
  10100. };
  10101. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function() {
  10102. var near = this.near,
  10103. top = near * Math.tan(
  10104. THREE.Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  10105. height = 2 * top,
  10106. width = this.aspect * height,
  10107. left = - 0.5 * width,
  10108. view = this.view;
  10109. if ( view !== null ) {
  10110. var fullWidth = view.fullWidth,
  10111. fullHeight = view.fullHeight;
  10112. left += view.offsetX * width / fullWidth;
  10113. top -= view.offsetY * height / fullHeight;
  10114. width *= view.width / fullWidth;
  10115. height *= view.height / fullHeight;
  10116. }
  10117. var skew = this.filmOffset;
  10118. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  10119. this.projectionMatrix.makeFrustum(
  10120. left, left + width, top - height, top, near, this.far );
  10121. };
  10122. THREE.PerspectiveCamera.prototype.copy = function( source ) {
  10123. THREE.Camera.prototype.copy.call( this, source );
  10124. this.fov = source.fov;
  10125. this.zoom = source.zoom;
  10126. this.near = source.near;
  10127. this.far = source.far;
  10128. this.focus = source.focus;
  10129. this.aspect = source.aspect;
  10130. this.view = source.view === null ? null : Object.assign( {}, source.view );
  10131. this.filmGauge = source.filmGauge;
  10132. this.filmOffset = source.filmOffset;
  10133. return this;
  10134. };
  10135. THREE.PerspectiveCamera.prototype.toJSON = function( meta ) {
  10136. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  10137. data.object.fov = this.fov;
  10138. data.object.zoom = this.zoom;
  10139. data.object.near = this.near;
  10140. data.object.far = this.far;
  10141. data.object.focus = this.focus;
  10142. data.object.aspect = this.aspect;
  10143. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  10144. data.object.filmGauge = this.filmGauge;
  10145. data.object.filmOffset = this.filmOffset;
  10146. return data;
  10147. };
  10148. // File:src/cameras/StereoCamera.js
  10149. /**
  10150. * @author mrdoob / http://mrdoob.com/
  10151. */
  10152. THREE.StereoCamera = function () {
  10153. this.type = 'StereoCamera';
  10154. this.aspect = 1;
  10155. this.cameraL = new THREE.PerspectiveCamera();
  10156. this.cameraL.layers.enable( 1 );
  10157. this.cameraL.matrixAutoUpdate = false;
  10158. this.cameraR = new THREE.PerspectiveCamera();
  10159. this.cameraR.layers.enable( 2 );
  10160. this.cameraR.matrixAutoUpdate = false;
  10161. };
  10162. THREE.StereoCamera.prototype = {
  10163. constructor: THREE.StereoCamera,
  10164. update: ( function () {
  10165. var focus, fov, aspect, near, far;
  10166. var eyeRight = new THREE.Matrix4();
  10167. var eyeLeft = new THREE.Matrix4();
  10168. return function update ( camera ) {
  10169. var needsUpdate = focus !== camera.focus || fov !== camera.fov ||
  10170. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  10171. far !== camera.far;
  10172. if ( needsUpdate ) {
  10173. focus = camera.focus;
  10174. fov = camera.fov;
  10175. aspect = camera.aspect * this.aspect;
  10176. near = camera.near;
  10177. far = camera.far;
  10178. // Off-axis stereoscopic effect based on
  10179. // http://paulbourke.net/stereographics/stereorender/
  10180. var projectionMatrix = camera.projectionMatrix.clone();
  10181. var eyeSep = 0.064 / 2;
  10182. var eyeSepOnProjection = eyeSep * near / focus;
  10183. var ymax = near * Math.tan( THREE.Math.DEG2RAD * fov * 0.5 );
  10184. var xmin, xmax;
  10185. // translate xOffset
  10186. eyeLeft.elements[ 12 ] = - eyeSep;
  10187. eyeRight.elements[ 12 ] = eyeSep;
  10188. // for left eye
  10189. xmin = - ymax * aspect + eyeSepOnProjection;
  10190. xmax = ymax * aspect + eyeSepOnProjection;
  10191. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  10192. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  10193. this.cameraL.projectionMatrix.copy( projectionMatrix );
  10194. // for right eye
  10195. xmin = - ymax * aspect - eyeSepOnProjection;
  10196. xmax = ymax * aspect - eyeSepOnProjection;
  10197. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  10198. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  10199. this.cameraR.projectionMatrix.copy( projectionMatrix );
  10200. }
  10201. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  10202. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  10203. };
  10204. } )()
  10205. };
  10206. // File:src/lights/Light.js
  10207. /**
  10208. * @author mrdoob / http://mrdoob.com/
  10209. * @author alteredq / http://alteredqualia.com/
  10210. */
  10211. THREE.Light = function ( color, intensity ) {
  10212. THREE.Object3D.call( this );
  10213. this.type = 'Light';
  10214. this.color = new THREE.Color( color );
  10215. this.intensity = intensity !== undefined ? intensity : 1;
  10216. this.receiveShadow = undefined;
  10217. };
  10218. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  10219. THREE.Light.prototype.constructor = THREE.Light;
  10220. THREE.Light.prototype.copy = function ( source ) {
  10221. THREE.Object3D.prototype.copy.call( this, source );
  10222. this.color.copy( source.color );
  10223. this.intensity = source.intensity;
  10224. return this;
  10225. };
  10226. THREE.Light.prototype.toJSON = function ( meta ) {
  10227. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  10228. data.object.color = this.color.getHex();
  10229. data.object.intensity = this.intensity;
  10230. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  10231. if ( this.distance !== undefined ) data.object.distance = this.distance;
  10232. if ( this.angle !== undefined ) data.object.angle = this.angle;
  10233. if ( this.decay !== undefined ) data.object.decay = this.decay;
  10234. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  10235. return data;
  10236. };
  10237. // File:src/lights/LightShadow.js
  10238. /**
  10239. * @author mrdoob / http://mrdoob.com/
  10240. */
  10241. THREE.LightShadow = function ( camera ) {
  10242. this.camera = camera;
  10243. this.bias = 0;
  10244. this.radius = 1;
  10245. this.mapSize = new THREE.Vector2( 512, 512 );
  10246. this.map = null;
  10247. this.matrix = new THREE.Matrix4();
  10248. };
  10249. THREE.LightShadow.prototype = {
  10250. constructor: THREE.LightShadow,
  10251. copy: function ( source ) {
  10252. this.camera = source.camera.clone();
  10253. this.bias = source.bias;
  10254. this.radius = source.radius;
  10255. this.mapSize.copy( source.mapSize );
  10256. return this;
  10257. },
  10258. clone: function () {
  10259. return new this.constructor().copy( this );
  10260. }
  10261. };
  10262. // File:src/lights/AmbientLight.js
  10263. /**
  10264. * @author mrdoob / http://mrdoob.com/
  10265. */
  10266. THREE.AmbientLight = function ( color, intensity ) {
  10267. THREE.Light.call( this, color, intensity );
  10268. this.type = 'AmbientLight';
  10269. this.castShadow = undefined;
  10270. };
  10271. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  10272. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  10273. // File:src/lights/DirectionalLight.js
  10274. /**
  10275. * @author mrdoob / http://mrdoob.com/
  10276. * @author alteredq / http://alteredqualia.com/
  10277. */
  10278. THREE.DirectionalLight = function ( color, intensity ) {
  10279. THREE.Light.call( this, color, intensity );
  10280. this.type = 'DirectionalLight';
  10281. this.position.set( 0, 1, 0 );
  10282. this.updateMatrix();
  10283. this.target = new THREE.Object3D();
  10284. this.shadow = new THREE.DirectionalLightShadow();
  10285. };
  10286. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  10287. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  10288. THREE.DirectionalLight.prototype.copy = function ( source ) {
  10289. THREE.Light.prototype.copy.call( this, source );
  10290. this.target = source.target.clone();
  10291. this.shadow = source.shadow.clone();
  10292. return this;
  10293. };
  10294. // File:src/lights/DirectionalLightShadow.js
  10295. /**
  10296. * @author mrdoob / http://mrdoob.com/
  10297. */
  10298. THREE.DirectionalLightShadow = function ( light ) {
  10299. THREE.LightShadow.call( this, new THREE.OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  10300. };
  10301. THREE.DirectionalLightShadow.prototype = Object.create( THREE.LightShadow.prototype );
  10302. THREE.DirectionalLightShadow.prototype.constructor = THREE.DirectionalLightShadow;
  10303. // File:src/lights/HemisphereLight.js
  10304. /**
  10305. * @author alteredq / http://alteredqualia.com/
  10306. */
  10307. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  10308. THREE.Light.call( this, skyColor, intensity );
  10309. this.type = 'HemisphereLight';
  10310. this.castShadow = undefined;
  10311. this.position.set( 0, 1, 0 );
  10312. this.updateMatrix();
  10313. this.groundColor = new THREE.Color( groundColor );
  10314. };
  10315. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  10316. THREE.HemisphereLight.prototype.constructor = THREE.HemisphereLight;
  10317. THREE.HemisphereLight.prototype.copy = function ( source ) {
  10318. THREE.Light.prototype.copy.call( this, source );
  10319. this.groundColor.copy( source.groundColor );
  10320. return this;
  10321. };
  10322. // File:src/lights/PointLight.js
  10323. /**
  10324. * @author mrdoob / http://mrdoob.com/
  10325. */
  10326. THREE.PointLight = function ( color, intensity, distance, decay ) {
  10327. THREE.Light.call( this, color, intensity );
  10328. this.type = 'PointLight';
  10329. this.distance = ( distance !== undefined ) ? distance : 0;
  10330. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  10331. this.shadow = new THREE.LightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  10332. };
  10333. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  10334. THREE.PointLight.prototype.constructor = THREE.PointLight;
  10335. Object.defineProperty( THREE.PointLight.prototype, "power", {
  10336. get: function () {
  10337. // intensity = power per solid angle.
  10338. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  10339. return this.intensity * 4 * Math.PI;
  10340. },
  10341. set: function ( power ) {
  10342. // intensity = power per solid angle.
  10343. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  10344. this.intensity = power / ( 4 * Math.PI );
  10345. }
  10346. } );
  10347. THREE.PointLight.prototype.copy = function ( source ) {
  10348. THREE.Light.prototype.copy.call( this, source );
  10349. this.distance = source.distance;
  10350. this.decay = source.decay;
  10351. this.shadow = source.shadow.clone();
  10352. return this;
  10353. };
  10354. // File:src/lights/SpotLight.js
  10355. /**
  10356. * @author alteredq / http://alteredqualia.com/
  10357. */
  10358. THREE.SpotLight = function ( color, intensity, distance, angle, penumbra, decay ) {
  10359. THREE.Light.call( this, color, intensity );
  10360. this.type = 'SpotLight';
  10361. this.position.set( 0, 1, 0 );
  10362. this.updateMatrix();
  10363. this.target = new THREE.Object3D();
  10364. this.distance = ( distance !== undefined ) ? distance : 0;
  10365. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  10366. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  10367. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  10368. this.shadow = new THREE.SpotLightShadow();
  10369. };
  10370. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  10371. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  10372. Object.defineProperty( THREE.SpotLight.prototype, "power", {
  10373. get: function () {
  10374. // intensity = power per solid angle.
  10375. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  10376. return this.intensity * Math.PI;
  10377. },
  10378. set: function ( power ) {
  10379. // intensity = power per solid angle.
  10380. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  10381. this.intensity = power / Math.PI;
  10382. }
  10383. } );
  10384. THREE.SpotLight.prototype.copy = function ( source ) {
  10385. THREE.Light.prototype.copy.call( this, source );
  10386. this.distance = source.distance;
  10387. this.angle = source.angle;
  10388. this.penumbra = source.penumbra;
  10389. this.decay = source.decay;
  10390. this.target = source.target.clone();
  10391. this.shadow = source.shadow.clone();
  10392. return this;
  10393. };
  10394. // File:src/lights/SpotLightShadow.js
  10395. /**
  10396. * @author mrdoob / http://mrdoob.com/
  10397. */
  10398. THREE.SpotLightShadow = function () {
  10399. THREE.LightShadow.call( this, new THREE.PerspectiveCamera( 50, 1, 0.5, 500 ) );
  10400. };
  10401. THREE.SpotLightShadow.prototype = Object.create( THREE.LightShadow.prototype );
  10402. THREE.SpotLightShadow.prototype.constructor = THREE.SpotLightShadow;
  10403. THREE.SpotLightShadow.prototype.update = function ( light ) {
  10404. var fov = THREE.Math.RAD2DEG * 2 * light.angle;
  10405. var aspect = this.mapSize.width / this.mapSize.height;
  10406. var far = light.distance || 500;
  10407. var camera = this.camera;
  10408. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  10409. camera.fov = fov;
  10410. camera.aspect = aspect;
  10411. camera.far = far;
  10412. camera.updateProjectionMatrix();
  10413. }
  10414. };
  10415. // File:src/loaders/AudioLoader.js
  10416. /**
  10417. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  10418. */
  10419. THREE.AudioLoader = function ( manager ) {
  10420. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10421. };
  10422. THREE.AudioLoader.prototype = {
  10423. constructor: THREE.AudioLoader,
  10424. load: function ( url, onLoad, onProgress, onError ) {
  10425. var loader = new THREE.XHRLoader( this.manager );
  10426. loader.setResponseType( 'arraybuffer' );
  10427. loader.load( url, function ( buffer ) {
  10428. var context = THREE.AudioContext;
  10429. context.decodeAudioData( buffer, function ( audioBuffer ) {
  10430. onLoad( audioBuffer );
  10431. } );
  10432. }, onProgress, onError );
  10433. }
  10434. };
  10435. // File:src/loaders/Cache.js
  10436. /**
  10437. * @author mrdoob / http://mrdoob.com/
  10438. */
  10439. THREE.Cache = {
  10440. enabled: false,
  10441. files: {},
  10442. add: function ( key, file ) {
  10443. if ( this.enabled === false ) return;
  10444. // console.log( 'THREE.Cache', 'Adding key:', key );
  10445. this.files[ key ] = file;
  10446. },
  10447. get: function ( key ) {
  10448. if ( this.enabled === false ) return;
  10449. // console.log( 'THREE.Cache', 'Checking key:', key );
  10450. return this.files[ key ];
  10451. },
  10452. remove: function ( key ) {
  10453. delete this.files[ key ];
  10454. },
  10455. clear: function () {
  10456. this.files = {};
  10457. }
  10458. };
  10459. // File:src/loaders/Loader.js
  10460. /**
  10461. * @author alteredq / http://alteredqualia.com/
  10462. */
  10463. THREE.Loader = function () {
  10464. this.onLoadStart = function () {};
  10465. this.onLoadProgress = function () {};
  10466. this.onLoadComplete = function () {};
  10467. };
  10468. THREE.Loader.prototype = {
  10469. constructor: THREE.Loader,
  10470. crossOrigin: undefined,
  10471. extractUrlBase: function ( url ) {
  10472. var parts = url.split( '/' );
  10473. if ( parts.length === 1 ) return './';
  10474. parts.pop();
  10475. return parts.join( '/' ) + '/';
  10476. },
  10477. initMaterials: function ( materials, texturePath, crossOrigin ) {
  10478. var array = [];
  10479. for ( var i = 0; i < materials.length; ++ i ) {
  10480. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  10481. }
  10482. return array;
  10483. },
  10484. createMaterial: ( function () {
  10485. var color, textureLoader, materialLoader;
  10486. return function ( m, texturePath, crossOrigin ) {
  10487. if ( color === undefined ) color = new THREE.Color();
  10488. if ( textureLoader === undefined ) textureLoader = new THREE.TextureLoader();
  10489. if ( materialLoader === undefined ) materialLoader = new THREE.MaterialLoader();
  10490. // convert from old material format
  10491. var textures = {};
  10492. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  10493. var fullPath = texturePath + path;
  10494. var loader = THREE.Loader.Handlers.get( fullPath );
  10495. var texture;
  10496. if ( loader !== null ) {
  10497. texture = loader.load( fullPath );
  10498. } else {
  10499. textureLoader.setCrossOrigin( crossOrigin );
  10500. texture = textureLoader.load( fullPath );
  10501. }
  10502. if ( repeat !== undefined ) {
  10503. texture.repeat.fromArray( repeat );
  10504. if ( repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  10505. if ( repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  10506. }
  10507. if ( offset !== undefined ) {
  10508. texture.offset.fromArray( offset );
  10509. }
  10510. if ( wrap !== undefined ) {
  10511. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = THREE.RepeatWrapping;
  10512. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = THREE.MirroredRepeatWrapping;
  10513. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = THREE.RepeatWrapping;
  10514. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = THREE.MirroredRepeatWrapping;
  10515. }
  10516. if ( anisotropy !== undefined ) {
  10517. texture.anisotropy = anisotropy;
  10518. }
  10519. var uuid = THREE.Math.generateUUID();
  10520. textures[ uuid ] = texture;
  10521. return uuid;
  10522. }
  10523. //
  10524. var json = {
  10525. uuid: THREE.Math.generateUUID(),
  10526. type: 'MeshLambertMaterial'
  10527. };
  10528. for ( var name in m ) {
  10529. var value = m[ name ];
  10530. switch ( name ) {
  10531. case 'DbgColor':
  10532. case 'DbgIndex':
  10533. case 'opticalDensity':
  10534. case 'illumination':
  10535. break;
  10536. case 'DbgName':
  10537. json.name = value;
  10538. break;
  10539. case 'blending':
  10540. json.blending = THREE[ value ];
  10541. break;
  10542. case 'colorAmbient':
  10543. case 'mapAmbient':
  10544. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  10545. break;
  10546. case 'colorDiffuse':
  10547. json.color = color.fromArray( value ).getHex();
  10548. break;
  10549. case 'colorSpecular':
  10550. json.specular = color.fromArray( value ).getHex();
  10551. break;
  10552. case 'colorEmissive':
  10553. json.emissive = color.fromArray( value ).getHex();
  10554. break;
  10555. case 'specularCoef':
  10556. json.shininess = value;
  10557. break;
  10558. case 'shading':
  10559. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  10560. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  10561. break;
  10562. case 'mapDiffuse':
  10563. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  10564. break;
  10565. case 'mapDiffuseRepeat':
  10566. case 'mapDiffuseOffset':
  10567. case 'mapDiffuseWrap':
  10568. case 'mapDiffuseAnisotropy':
  10569. break;
  10570. case 'mapLight':
  10571. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  10572. break;
  10573. case 'mapLightRepeat':
  10574. case 'mapLightOffset':
  10575. case 'mapLightWrap':
  10576. case 'mapLightAnisotropy':
  10577. break;
  10578. case 'mapAO':
  10579. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  10580. break;
  10581. case 'mapAORepeat':
  10582. case 'mapAOOffset':
  10583. case 'mapAOWrap':
  10584. case 'mapAOAnisotropy':
  10585. break;
  10586. case 'mapBump':
  10587. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  10588. break;
  10589. case 'mapBumpScale':
  10590. json.bumpScale = value;
  10591. break;
  10592. case 'mapBumpRepeat':
  10593. case 'mapBumpOffset':
  10594. case 'mapBumpWrap':
  10595. case 'mapBumpAnisotropy':
  10596. break;
  10597. case 'mapNormal':
  10598. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  10599. break;
  10600. case 'mapNormalFactor':
  10601. json.normalScale = [ value, value ];
  10602. break;
  10603. case 'mapNormalRepeat':
  10604. case 'mapNormalOffset':
  10605. case 'mapNormalWrap':
  10606. case 'mapNormalAnisotropy':
  10607. break;
  10608. case 'mapSpecular':
  10609. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  10610. break;
  10611. case 'mapSpecularRepeat':
  10612. case 'mapSpecularOffset':
  10613. case 'mapSpecularWrap':
  10614. case 'mapSpecularAnisotropy':
  10615. break;
  10616. case 'mapAlpha':
  10617. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  10618. break;
  10619. case 'mapAlphaRepeat':
  10620. case 'mapAlphaOffset':
  10621. case 'mapAlphaWrap':
  10622. case 'mapAlphaAnisotropy':
  10623. break;
  10624. case 'flipSided':
  10625. json.side = THREE.BackSide;
  10626. break;
  10627. case 'doubleSided':
  10628. json.side = THREE.DoubleSide;
  10629. break;
  10630. case 'transparency':
  10631. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  10632. json.opacity = value;
  10633. break;
  10634. case 'depthTest':
  10635. case 'depthWrite':
  10636. case 'colorWrite':
  10637. case 'opacity':
  10638. case 'reflectivity':
  10639. case 'transparent':
  10640. case 'visible':
  10641. case 'wireframe':
  10642. json[ name ] = value;
  10643. break;
  10644. case 'vertexColors':
  10645. if ( value === true ) json.vertexColors = THREE.VertexColors;
  10646. if ( value === 'face' ) json.vertexColors = THREE.FaceColors;
  10647. break;
  10648. default:
  10649. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  10650. break;
  10651. }
  10652. }
  10653. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  10654. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  10655. if ( json.opacity < 1 ) json.transparent = true;
  10656. materialLoader.setTextures( textures );
  10657. return materialLoader.parse( json );
  10658. };
  10659. } )()
  10660. };
  10661. THREE.Loader.Handlers = {
  10662. handlers: [],
  10663. add: function ( regex, loader ) {
  10664. this.handlers.push( regex, loader );
  10665. },
  10666. get: function ( file ) {
  10667. var handlers = this.handlers;
  10668. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  10669. var regex = handlers[ i ];
  10670. var loader = handlers[ i + 1 ];
  10671. if ( regex.test( file ) ) {
  10672. return loader;
  10673. }
  10674. }
  10675. return null;
  10676. }
  10677. };
  10678. // File:src/loaders/XHRLoader.js
  10679. /**
  10680. * @author mrdoob / http://mrdoob.com/
  10681. */
  10682. THREE.XHRLoader = function ( manager ) {
  10683. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10684. };
  10685. THREE.XHRLoader.prototype = {
  10686. constructor: THREE.XHRLoader,
  10687. load: function ( url, onLoad, onProgress, onError ) {
  10688. if ( this.path !== undefined ) url = this.path + url;
  10689. var scope = this;
  10690. var cached = THREE.Cache.get( url );
  10691. if ( cached !== undefined ) {
  10692. if ( onLoad ) {
  10693. setTimeout( function () {
  10694. onLoad( cached );
  10695. }, 0 );
  10696. }
  10697. return cached;
  10698. }
  10699. var request = new XMLHttpRequest();
  10700. request.overrideMimeType( 'text/plain' );
  10701. request.open( 'GET', url, true );
  10702. request.addEventListener( 'load', function ( event ) {
  10703. var response = event.target.response;
  10704. THREE.Cache.add( url, response );
  10705. if ( this.status === 200 ) {
  10706. if ( onLoad ) onLoad( response );
  10707. scope.manager.itemEnd( url );
  10708. } else if ( this.status === 0 ) {
  10709. // Some browsers return HTTP Status 0 when using non-http protocol
  10710. // e.g. 'file://' or 'data://'. Handle as success.
  10711. console.warn( 'THREE.XHRLoader: HTTP Status 0 received.' );
  10712. if ( onLoad ) onLoad( response );
  10713. scope.manager.itemEnd( url );
  10714. } else {
  10715. if ( onError ) onError( event );
  10716. scope.manager.itemError( url );
  10717. }
  10718. }, false );
  10719. if ( onProgress !== undefined ) {
  10720. request.addEventListener( 'progress', function ( event ) {
  10721. onProgress( event );
  10722. }, false );
  10723. }
  10724. request.addEventListener( 'error', function ( event ) {
  10725. if ( onError ) onError( event );
  10726. scope.manager.itemError( url );
  10727. }, false );
  10728. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  10729. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  10730. request.send( null );
  10731. scope.manager.itemStart( url );
  10732. return request;
  10733. },
  10734. setPath: function ( value ) {
  10735. this.path = value;
  10736. },
  10737. setResponseType: function ( value ) {
  10738. this.responseType = value;
  10739. },
  10740. setWithCredentials: function ( value ) {
  10741. this.withCredentials = value;
  10742. }
  10743. };
  10744. // File:src/loaders/FontLoader.js
  10745. /**
  10746. * @author mrdoob / http://mrdoob.com/
  10747. */
  10748. THREE.FontLoader = function ( manager ) {
  10749. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10750. };
  10751. THREE.FontLoader.prototype = {
  10752. constructor: THREE.FontLoader,
  10753. load: function ( url, onLoad, onProgress, onError ) {
  10754. var loader = new THREE.XHRLoader( this.manager );
  10755. loader.load( url, function ( text ) {
  10756. onLoad( new THREE.Font( JSON.parse( text.substring( 65, text.length - 2 ) ) ) );
  10757. }, onProgress, onError );
  10758. }
  10759. };
  10760. // File:src/loaders/ImageLoader.js
  10761. /**
  10762. * @author mrdoob / http://mrdoob.com/
  10763. */
  10764. THREE.ImageLoader = function ( manager ) {
  10765. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10766. };
  10767. THREE.ImageLoader.prototype = {
  10768. constructor: THREE.ImageLoader,
  10769. load: function ( url, onLoad, onProgress, onError ) {
  10770. if ( this.path !== undefined ) url = this.path + url;
  10771. var scope = this;
  10772. var cached = THREE.Cache.get( url );
  10773. if ( cached !== undefined ) {
  10774. scope.manager.itemStart( url );
  10775. if ( onLoad ) {
  10776. setTimeout( function () {
  10777. onLoad( cached );
  10778. scope.manager.itemEnd( url );
  10779. }, 0 );
  10780. } else {
  10781. scope.manager.itemEnd( url );
  10782. }
  10783. return cached;
  10784. }
  10785. var image = document.createElement( 'img' );
  10786. image.addEventListener( 'load', function ( event ) {
  10787. THREE.Cache.add( url, this );
  10788. if ( onLoad ) onLoad( this );
  10789. scope.manager.itemEnd( url );
  10790. }, false );
  10791. if ( onProgress !== undefined ) {
  10792. image.addEventListener( 'progress', function ( event ) {
  10793. onProgress( event );
  10794. }, false );
  10795. }
  10796. image.addEventListener( 'error', function ( event ) {
  10797. if ( onError ) onError( event );
  10798. scope.manager.itemError( url );
  10799. }, false );
  10800. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  10801. scope.manager.itemStart( url );
  10802. image.src = url;
  10803. return image;
  10804. },
  10805. setCrossOrigin: function ( value ) {
  10806. this.crossOrigin = value;
  10807. },
  10808. setPath: function ( value ) {
  10809. this.path = value;
  10810. }
  10811. };
  10812. // File:src/loaders/JSONLoader.js
  10813. /**
  10814. * @author mrdoob / http://mrdoob.com/
  10815. * @author alteredq / http://alteredqualia.com/
  10816. */
  10817. THREE.JSONLoader = function ( manager ) {
  10818. if ( typeof manager === 'boolean' ) {
  10819. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  10820. manager = undefined;
  10821. }
  10822. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  10823. this.withCredentials = false;
  10824. };
  10825. THREE.JSONLoader.prototype = {
  10826. constructor: THREE.JSONLoader,
  10827. // Deprecated
  10828. get statusDomElement () {
  10829. if ( this._statusDomElement === undefined ) {
  10830. this._statusDomElement = document.createElement( 'div' );
  10831. }
  10832. console.warn( 'THREE.JSONLoader: .statusDomElement has been removed.' );
  10833. return this._statusDomElement;
  10834. },
  10835. load: function( url, onLoad, onProgress, onError ) {
  10836. var scope = this;
  10837. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : THREE.Loader.prototype.extractUrlBase( url );
  10838. var loader = new THREE.XHRLoader( this.manager );
  10839. loader.setWithCredentials( this.withCredentials );
  10840. loader.load( url, function ( text ) {
  10841. var json = JSON.parse( text );
  10842. var metadata = json.metadata;
  10843. if ( metadata !== undefined ) {
  10844. var type = metadata.type;
  10845. if ( type !== undefined ) {
  10846. if ( type.toLowerCase() === 'object' ) {
  10847. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  10848. return;
  10849. }
  10850. if ( type.toLowerCase() === 'scene' ) {
  10851. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  10852. return;
  10853. }
  10854. }
  10855. }
  10856. var object = scope.parse( json, texturePath );
  10857. onLoad( object.geometry, object.materials );
  10858. }, onProgress, onError );
  10859. },
  10860. setTexturePath: function ( value ) {
  10861. this.texturePath = value;
  10862. },
  10863. parse: function ( json, texturePath ) {
  10864. var geometry = new THREE.Geometry(),
  10865. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  10866. parseModel( scale );
  10867. parseSkin();
  10868. parseMorphing( scale );
  10869. parseAnimations();
  10870. geometry.computeFaceNormals();
  10871. geometry.computeBoundingSphere();
  10872. function parseModel( scale ) {
  10873. function isBitSet( value, position ) {
  10874. return value & ( 1 << position );
  10875. }
  10876. var i, j, fi,
  10877. offset, zLength,
  10878. colorIndex, normalIndex, uvIndex, materialIndex,
  10879. type,
  10880. isQuad,
  10881. hasMaterial,
  10882. hasFaceVertexUv,
  10883. hasFaceNormal, hasFaceVertexNormal,
  10884. hasFaceColor, hasFaceVertexColor,
  10885. vertex, face, faceA, faceB, hex, normal,
  10886. uvLayer, uv, u, v,
  10887. faces = json.faces,
  10888. vertices = json.vertices,
  10889. normals = json.normals,
  10890. colors = json.colors,
  10891. nUvLayers = 0;
  10892. if ( json.uvs !== undefined ) {
  10893. // disregard empty arrays
  10894. for ( i = 0; i < json.uvs.length; i ++ ) {
  10895. if ( json.uvs[ i ].length ) nUvLayers ++;
  10896. }
  10897. for ( i = 0; i < nUvLayers; i ++ ) {
  10898. geometry.faceVertexUvs[ i ] = [];
  10899. }
  10900. }
  10901. offset = 0;
  10902. zLength = vertices.length;
  10903. while ( offset < zLength ) {
  10904. vertex = new THREE.Vector3();
  10905. vertex.x = vertices[ offset ++ ] * scale;
  10906. vertex.y = vertices[ offset ++ ] * scale;
  10907. vertex.z = vertices[ offset ++ ] * scale;
  10908. geometry.vertices.push( vertex );
  10909. }
  10910. offset = 0;
  10911. zLength = faces.length;
  10912. while ( offset < zLength ) {
  10913. type = faces[ offset ++ ];
  10914. isQuad = isBitSet( type, 0 );
  10915. hasMaterial = isBitSet( type, 1 );
  10916. hasFaceVertexUv = isBitSet( type, 3 );
  10917. hasFaceNormal = isBitSet( type, 4 );
  10918. hasFaceVertexNormal = isBitSet( type, 5 );
  10919. hasFaceColor = isBitSet( type, 6 );
  10920. hasFaceVertexColor = isBitSet( type, 7 );
  10921. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  10922. if ( isQuad ) {
  10923. faceA = new THREE.Face3();
  10924. faceA.a = faces[ offset ];
  10925. faceA.b = faces[ offset + 1 ];
  10926. faceA.c = faces[ offset + 3 ];
  10927. faceB = new THREE.Face3();
  10928. faceB.a = faces[ offset + 1 ];
  10929. faceB.b = faces[ offset + 2 ];
  10930. faceB.c = faces[ offset + 3 ];
  10931. offset += 4;
  10932. if ( hasMaterial ) {
  10933. materialIndex = faces[ offset ++ ];
  10934. faceA.materialIndex = materialIndex;
  10935. faceB.materialIndex = materialIndex;
  10936. }
  10937. // to get face <=> uv index correspondence
  10938. fi = geometry.faces.length;
  10939. if ( hasFaceVertexUv ) {
  10940. for ( i = 0; i < nUvLayers; i ++ ) {
  10941. uvLayer = json.uvs[ i ];
  10942. geometry.faceVertexUvs[ i ][ fi ] = [];
  10943. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  10944. for ( j = 0; j < 4; j ++ ) {
  10945. uvIndex = faces[ offset ++ ];
  10946. u = uvLayer[ uvIndex * 2 ];
  10947. v = uvLayer[ uvIndex * 2 + 1 ];
  10948. uv = new THREE.Vector2( u, v );
  10949. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  10950. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  10951. }
  10952. }
  10953. }
  10954. if ( hasFaceNormal ) {
  10955. normalIndex = faces[ offset ++ ] * 3;
  10956. faceA.normal.set(
  10957. normals[ normalIndex ++ ],
  10958. normals[ normalIndex ++ ],
  10959. normals[ normalIndex ]
  10960. );
  10961. faceB.normal.copy( faceA.normal );
  10962. }
  10963. if ( hasFaceVertexNormal ) {
  10964. for ( i = 0; i < 4; i ++ ) {
  10965. normalIndex = faces[ offset ++ ] * 3;
  10966. normal = new THREE.Vector3(
  10967. normals[ normalIndex ++ ],
  10968. normals[ normalIndex ++ ],
  10969. normals[ normalIndex ]
  10970. );
  10971. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  10972. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  10973. }
  10974. }
  10975. if ( hasFaceColor ) {
  10976. colorIndex = faces[ offset ++ ];
  10977. hex = colors[ colorIndex ];
  10978. faceA.color.setHex( hex );
  10979. faceB.color.setHex( hex );
  10980. }
  10981. if ( hasFaceVertexColor ) {
  10982. for ( i = 0; i < 4; i ++ ) {
  10983. colorIndex = faces[ offset ++ ];
  10984. hex = colors[ colorIndex ];
  10985. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  10986. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  10987. }
  10988. }
  10989. geometry.faces.push( faceA );
  10990. geometry.faces.push( faceB );
  10991. } else {
  10992. face = new THREE.Face3();
  10993. face.a = faces[ offset ++ ];
  10994. face.b = faces[ offset ++ ];
  10995. face.c = faces[ offset ++ ];
  10996. if ( hasMaterial ) {
  10997. materialIndex = faces[ offset ++ ];
  10998. face.materialIndex = materialIndex;
  10999. }
  11000. // to get face <=> uv index correspondence
  11001. fi = geometry.faces.length;
  11002. if ( hasFaceVertexUv ) {
  11003. for ( i = 0; i < nUvLayers; i ++ ) {
  11004. uvLayer = json.uvs[ i ];
  11005. geometry.faceVertexUvs[ i ][ fi ] = [];
  11006. for ( j = 0; j < 3; j ++ ) {
  11007. uvIndex = faces[ offset ++ ];
  11008. u = uvLayer[ uvIndex * 2 ];
  11009. v = uvLayer[ uvIndex * 2 + 1 ];
  11010. uv = new THREE.Vector2( u, v );
  11011. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  11012. }
  11013. }
  11014. }
  11015. if ( hasFaceNormal ) {
  11016. normalIndex = faces[ offset ++ ] * 3;
  11017. face.normal.set(
  11018. normals[ normalIndex ++ ],
  11019. normals[ normalIndex ++ ],
  11020. normals[ normalIndex ]
  11021. );
  11022. }
  11023. if ( hasFaceVertexNormal ) {
  11024. for ( i = 0; i < 3; i ++ ) {
  11025. normalIndex = faces[ offset ++ ] * 3;
  11026. normal = new THREE.Vector3(
  11027. normals[ normalIndex ++ ],
  11028. normals[ normalIndex ++ ],
  11029. normals[ normalIndex ]
  11030. );
  11031. face.vertexNormals.push( normal );
  11032. }
  11033. }
  11034. if ( hasFaceColor ) {
  11035. colorIndex = faces[ offset ++ ];
  11036. face.color.setHex( colors[ colorIndex ] );
  11037. }
  11038. if ( hasFaceVertexColor ) {
  11039. for ( i = 0; i < 3; i ++ ) {
  11040. colorIndex = faces[ offset ++ ];
  11041. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  11042. }
  11043. }
  11044. geometry.faces.push( face );
  11045. }
  11046. }
  11047. };
  11048. function parseSkin() {
  11049. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  11050. if ( json.skinWeights ) {
  11051. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  11052. var x = json.skinWeights[ i ];
  11053. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  11054. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  11055. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  11056. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  11057. }
  11058. }
  11059. if ( json.skinIndices ) {
  11060. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  11061. var a = json.skinIndices[ i ];
  11062. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  11063. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  11064. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  11065. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  11066. }
  11067. }
  11068. geometry.bones = json.bones;
  11069. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  11070. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  11071. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  11072. }
  11073. };
  11074. function parseMorphing( scale ) {
  11075. if ( json.morphTargets !== undefined ) {
  11076. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  11077. geometry.morphTargets[ i ] = {};
  11078. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  11079. geometry.morphTargets[ i ].vertices = [];
  11080. var dstVertices = geometry.morphTargets[ i ].vertices;
  11081. var srcVertices = json.morphTargets[ i ].vertices;
  11082. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  11083. var vertex = new THREE.Vector3();
  11084. vertex.x = srcVertices[ v ] * scale;
  11085. vertex.y = srcVertices[ v + 1 ] * scale;
  11086. vertex.z = srcVertices[ v + 2 ] * scale;
  11087. dstVertices.push( vertex );
  11088. }
  11089. }
  11090. }
  11091. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  11092. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  11093. var faces = geometry.faces;
  11094. var morphColors = json.morphColors[ 0 ].colors;
  11095. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  11096. faces[ i ].color.fromArray( morphColors, i * 3 );
  11097. }
  11098. }
  11099. }
  11100. function parseAnimations() {
  11101. var outputAnimations = [];
  11102. // parse old style Bone/Hierarchy animations
  11103. var animations = [];
  11104. if ( json.animation !== undefined ) {
  11105. animations.push( json.animation );
  11106. }
  11107. if ( json.animations !== undefined ) {
  11108. if ( json.animations.length ) {
  11109. animations = animations.concat( json.animations );
  11110. } else {
  11111. animations.push( json.animations );
  11112. }
  11113. }
  11114. for ( var i = 0; i < animations.length; i ++ ) {
  11115. var clip = THREE.AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  11116. if ( clip ) outputAnimations.push( clip );
  11117. }
  11118. // parse implicit morph animations
  11119. if ( geometry.morphTargets ) {
  11120. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  11121. var morphAnimationClips = THREE.AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  11122. outputAnimations = outputAnimations.concat( morphAnimationClips );
  11123. }
  11124. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  11125. };
  11126. if ( json.materials === undefined || json.materials.length === 0 ) {
  11127. return { geometry: geometry };
  11128. } else {
  11129. var materials = THREE.Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  11130. return { geometry: geometry, materials: materials };
  11131. }
  11132. }
  11133. };
  11134. // File:src/loaders/LoadingManager.js
  11135. /**
  11136. * @author mrdoob / http://mrdoob.com/
  11137. */
  11138. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  11139. var scope = this;
  11140. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  11141. this.onStart = undefined;
  11142. this.onLoad = onLoad;
  11143. this.onProgress = onProgress;
  11144. this.onError = onError;
  11145. this.itemStart = function ( url ) {
  11146. itemsTotal ++;
  11147. if ( isLoading === false ) {
  11148. if ( scope.onStart !== undefined ) {
  11149. scope.onStart( url, itemsLoaded, itemsTotal );
  11150. }
  11151. }
  11152. isLoading = true;
  11153. };
  11154. this.itemEnd = function ( url ) {
  11155. itemsLoaded ++;
  11156. if ( scope.onProgress !== undefined ) {
  11157. scope.onProgress( url, itemsLoaded, itemsTotal );
  11158. }
  11159. if ( itemsLoaded === itemsTotal ) {
  11160. isLoading = false;
  11161. if ( scope.onLoad !== undefined ) {
  11162. scope.onLoad();
  11163. }
  11164. }
  11165. };
  11166. this.itemError = function ( url ) {
  11167. if ( scope.onError !== undefined ) {
  11168. scope.onError( url );
  11169. }
  11170. };
  11171. };
  11172. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  11173. // File:src/loaders/BufferGeometryLoader.js
  11174. /**
  11175. * @author mrdoob / http://mrdoob.com/
  11176. */
  11177. THREE.BufferGeometryLoader = function ( manager ) {
  11178. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11179. };
  11180. THREE.BufferGeometryLoader.prototype = {
  11181. constructor: THREE.BufferGeometryLoader,
  11182. load: function ( url, onLoad, onProgress, onError ) {
  11183. var scope = this;
  11184. var loader = new THREE.XHRLoader( scope.manager );
  11185. loader.load( url, function ( text ) {
  11186. onLoad( scope.parse( JSON.parse( text ) ) );
  11187. }, onProgress, onError );
  11188. },
  11189. parse: function ( json ) {
  11190. var geometry = new THREE.BufferGeometry();
  11191. var index = json.data.index;
  11192. var TYPED_ARRAYS = {
  11193. 'Int8Array': Int8Array,
  11194. 'Uint8Array': Uint8Array,
  11195. 'Uint8ClampedArray': Uint8ClampedArray,
  11196. 'Int16Array': Int16Array,
  11197. 'Uint16Array': Uint16Array,
  11198. 'Int32Array': Int32Array,
  11199. 'Uint32Array': Uint32Array,
  11200. 'Float32Array': Float32Array,
  11201. 'Float64Array': Float64Array
  11202. };
  11203. if ( index !== undefined ) {
  11204. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  11205. geometry.setIndex( new THREE.BufferAttribute( typedArray, 1 ) );
  11206. }
  11207. var attributes = json.data.attributes;
  11208. for ( var key in attributes ) {
  11209. var attribute = attributes[ key ];
  11210. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  11211. geometry.addAttribute( key, new THREE.BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  11212. }
  11213. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  11214. if ( groups !== undefined ) {
  11215. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  11216. var group = groups[ i ];
  11217. geometry.addGroup( group.start, group.count, group.materialIndex );
  11218. }
  11219. }
  11220. var boundingSphere = json.data.boundingSphere;
  11221. if ( boundingSphere !== undefined ) {
  11222. var center = new THREE.Vector3();
  11223. if ( boundingSphere.center !== undefined ) {
  11224. center.fromArray( boundingSphere.center );
  11225. }
  11226. geometry.boundingSphere = new THREE.Sphere( center, boundingSphere.radius );
  11227. }
  11228. return geometry;
  11229. }
  11230. };
  11231. // File:src/loaders/MaterialLoader.js
  11232. /**
  11233. * @author mrdoob / http://mrdoob.com/
  11234. */
  11235. THREE.MaterialLoader = function ( manager ) {
  11236. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11237. this.textures = {};
  11238. };
  11239. THREE.MaterialLoader.prototype = {
  11240. constructor: THREE.MaterialLoader,
  11241. load: function ( url, onLoad, onProgress, onError ) {
  11242. var scope = this;
  11243. var loader = new THREE.XHRLoader( scope.manager );
  11244. loader.load( url, function ( text ) {
  11245. onLoad( scope.parse( JSON.parse( text ) ) );
  11246. }, onProgress, onError );
  11247. },
  11248. setTextures: function ( value ) {
  11249. this.textures = value;
  11250. },
  11251. getTexture: function ( name ) {
  11252. var textures = this.textures;
  11253. if ( textures[ name ] === undefined ) {
  11254. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  11255. }
  11256. return textures[ name ];
  11257. },
  11258. parse: function ( json ) {
  11259. var material = new THREE[ json.type ];
  11260. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  11261. if ( json.name !== undefined ) material.name = json.name;
  11262. if ( json.color !== undefined ) material.color.setHex( json.color );
  11263. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  11264. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  11265. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  11266. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  11267. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  11268. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  11269. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  11270. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  11271. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  11272. if ( json.shading !== undefined ) material.shading = json.shading;
  11273. if ( json.blending !== undefined ) material.blending = json.blending;
  11274. if ( json.side !== undefined ) material.side = json.side;
  11275. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  11276. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  11277. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  11278. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  11279. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  11280. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  11281. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  11282. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  11283. // for PointsMaterial
  11284. if ( json.size !== undefined ) material.size = json.size;
  11285. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  11286. // maps
  11287. if ( json.map !== undefined ) material.map = this.getTexture( json.map );
  11288. if ( json.alphaMap !== undefined ) {
  11289. material.alphaMap = this.getTexture( json.alphaMap );
  11290. material.transparent = true;
  11291. }
  11292. if ( json.bumpMap !== undefined ) material.bumpMap = this.getTexture( json.bumpMap );
  11293. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  11294. if ( json.normalMap !== undefined ) material.normalMap = this.getTexture( json.normalMap );
  11295. if ( json.normalScale !== undefined ) {
  11296. var normalScale = json.normalScale;
  11297. if ( Array.isArray( normalScale ) === false ) {
  11298. // Blender exporter used to export a scalar. See #7459
  11299. normalScale = [ normalScale, normalScale ];
  11300. }
  11301. material.normalScale = new THREE.Vector2().fromArray( normalScale );
  11302. }
  11303. if ( json.displacementMap !== undefined ) material.displacementMap = this.getTexture( json.displacementMap );
  11304. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  11305. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  11306. if ( json.roughnessMap !== undefined ) material.roughnessMap = this.getTexture( json.roughnessMap );
  11307. if ( json.metalnessMap !== undefined ) material.metalnessMap = this.getTexture( json.metalnessMap );
  11308. if ( json.emissiveMap !== undefined ) material.emissiveMap = this.getTexture( json.emissiveMap );
  11309. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  11310. if ( json.specularMap !== undefined ) material.specularMap = this.getTexture( json.specularMap );
  11311. if ( json.envMap !== undefined ) {
  11312. material.envMap = this.getTexture( json.envMap );
  11313. material.combine = THREE.MultiplyOperation;
  11314. }
  11315. if ( json.reflectivity ) material.reflectivity = json.reflectivity;
  11316. if ( json.lightMap !== undefined ) material.lightMap = this.getTexture( json.lightMap );
  11317. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  11318. if ( json.aoMap !== undefined ) material.aoMap = this.getTexture( json.aoMap );
  11319. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  11320. // MultiMaterial
  11321. if ( json.materials !== undefined ) {
  11322. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  11323. material.materials.push( this.parse( json.materials[ i ] ) );
  11324. }
  11325. }
  11326. return material;
  11327. }
  11328. };
  11329. // File:src/loaders/ObjectLoader.js
  11330. /**
  11331. * @author mrdoob / http://mrdoob.com/
  11332. */
  11333. THREE.ObjectLoader = function ( manager ) {
  11334. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11335. this.texturePath = '';
  11336. };
  11337. THREE.ObjectLoader.prototype = {
  11338. constructor: THREE.ObjectLoader,
  11339. load: function ( url, onLoad, onProgress, onError ) {
  11340. if ( this.texturePath === '' ) {
  11341. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  11342. }
  11343. var scope = this;
  11344. var loader = new THREE.XHRLoader( scope.manager );
  11345. loader.load( url, function ( text ) {
  11346. scope.parse( JSON.parse( text ), onLoad );
  11347. }, onProgress, onError );
  11348. },
  11349. setTexturePath: function ( value ) {
  11350. this.texturePath = value;
  11351. },
  11352. setCrossOrigin: function ( value ) {
  11353. this.crossOrigin = value;
  11354. },
  11355. parse: function ( json, onLoad ) {
  11356. var geometries = this.parseGeometries( json.geometries );
  11357. var images = this.parseImages( json.images, function () {
  11358. if ( onLoad !== undefined ) onLoad( object );
  11359. } );
  11360. var textures = this.parseTextures( json.textures, images );
  11361. var materials = this.parseMaterials( json.materials, textures );
  11362. var object = this.parseObject( json.object, geometries, materials );
  11363. if ( json.animations ) {
  11364. object.animations = this.parseAnimations( json.animations );
  11365. }
  11366. if ( json.images === undefined || json.images.length === 0 ) {
  11367. if ( onLoad !== undefined ) onLoad( object );
  11368. }
  11369. return object;
  11370. },
  11371. parseGeometries: function ( json ) {
  11372. var geometries = {};
  11373. if ( json !== undefined ) {
  11374. var geometryLoader = new THREE.JSONLoader();
  11375. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  11376. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11377. var geometry;
  11378. var data = json[ i ];
  11379. switch ( data.type ) {
  11380. case 'PlaneGeometry':
  11381. case 'PlaneBufferGeometry':
  11382. geometry = new THREE[ data.type ](
  11383. data.width,
  11384. data.height,
  11385. data.widthSegments,
  11386. data.heightSegments
  11387. );
  11388. break;
  11389. case 'BoxGeometry':
  11390. case 'BoxBufferGeometry':
  11391. case 'CubeGeometry': // backwards compatible
  11392. geometry = new THREE[ data.type ](
  11393. data.width,
  11394. data.height,
  11395. data.depth,
  11396. data.widthSegments,
  11397. data.heightSegments,
  11398. data.depthSegments
  11399. );
  11400. break;
  11401. case 'CircleGeometry':
  11402. case 'CircleBufferGeometry':
  11403. geometry = new THREE[ data.type ](
  11404. data.radius,
  11405. data.segments,
  11406. data.thetaStart,
  11407. data.thetaLength
  11408. );
  11409. break;
  11410. case 'CylinderGeometry':
  11411. case 'CylinderBufferGeometry':
  11412. geometry = new THREE[ data.type ](
  11413. data.radiusTop,
  11414. data.radiusBottom,
  11415. data.height,
  11416. data.radialSegments,
  11417. data.heightSegments,
  11418. data.openEnded,
  11419. data.thetaStart,
  11420. data.thetaLength
  11421. );
  11422. break;
  11423. case 'SphereGeometry':
  11424. case 'SphereBufferGeometry':
  11425. geometry = new THREE[ data.type ](
  11426. data.radius,
  11427. data.widthSegments,
  11428. data.heightSegments,
  11429. data.phiStart,
  11430. data.phiLength,
  11431. data.thetaStart,
  11432. data.thetaLength
  11433. );
  11434. break;
  11435. case 'DodecahedronGeometry':
  11436. geometry = new THREE.DodecahedronGeometry(
  11437. data.radius,
  11438. data.detail
  11439. );
  11440. break;
  11441. case 'IcosahedronGeometry':
  11442. geometry = new THREE.IcosahedronGeometry(
  11443. data.radius,
  11444. data.detail
  11445. );
  11446. break;
  11447. case 'OctahedronGeometry':
  11448. geometry = new THREE.OctahedronGeometry(
  11449. data.radius,
  11450. data.detail
  11451. );
  11452. break;
  11453. case 'TetrahedronGeometry':
  11454. geometry = new THREE.TetrahedronGeometry(
  11455. data.radius,
  11456. data.detail
  11457. );
  11458. break;
  11459. case 'RingGeometry':
  11460. case 'RingBufferGeometry':
  11461. geometry = new THREE[ data.type ](
  11462. data.innerRadius,
  11463. data.outerRadius,
  11464. data.thetaSegments,
  11465. data.phiSegments,
  11466. data.thetaStart,
  11467. data.thetaLength
  11468. );
  11469. break;
  11470. case 'TorusGeometry':
  11471. case 'TorusBufferGeometry':
  11472. geometry = new THREE[ data.type ](
  11473. data.radius,
  11474. data.tube,
  11475. data.radialSegments,
  11476. data.tubularSegments,
  11477. data.arc
  11478. );
  11479. break;
  11480. case 'TorusKnotGeometry':
  11481. case 'TorusKnotBufferGeometry':
  11482. geometry = new THREE[ data.type ](
  11483. data.radius,
  11484. data.tube,
  11485. data.tubularSegments,
  11486. data.radialSegments,
  11487. data.p,
  11488. data.q
  11489. );
  11490. break;
  11491. case 'LatheGeometry':
  11492. case 'LatheBufferGeometry':
  11493. geometry = new THREE[ data.type ](
  11494. data.points,
  11495. data.segments,
  11496. data.phiStart,
  11497. data.phiLength
  11498. );
  11499. break;
  11500. case 'BufferGeometry':
  11501. geometry = bufferGeometryLoader.parse( data );
  11502. break;
  11503. case 'Geometry':
  11504. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  11505. break;
  11506. default:
  11507. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  11508. continue;
  11509. }
  11510. geometry.uuid = data.uuid;
  11511. if ( data.name !== undefined ) geometry.name = data.name;
  11512. geometries[ data.uuid ] = geometry;
  11513. }
  11514. }
  11515. return geometries;
  11516. },
  11517. parseMaterials: function ( json, textures ) {
  11518. var materials = {};
  11519. if ( json !== undefined ) {
  11520. var loader = new THREE.MaterialLoader();
  11521. loader.setTextures( textures );
  11522. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11523. var material = loader.parse( json[ i ] );
  11524. materials[ material.uuid ] = material;
  11525. }
  11526. }
  11527. return materials;
  11528. },
  11529. parseAnimations: function ( json ) {
  11530. var animations = [];
  11531. for ( var i = 0; i < json.length; i ++ ) {
  11532. var clip = THREE.AnimationClip.parse( json[ i ] );
  11533. animations.push( clip );
  11534. }
  11535. return animations;
  11536. },
  11537. parseImages: function ( json, onLoad ) {
  11538. var scope = this;
  11539. var images = {};
  11540. function loadImage( url ) {
  11541. scope.manager.itemStart( url );
  11542. return loader.load( url, function () {
  11543. scope.manager.itemEnd( url );
  11544. } );
  11545. }
  11546. if ( json !== undefined && json.length > 0 ) {
  11547. var manager = new THREE.LoadingManager( onLoad );
  11548. var loader = new THREE.ImageLoader( manager );
  11549. loader.setCrossOrigin( this.crossOrigin );
  11550. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11551. var image = json[ i ];
  11552. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  11553. images[ image.uuid ] = loadImage( path );
  11554. }
  11555. }
  11556. return images;
  11557. },
  11558. parseTextures: function ( json, images ) {
  11559. function parseConstant( value ) {
  11560. if ( typeof( value ) === 'number' ) return value;
  11561. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  11562. return THREE[ value ];
  11563. }
  11564. var textures = {};
  11565. if ( json !== undefined ) {
  11566. for ( var i = 0, l = json.length; i < l; i ++ ) {
  11567. var data = json[ i ];
  11568. if ( data.image === undefined ) {
  11569. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  11570. }
  11571. if ( images[ data.image ] === undefined ) {
  11572. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  11573. }
  11574. var texture = new THREE.Texture( images[ data.image ] );
  11575. texture.needsUpdate = true;
  11576. texture.uuid = data.uuid;
  11577. if ( data.name !== undefined ) texture.name = data.name;
  11578. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping );
  11579. if ( data.offset !== undefined ) texture.offset = new THREE.Vector2( data.offset[ 0 ], data.offset[ 1 ] );
  11580. if ( data.repeat !== undefined ) texture.repeat = new THREE.Vector2( data.repeat[ 0 ], data.repeat[ 1 ] );
  11581. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter );
  11582. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter );
  11583. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  11584. if ( Array.isArray( data.wrap ) ) {
  11585. texture.wrapS = parseConstant( data.wrap[ 0 ] );
  11586. texture.wrapT = parseConstant( data.wrap[ 1 ] );
  11587. }
  11588. textures[ data.uuid ] = texture;
  11589. }
  11590. }
  11591. return textures;
  11592. },
  11593. parseObject: function () {
  11594. var matrix = new THREE.Matrix4();
  11595. return function ( data, geometries, materials ) {
  11596. var object;
  11597. function getGeometry( name ) {
  11598. if ( geometries[ name ] === undefined ) {
  11599. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  11600. }
  11601. return geometries[ name ];
  11602. }
  11603. function getMaterial( name ) {
  11604. if ( name === undefined ) return undefined;
  11605. if ( materials[ name ] === undefined ) {
  11606. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  11607. }
  11608. return materials[ name ];
  11609. }
  11610. switch ( data.type ) {
  11611. case 'Scene':
  11612. object = new THREE.Scene();
  11613. break;
  11614. case 'PerspectiveCamera':
  11615. object = new THREE.PerspectiveCamera(
  11616. data.fov, data.aspect, data.near, data.far );
  11617. if ( data.focus !== undefined ) object.focus = data.focus;
  11618. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  11619. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  11620. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  11621. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  11622. break;
  11623. case 'OrthographicCamera':
  11624. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  11625. break;
  11626. case 'AmbientLight':
  11627. object = new THREE.AmbientLight( data.color, data.intensity );
  11628. break;
  11629. case 'DirectionalLight':
  11630. object = new THREE.DirectionalLight( data.color, data.intensity );
  11631. break;
  11632. case 'PointLight':
  11633. object = new THREE.PointLight( data.color, data.intensity, data.distance, data.decay );
  11634. break;
  11635. case 'SpotLight':
  11636. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  11637. break;
  11638. case 'HemisphereLight':
  11639. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  11640. break;
  11641. case 'Mesh':
  11642. var geometry = getGeometry( data.geometry );
  11643. var material = getMaterial( data.material );
  11644. if ( geometry.bones && geometry.bones.length > 0 ) {
  11645. object = new THREE.SkinnedMesh( geometry, material );
  11646. } else {
  11647. object = new THREE.Mesh( geometry, material );
  11648. }
  11649. break;
  11650. case 'LOD':
  11651. object = new THREE.LOD();
  11652. break;
  11653. case 'Line':
  11654. object = new THREE.Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  11655. break;
  11656. case 'PointCloud':
  11657. case 'Points':
  11658. object = new THREE.Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  11659. break;
  11660. case 'Sprite':
  11661. object = new THREE.Sprite( getMaterial( data.material ) );
  11662. break;
  11663. case 'Group':
  11664. object = new THREE.Group();
  11665. break;
  11666. default:
  11667. object = new THREE.Object3D();
  11668. }
  11669. object.uuid = data.uuid;
  11670. if ( data.name !== undefined ) object.name = data.name;
  11671. if ( data.matrix !== undefined ) {
  11672. matrix.fromArray( data.matrix );
  11673. matrix.decompose( object.position, object.quaternion, object.scale );
  11674. } else {
  11675. if ( data.position !== undefined ) object.position.fromArray( data.position );
  11676. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  11677. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  11678. }
  11679. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  11680. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  11681. if ( data.visible !== undefined ) object.visible = data.visible;
  11682. if ( data.userData !== undefined ) object.userData = data.userData;
  11683. if ( data.children !== undefined ) {
  11684. for ( var child in data.children ) {
  11685. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  11686. }
  11687. }
  11688. if ( data.type === 'LOD' ) {
  11689. var levels = data.levels;
  11690. for ( var l = 0; l < levels.length; l ++ ) {
  11691. var level = levels[ l ];
  11692. var child = object.getObjectByProperty( 'uuid', level.object );
  11693. if ( child !== undefined ) {
  11694. object.addLevel( child, level.distance );
  11695. }
  11696. }
  11697. }
  11698. return object;
  11699. };
  11700. }()
  11701. };
  11702. // File:src/loaders/TextureLoader.js
  11703. /**
  11704. * @author mrdoob / http://mrdoob.com/
  11705. */
  11706. THREE.TextureLoader = function ( manager ) {
  11707. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11708. };
  11709. THREE.TextureLoader.prototype = {
  11710. constructor: THREE.TextureLoader,
  11711. load: function ( url, onLoad, onProgress, onError ) {
  11712. var texture = new THREE.Texture();
  11713. var loader = new THREE.ImageLoader( this.manager );
  11714. loader.setCrossOrigin( this.crossOrigin );
  11715. loader.setPath( this.path );
  11716. loader.load( url, function ( image ) {
  11717. texture.image = image;
  11718. texture.needsUpdate = true;
  11719. if ( onLoad !== undefined ) {
  11720. onLoad( texture );
  11721. }
  11722. }, onProgress, onError );
  11723. return texture;
  11724. },
  11725. setCrossOrigin: function ( value ) {
  11726. this.crossOrigin = value;
  11727. },
  11728. setPath: function ( value ) {
  11729. this.path = value;
  11730. }
  11731. };
  11732. // File:src/loaders/CubeTextureLoader.js
  11733. /**
  11734. * @author mrdoob / http://mrdoob.com/
  11735. */
  11736. THREE.CubeTextureLoader = function ( manager ) {
  11737. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11738. };
  11739. THREE.CubeTextureLoader.prototype = {
  11740. constructor: THREE.CubeTextureLoader,
  11741. load: function ( urls, onLoad, onProgress, onError ) {
  11742. var texture = new THREE.CubeTexture();
  11743. var loader = new THREE.ImageLoader( this.manager );
  11744. loader.setCrossOrigin( this.crossOrigin );
  11745. loader.setPath( this.path );
  11746. var loaded = 0;
  11747. function loadTexture( i ) {
  11748. loader.load( urls[ i ], function ( image ) {
  11749. texture.images[ i ] = image;
  11750. loaded ++;
  11751. if ( loaded === 6 ) {
  11752. texture.needsUpdate = true;
  11753. if ( onLoad ) onLoad( texture );
  11754. }
  11755. }, undefined, onError );
  11756. }
  11757. for ( var i = 0; i < urls.length; ++ i ) {
  11758. loadTexture( i );
  11759. }
  11760. return texture;
  11761. },
  11762. setCrossOrigin: function ( value ) {
  11763. this.crossOrigin = value;
  11764. },
  11765. setPath: function ( value ) {
  11766. this.path = value;
  11767. }
  11768. };
  11769. // File:src/loaders/BinaryTextureLoader.js
  11770. /**
  11771. * @author Nikos M. / https://github.com/foo123/
  11772. *
  11773. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  11774. */
  11775. THREE.DataTextureLoader = THREE.BinaryTextureLoader = function ( manager ) {
  11776. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11777. // override in sub classes
  11778. this._parser = null;
  11779. };
  11780. THREE.BinaryTextureLoader.prototype = {
  11781. constructor: THREE.BinaryTextureLoader,
  11782. load: function ( url, onLoad, onProgress, onError ) {
  11783. var scope = this;
  11784. var texture = new THREE.DataTexture();
  11785. var loader = new THREE.XHRLoader( this.manager );
  11786. loader.setResponseType( 'arraybuffer' );
  11787. loader.load( url, function ( buffer ) {
  11788. var texData = scope._parser( buffer );
  11789. if ( ! texData ) return;
  11790. if ( undefined !== texData.image ) {
  11791. texture.image = texData.image;
  11792. } else if ( undefined !== texData.data ) {
  11793. texture.image.width = texData.width;
  11794. texture.image.height = texData.height;
  11795. texture.image.data = texData.data;
  11796. }
  11797. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
  11798. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;
  11799. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
  11800. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;
  11801. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  11802. if ( undefined !== texData.format ) {
  11803. texture.format = texData.format;
  11804. }
  11805. if ( undefined !== texData.type ) {
  11806. texture.type = texData.type;
  11807. }
  11808. if ( undefined !== texData.mipmaps ) {
  11809. texture.mipmaps = texData.mipmaps;
  11810. }
  11811. if ( 1 === texData.mipmapCount ) {
  11812. texture.minFilter = THREE.LinearFilter;
  11813. }
  11814. texture.needsUpdate = true;
  11815. if ( onLoad ) onLoad( texture, texData );
  11816. }, onProgress, onError );
  11817. return texture;
  11818. }
  11819. };
  11820. // File:src/loaders/CompressedTextureLoader.js
  11821. /**
  11822. * @author mrdoob / http://mrdoob.com/
  11823. *
  11824. * Abstract Base class to block based textures loader (dds, pvr, ...)
  11825. */
  11826. THREE.CompressedTextureLoader = function ( manager ) {
  11827. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  11828. // override in sub classes
  11829. this._parser = null;
  11830. };
  11831. THREE.CompressedTextureLoader.prototype = {
  11832. constructor: THREE.CompressedTextureLoader,
  11833. load: function ( url, onLoad, onProgress, onError ) {
  11834. var scope = this;
  11835. var images = [];
  11836. var texture = new THREE.CompressedTexture();
  11837. texture.image = images;
  11838. var loader = new THREE.XHRLoader( this.manager );
  11839. loader.setPath( this.path );
  11840. loader.setResponseType( 'arraybuffer' );
  11841. function loadTexture( i ) {
  11842. loader.load( url[ i ], function ( buffer ) {
  11843. var texDatas = scope._parser( buffer, true );
  11844. images[ i ] = {
  11845. width: texDatas.width,
  11846. height: texDatas.height,
  11847. format: texDatas.format,
  11848. mipmaps: texDatas.mipmaps
  11849. };
  11850. loaded += 1;
  11851. if ( loaded === 6 ) {
  11852. if ( texDatas.mipmapCount === 1 )
  11853. texture.minFilter = THREE.LinearFilter;
  11854. texture.format = texDatas.format;
  11855. texture.needsUpdate = true;
  11856. if ( onLoad ) onLoad( texture );
  11857. }
  11858. }, onProgress, onError );
  11859. }
  11860. if ( Array.isArray( url ) ) {
  11861. var loaded = 0;
  11862. for ( var i = 0, il = url.length; i < il; ++ i ) {
  11863. loadTexture( i );
  11864. }
  11865. } else {
  11866. // compressed cubemap texture stored in a single DDS file
  11867. loader.load( url, function ( buffer ) {
  11868. var texDatas = scope._parser( buffer, true );
  11869. if ( texDatas.isCubemap ) {
  11870. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  11871. for ( var f = 0; f < faces; f ++ ) {
  11872. images[ f ] = { mipmaps : [] };
  11873. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  11874. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  11875. images[ f ].format = texDatas.format;
  11876. images[ f ].width = texDatas.width;
  11877. images[ f ].height = texDatas.height;
  11878. }
  11879. }
  11880. } else {
  11881. texture.image.width = texDatas.width;
  11882. texture.image.height = texDatas.height;
  11883. texture.mipmaps = texDatas.mipmaps;
  11884. }
  11885. if ( texDatas.mipmapCount === 1 ) {
  11886. texture.minFilter = THREE.LinearFilter;
  11887. }
  11888. texture.format = texDatas.format;
  11889. texture.needsUpdate = true;
  11890. if ( onLoad ) onLoad( texture );
  11891. }, onProgress, onError );
  11892. }
  11893. return texture;
  11894. },
  11895. setPath: function ( value ) {
  11896. this.path = value;
  11897. }
  11898. };
  11899. // File:src/materials/Material.js
  11900. /**
  11901. * @author mrdoob / http://mrdoob.com/
  11902. * @author alteredq / http://alteredqualia.com/
  11903. */
  11904. THREE.Material = function () {
  11905. Object.defineProperty( this, 'id', { value: THREE.MaterialIdCount ++ } );
  11906. this.uuid = THREE.Math.generateUUID();
  11907. this.name = '';
  11908. this.type = 'Material';
  11909. this.side = THREE.FrontSide;
  11910. this.opacity = 1;
  11911. this.transparent = false;
  11912. this.blending = THREE.NormalBlending;
  11913. this.blendSrc = THREE.SrcAlphaFactor;
  11914. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  11915. this.blendEquation = THREE.AddEquation;
  11916. this.blendSrcAlpha = null;
  11917. this.blendDstAlpha = null;
  11918. this.blendEquationAlpha = null;
  11919. this.depthFunc = THREE.LessEqualDepth;
  11920. this.depthTest = true;
  11921. this.depthWrite = true;
  11922. this.clippingPlanes = null;
  11923. this.clipShadows = false;
  11924. this.colorWrite = true;
  11925. this.precision = null; // override the renderer's default precision for this material
  11926. this.polygonOffset = false;
  11927. this.polygonOffsetFactor = 0;
  11928. this.polygonOffsetUnits = 0;
  11929. this.alphaTest = 0;
  11930. this.premultipliedAlpha = false;
  11931. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  11932. this.visible = true;
  11933. this._needsUpdate = true;
  11934. };
  11935. THREE.Material.prototype = {
  11936. constructor: THREE.Material,
  11937. get needsUpdate () {
  11938. return this._needsUpdate;
  11939. },
  11940. set needsUpdate ( value ) {
  11941. if ( value === true ) this.update();
  11942. this._needsUpdate = value;
  11943. },
  11944. setValues: function ( values ) {
  11945. if ( values === undefined ) return;
  11946. for ( var key in values ) {
  11947. var newValue = values[ key ];
  11948. if ( newValue === undefined ) {
  11949. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  11950. continue;
  11951. }
  11952. var currentValue = this[ key ];
  11953. if ( currentValue === undefined ) {
  11954. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  11955. continue;
  11956. }
  11957. if ( currentValue instanceof THREE.Color ) {
  11958. currentValue.set( newValue );
  11959. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  11960. currentValue.copy( newValue );
  11961. } else if ( key === 'overdraw' ) {
  11962. // ensure overdraw is backwards-compatible with legacy boolean type
  11963. this[ key ] = Number( newValue );
  11964. } else {
  11965. this[ key ] = newValue;
  11966. }
  11967. }
  11968. },
  11969. toJSON: function ( meta ) {
  11970. var isRoot = meta === undefined;
  11971. if ( isRoot ) {
  11972. meta = {
  11973. textures: {},
  11974. images: {}
  11975. };
  11976. }
  11977. var data = {
  11978. metadata: {
  11979. version: 4.4,
  11980. type: 'Material',
  11981. generator: 'Material.toJSON'
  11982. }
  11983. };
  11984. // standard Material serialization
  11985. data.uuid = this.uuid;
  11986. data.type = this.type;
  11987. if ( this.name !== '' ) data.name = this.name;
  11988. if ( this.color instanceof THREE.Color ) data.color = this.color.getHex();
  11989. if ( this.roughness !== 0.5 ) data.roughness = this.roughness;
  11990. if ( this.metalness !== 0.5 ) data.metalness = this.metalness;
  11991. if ( this.emissive instanceof THREE.Color ) data.emissive = this.emissive.getHex();
  11992. if ( this.specular instanceof THREE.Color ) data.specular = this.specular.getHex();
  11993. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  11994. if ( this.map instanceof THREE.Texture ) data.map = this.map.toJSON( meta ).uuid;
  11995. if ( this.alphaMap instanceof THREE.Texture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  11996. if ( this.lightMap instanceof THREE.Texture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  11997. if ( this.bumpMap instanceof THREE.Texture ) {
  11998. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  11999. data.bumpScale = this.bumpScale;
  12000. }
  12001. if ( this.normalMap instanceof THREE.Texture ) {
  12002. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12003. data.normalScale = this.normalScale.toArray();
  12004. }
  12005. if ( this.displacementMap instanceof THREE.Texture ) {
  12006. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12007. data.displacementScale = this.displacementScale;
  12008. data.displacementBias = this.displacementBias;
  12009. }
  12010. if ( this.roughnessMap instanceof THREE.Texture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12011. if ( this.metalnessMap instanceof THREE.Texture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12012. if ( this.emissiveMap instanceof THREE.Texture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12013. if ( this.specularMap instanceof THREE.Texture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12014. if ( this.envMap instanceof THREE.Texture ) {
  12015. data.envMap = this.envMap.toJSON( meta ).uuid;
  12016. data.reflectivity = this.reflectivity; // Scale behind envMap
  12017. }
  12018. if ( this.size !== undefined ) data.size = this.size;
  12019. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12020. if ( this.vertexColors !== undefined && this.vertexColors !== THREE.NoColors ) data.vertexColors = this.vertexColors;
  12021. if ( this.shading !== undefined && this.shading !== THREE.SmoothShading ) data.shading = this.shading;
  12022. if ( this.blending !== undefined && this.blending !== THREE.NormalBlending ) data.blending = this.blending;
  12023. if ( this.side !== undefined && this.side !== THREE.FrontSide ) data.side = this.side;
  12024. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12025. if ( this.transparent === true ) data.transparent = this.transparent;
  12026. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12027. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  12028. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  12029. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12030. // TODO: Copied from Object3D.toJSON
  12031. function extractFromCache ( cache ) {
  12032. var values = [];
  12033. for ( var key in cache ) {
  12034. var data = cache[ key ];
  12035. delete data.metadata;
  12036. values.push( data );
  12037. }
  12038. return values;
  12039. }
  12040. if ( isRoot ) {
  12041. var textures = extractFromCache( meta.textures );
  12042. var images = extractFromCache( meta.images );
  12043. if ( textures.length > 0 ) data.textures = textures;
  12044. if ( images.length > 0 ) data.images = images;
  12045. }
  12046. return data;
  12047. },
  12048. clone: function () {
  12049. return new this.constructor().copy( this );
  12050. },
  12051. copy: function ( source ) {
  12052. this.name = source.name;
  12053. this.side = source.side;
  12054. this.opacity = source.opacity;
  12055. this.transparent = source.transparent;
  12056. this.blending = source.blending;
  12057. this.blendSrc = source.blendSrc;
  12058. this.blendDst = source.blendDst;
  12059. this.blendEquation = source.blendEquation;
  12060. this.blendSrcAlpha = source.blendSrcAlpha;
  12061. this.blendDstAlpha = source.blendDstAlpha;
  12062. this.blendEquationAlpha = source.blendEquationAlpha;
  12063. this.depthFunc = source.depthFunc;
  12064. this.depthTest = source.depthTest;
  12065. this.depthWrite = source.depthWrite;
  12066. this.colorWrite = source.colorWrite;
  12067. this.precision = source.precision;
  12068. this.polygonOffset = source.polygonOffset;
  12069. this.polygonOffsetFactor = source.polygonOffsetFactor;
  12070. this.polygonOffsetUnits = source.polygonOffsetUnits;
  12071. this.alphaTest = source.alphaTest;
  12072. this.premultipliedAlpha = source.premultipliedAlpha;
  12073. this.overdraw = source.overdraw;
  12074. this.visible = source.visible;
  12075. this.clipShadows = source.clipShadows;
  12076. var srcPlanes = source.clippingPlanes,
  12077. dstPlanes = null;
  12078. if ( srcPlanes !== null ) {
  12079. var n = srcPlanes.length;
  12080. dstPlanes = new Array( n );
  12081. for ( var i = 0; i !== n; ++ i )
  12082. dstPlanes[ i ] = srcPlanes[ i ].clone();
  12083. }
  12084. this.clippingPlanes = dstPlanes;
  12085. return this;
  12086. },
  12087. update: function () {
  12088. this.dispatchEvent( { type: 'update' } );
  12089. },
  12090. dispose: function () {
  12091. this.dispatchEvent( { type: 'dispose' } );
  12092. }
  12093. };
  12094. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  12095. THREE.MaterialIdCount = 0;
  12096. // File:src/materials/LineBasicMaterial.js
  12097. /**
  12098. * @author mrdoob / http://mrdoob.com/
  12099. * @author alteredq / http://alteredqualia.com/
  12100. *
  12101. * parameters = {
  12102. * color: <hex>,
  12103. * opacity: <float>,
  12104. *
  12105. * linewidth: <float>,
  12106. * linecap: "round",
  12107. * linejoin: "round",
  12108. *
  12109. * blending: THREE.NormalBlending,
  12110. * depthTest: <bool>,
  12111. * depthWrite: <bool>,
  12112. *
  12113. * vertexColors: <bool>
  12114. *
  12115. * fog: <bool>
  12116. * }
  12117. */
  12118. THREE.LineBasicMaterial = function ( parameters ) {
  12119. THREE.Material.call( this );
  12120. this.type = 'LineBasicMaterial';
  12121. this.color = new THREE.Color( 0xffffff );
  12122. this.linewidth = 1;
  12123. this.linecap = 'round';
  12124. this.linejoin = 'round';
  12125. this.blending = THREE.NormalBlending;
  12126. this.vertexColors = THREE.NoColors;
  12127. this.fog = true;
  12128. this.setValues( parameters );
  12129. };
  12130. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  12131. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  12132. THREE.LineBasicMaterial.prototype.copy = function ( source ) {
  12133. THREE.Material.prototype.copy.call( this, source );
  12134. this.color.copy( source.color );
  12135. this.linewidth = source.linewidth;
  12136. this.linecap = source.linecap;
  12137. this.linejoin = source.linejoin;
  12138. this.vertexColors = source.vertexColors;
  12139. this.fog = source.fog;
  12140. return this;
  12141. };
  12142. // File:src/materials/LineDashedMaterial.js
  12143. /**
  12144. * @author alteredq / http://alteredqualia.com/
  12145. *
  12146. * parameters = {
  12147. * color: <hex>,
  12148. * opacity: <float>,
  12149. *
  12150. * linewidth: <float>,
  12151. *
  12152. * scale: <float>,
  12153. * dashSize: <float>,
  12154. * gapSize: <float>,
  12155. *
  12156. * blending: THREE.NormalBlending,
  12157. * depthTest: <bool>,
  12158. * depthWrite: <bool>,
  12159. *
  12160. * vertexColors: THREE.NoColors / THREE.FaceColors / THREE.VertexColors
  12161. *
  12162. * fog: <bool>
  12163. * }
  12164. */
  12165. THREE.LineDashedMaterial = function ( parameters ) {
  12166. THREE.Material.call( this );
  12167. this.type = 'LineDashedMaterial';
  12168. this.color = new THREE.Color( 0xffffff );
  12169. this.linewidth = 1;
  12170. this.scale = 1;
  12171. this.dashSize = 3;
  12172. this.gapSize = 1;
  12173. this.blending = THREE.NormalBlending;
  12174. this.vertexColors = THREE.NoColors;
  12175. this.fog = true;
  12176. this.setValues( parameters );
  12177. };
  12178. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  12179. THREE.LineDashedMaterial.prototype.constructor = THREE.LineDashedMaterial;
  12180. THREE.LineDashedMaterial.prototype.copy = function ( source ) {
  12181. THREE.Material.prototype.copy.call( this, source );
  12182. this.color.copy( source.color );
  12183. this.linewidth = source.linewidth;
  12184. this.scale = source.scale;
  12185. this.dashSize = source.dashSize;
  12186. this.gapSize = source.gapSize;
  12187. this.vertexColors = source.vertexColors;
  12188. this.fog = source.fog;
  12189. return this;
  12190. };
  12191. // File:src/materials/MeshBasicMaterial.js
  12192. /**
  12193. * @author mrdoob / http://mrdoob.com/
  12194. * @author alteredq / http://alteredqualia.com/
  12195. *
  12196. * parameters = {
  12197. * color: <hex>,
  12198. * opacity: <float>,
  12199. * map: new THREE.Texture( <Image> ),
  12200. *
  12201. * aoMap: new THREE.Texture( <Image> ),
  12202. * aoMapIntensity: <float>
  12203. *
  12204. * specularMap: new THREE.Texture( <Image> ),
  12205. *
  12206. * alphaMap: new THREE.Texture( <Image> ),
  12207. *
  12208. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  12209. * combine: THREE.Multiply,
  12210. * reflectivity: <float>,
  12211. * refractionRatio: <float>,
  12212. *
  12213. * shading: THREE.SmoothShading,
  12214. * blending: THREE.NormalBlending,
  12215. * depthTest: <bool>,
  12216. * depthWrite: <bool>,
  12217. *
  12218. * wireframe: <boolean>,
  12219. * wireframeLinewidth: <float>,
  12220. *
  12221. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12222. *
  12223. * skinning: <bool>,
  12224. * morphTargets: <bool>,
  12225. *
  12226. * fog: <bool>
  12227. * }
  12228. */
  12229. THREE.MeshBasicMaterial = function ( parameters ) {
  12230. THREE.Material.call( this );
  12231. this.type = 'MeshBasicMaterial';
  12232. this.color = new THREE.Color( 0xffffff ); // emissive
  12233. this.map = null;
  12234. this.aoMap = null;
  12235. this.aoMapIntensity = 1.0;
  12236. this.specularMap = null;
  12237. this.alphaMap = null;
  12238. this.envMap = null;
  12239. this.combine = THREE.MultiplyOperation;
  12240. this.reflectivity = 1;
  12241. this.refractionRatio = 0.98;
  12242. this.fog = true;
  12243. this.shading = THREE.SmoothShading;
  12244. this.blending = THREE.NormalBlending;
  12245. this.wireframe = false;
  12246. this.wireframeLinewidth = 1;
  12247. this.wireframeLinecap = 'round';
  12248. this.wireframeLinejoin = 'round';
  12249. this.vertexColors = THREE.NoColors;
  12250. this.skinning = false;
  12251. this.morphTargets = false;
  12252. this.setValues( parameters );
  12253. };
  12254. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  12255. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  12256. THREE.MeshBasicMaterial.prototype.copy = function ( source ) {
  12257. THREE.Material.prototype.copy.call( this, source );
  12258. this.color.copy( source.color );
  12259. this.map = source.map;
  12260. this.aoMap = source.aoMap;
  12261. this.aoMapIntensity = source.aoMapIntensity;
  12262. this.specularMap = source.specularMap;
  12263. this.alphaMap = source.alphaMap;
  12264. this.envMap = source.envMap;
  12265. this.combine = source.combine;
  12266. this.reflectivity = source.reflectivity;
  12267. this.refractionRatio = source.refractionRatio;
  12268. this.fog = source.fog;
  12269. this.shading = source.shading;
  12270. this.wireframe = source.wireframe;
  12271. this.wireframeLinewidth = source.wireframeLinewidth;
  12272. this.wireframeLinecap = source.wireframeLinecap;
  12273. this.wireframeLinejoin = source.wireframeLinejoin;
  12274. this.vertexColors = source.vertexColors;
  12275. this.skinning = source.skinning;
  12276. this.morphTargets = source.morphTargets;
  12277. return this;
  12278. };
  12279. // File:src/materials/MeshDepthMaterial.js
  12280. /**
  12281. * @author mrdoob / http://mrdoob.com/
  12282. * @author alteredq / http://alteredqualia.com/
  12283. * @author bhouston / https://clara.io
  12284. * @author WestLangley / http://github.com/WestLangley
  12285. *
  12286. * parameters = {
  12287. *
  12288. * opacity: <float>,
  12289. *
  12290. * map: new THREE.Texture( <Image> ),
  12291. *
  12292. * alphaMap: new THREE.Texture( <Image> ),
  12293. *
  12294. * displacementMap: new THREE.Texture( <Image> ),
  12295. * displacementScale: <float>,
  12296. * displacementBias: <float>,
  12297. *
  12298. * wireframe: <boolean>,
  12299. * wireframeLinewidth: <float>
  12300. * }
  12301. */
  12302. THREE.MeshDepthMaterial = function ( parameters ) {
  12303. THREE.Material.call( this );
  12304. this.type = 'MeshDepthMaterial';
  12305. this.depthPacking = THREE.BasicDepthPacking;
  12306. this.skinning = false;
  12307. this.morphTargets = false;
  12308. this.map = null;
  12309. this.alphaMap = null;
  12310. this.displacementMap = null;
  12311. this.displacementScale = 1;
  12312. this.displacementBias = 0;
  12313. this.wireframe = false;
  12314. this.wireframeLinewidth = 1;
  12315. this.setValues( parameters );
  12316. };
  12317. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  12318. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  12319. THREE.MeshDepthMaterial.prototype.copy = function ( source ) {
  12320. THREE.Material.prototype.copy.call( this, source );
  12321. this.depthPacking = source.depthPacking;
  12322. this.skinning = source.skinning;
  12323. this.morphTargets = source.morphTargets;
  12324. this.map = source.map;
  12325. this.alphaMap = source.alphaMap;
  12326. this.displacementMap = source.displacementMap;
  12327. this.displacementScale = source.displacementScale;
  12328. this.displacementBias = source.displacementBias;
  12329. this.wireframe = source.wireframe;
  12330. this.wireframeLinewidth = source.wireframeLinewidth;
  12331. return this;
  12332. };
  12333. // File:src/materials/MeshLambertMaterial.js
  12334. /**
  12335. * @author mrdoob / http://mrdoob.com/
  12336. * @author alteredq / http://alteredqualia.com/
  12337. *
  12338. * parameters = {
  12339. * color: <hex>,
  12340. * opacity: <float>,
  12341. *
  12342. * map: new THREE.Texture( <Image> ),
  12343. *
  12344. * lightMap: new THREE.Texture( <Image> ),
  12345. * lightMapIntensity: <float>
  12346. *
  12347. * aoMap: new THREE.Texture( <Image> ),
  12348. * aoMapIntensity: <float>
  12349. *
  12350. * emissive: <hex>,
  12351. * emissiveIntensity: <float>
  12352. * emissiveMap: new THREE.Texture( <Image> ),
  12353. *
  12354. * specularMap: new THREE.Texture( <Image> ),
  12355. *
  12356. * alphaMap: new THREE.Texture( <Image> ),
  12357. *
  12358. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  12359. * combine: THREE.Multiply,
  12360. * reflectivity: <float>,
  12361. * refractionRatio: <float>,
  12362. *
  12363. * blending: THREE.NormalBlending,
  12364. * depthTest: <bool>,
  12365. * depthWrite: <bool>,
  12366. *
  12367. * wireframe: <boolean>,
  12368. * wireframeLinewidth: <float>,
  12369. *
  12370. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12371. *
  12372. * skinning: <bool>,
  12373. * morphTargets: <bool>,
  12374. * morphNormals: <bool>,
  12375. *
  12376. * fog: <bool>
  12377. * }
  12378. */
  12379. THREE.MeshLambertMaterial = function ( parameters ) {
  12380. THREE.Material.call( this );
  12381. this.type = 'MeshLambertMaterial';
  12382. this.color = new THREE.Color( 0xffffff ); // diffuse
  12383. this.map = null;
  12384. this.lightMap = null;
  12385. this.lightMapIntensity = 1.0;
  12386. this.aoMap = null;
  12387. this.aoMapIntensity = 1.0;
  12388. this.emissive = new THREE.Color( 0x000000 );
  12389. this.emissiveIntensity = 1.0;
  12390. this.emissiveMap = null;
  12391. this.specularMap = null;
  12392. this.alphaMap = null;
  12393. this.envMap = null;
  12394. this.combine = THREE.MultiplyOperation;
  12395. this.reflectivity = 1;
  12396. this.refractionRatio = 0.98;
  12397. this.fog = true;
  12398. this.blending = THREE.NormalBlending;
  12399. this.wireframe = false;
  12400. this.wireframeLinewidth = 1;
  12401. this.wireframeLinecap = 'round';
  12402. this.wireframeLinejoin = 'round';
  12403. this.vertexColors = THREE.NoColors;
  12404. this.skinning = false;
  12405. this.morphTargets = false;
  12406. this.morphNormals = false;
  12407. this.setValues( parameters );
  12408. };
  12409. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  12410. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  12411. THREE.MeshLambertMaterial.prototype.copy = function ( source ) {
  12412. THREE.Material.prototype.copy.call( this, source );
  12413. this.color.copy( source.color );
  12414. this.map = source.map;
  12415. this.lightMap = source.lightMap;
  12416. this.lightMapIntensity = source.lightMapIntensity;
  12417. this.aoMap = source.aoMap;
  12418. this.aoMapIntensity = source.aoMapIntensity;
  12419. this.emissive.copy( source.emissive );
  12420. this.emissiveMap = source.emissiveMap;
  12421. this.emissiveIntensity = source.emissiveIntensity;
  12422. this.specularMap = source.specularMap;
  12423. this.alphaMap = source.alphaMap;
  12424. this.envMap = source.envMap;
  12425. this.combine = source.combine;
  12426. this.reflectivity = source.reflectivity;
  12427. this.refractionRatio = source.refractionRatio;
  12428. this.fog = source.fog;
  12429. this.wireframe = source.wireframe;
  12430. this.wireframeLinewidth = source.wireframeLinewidth;
  12431. this.wireframeLinecap = source.wireframeLinecap;
  12432. this.wireframeLinejoin = source.wireframeLinejoin;
  12433. this.vertexColors = source.vertexColors;
  12434. this.skinning = source.skinning;
  12435. this.morphTargets = source.morphTargets;
  12436. this.morphNormals = source.morphNormals;
  12437. return this;
  12438. };
  12439. // File:src/materials/MeshNormalMaterial.js
  12440. /**
  12441. * @author mrdoob / http://mrdoob.com/
  12442. *
  12443. * parameters = {
  12444. * opacity: <float>,
  12445. *
  12446. * wireframe: <boolean>,
  12447. * wireframeLinewidth: <float>
  12448. * }
  12449. */
  12450. THREE.MeshNormalMaterial = function ( parameters ) {
  12451. THREE.Material.call( this, parameters );
  12452. this.type = 'MeshNormalMaterial';
  12453. this.wireframe = false;
  12454. this.wireframeLinewidth = 1;
  12455. this.morphTargets = false;
  12456. this.setValues( parameters );
  12457. };
  12458. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  12459. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  12460. THREE.MeshNormalMaterial.prototype.copy = function ( source ) {
  12461. THREE.Material.prototype.copy.call( this, source );
  12462. this.wireframe = source.wireframe;
  12463. this.wireframeLinewidth = source.wireframeLinewidth;
  12464. return this;
  12465. };
  12466. // File:src/materials/MeshPhongMaterial.js
  12467. /**
  12468. * @author mrdoob / http://mrdoob.com/
  12469. * @author alteredq / http://alteredqualia.com/
  12470. *
  12471. * parameters = {
  12472. * color: <hex>,
  12473. * specular: <hex>,
  12474. * shininess: <float>,
  12475. * opacity: <float>,
  12476. *
  12477. * map: new THREE.Texture( <Image> ),
  12478. *
  12479. * lightMap: new THREE.Texture( <Image> ),
  12480. * lightMapIntensity: <float>
  12481. *
  12482. * aoMap: new THREE.Texture( <Image> ),
  12483. * aoMapIntensity: <float>
  12484. *
  12485. * emissive: <hex>,
  12486. * emissiveIntensity: <float>
  12487. * emissiveMap: new THREE.Texture( <Image> ),
  12488. *
  12489. * bumpMap: new THREE.Texture( <Image> ),
  12490. * bumpScale: <float>,
  12491. *
  12492. * normalMap: new THREE.Texture( <Image> ),
  12493. * normalScale: <Vector2>,
  12494. *
  12495. * displacementMap: new THREE.Texture( <Image> ),
  12496. * displacementScale: <float>,
  12497. * displacementBias: <float>,
  12498. *
  12499. * specularMap: new THREE.Texture( <Image> ),
  12500. *
  12501. * alphaMap: new THREE.Texture( <Image> ),
  12502. *
  12503. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  12504. * combine: THREE.Multiply,
  12505. * reflectivity: <float>,
  12506. * refractionRatio: <float>,
  12507. *
  12508. * shading: THREE.SmoothShading,
  12509. * blending: THREE.NormalBlending,
  12510. * depthTest: <bool>,
  12511. * depthWrite: <bool>,
  12512. *
  12513. * wireframe: <boolean>,
  12514. * wireframeLinewidth: <float>,
  12515. *
  12516. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12517. *
  12518. * skinning: <bool>,
  12519. * morphTargets: <bool>,
  12520. * morphNormals: <bool>,
  12521. *
  12522. * fog: <bool>
  12523. * }
  12524. */
  12525. THREE.MeshPhongMaterial = function ( parameters ) {
  12526. THREE.Material.call( this );
  12527. this.type = 'MeshPhongMaterial';
  12528. this.color = new THREE.Color( 0xffffff ); // diffuse
  12529. this.specular = new THREE.Color( 0x111111 );
  12530. this.shininess = 30;
  12531. this.map = null;
  12532. this.lightMap = null;
  12533. this.lightMapIntensity = 1.0;
  12534. this.aoMap = null;
  12535. this.aoMapIntensity = 1.0;
  12536. this.emissive = new THREE.Color( 0x000000 );
  12537. this.emissiveIntensity = 1.0;
  12538. this.emissiveMap = null;
  12539. this.bumpMap = null;
  12540. this.bumpScale = 1;
  12541. this.normalMap = null;
  12542. this.normalScale = new THREE.Vector2( 1, 1 );
  12543. this.displacementMap = null;
  12544. this.displacementScale = 1;
  12545. this.displacementBias = 0;
  12546. this.specularMap = null;
  12547. this.alphaMap = null;
  12548. this.envMap = null;
  12549. this.combine = THREE.MultiplyOperation;
  12550. this.reflectivity = 1;
  12551. this.refractionRatio = 0.98;
  12552. this.fog = true;
  12553. this.shading = THREE.SmoothShading;
  12554. this.blending = THREE.NormalBlending;
  12555. this.wireframe = false;
  12556. this.wireframeLinewidth = 1;
  12557. this.wireframeLinecap = 'round';
  12558. this.wireframeLinejoin = 'round';
  12559. this.vertexColors = THREE.NoColors;
  12560. this.skinning = false;
  12561. this.morphTargets = false;
  12562. this.morphNormals = false;
  12563. this.setValues( parameters );
  12564. };
  12565. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  12566. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  12567. THREE.MeshPhongMaterial.prototype.copy = function ( source ) {
  12568. THREE.Material.prototype.copy.call( this, source );
  12569. this.color.copy( source.color );
  12570. this.specular.copy( source.specular );
  12571. this.shininess = source.shininess;
  12572. this.map = source.map;
  12573. this.lightMap = source.lightMap;
  12574. this.lightMapIntensity = source.lightMapIntensity;
  12575. this.aoMap = source.aoMap;
  12576. this.aoMapIntensity = source.aoMapIntensity;
  12577. this.emissive.copy( source.emissive );
  12578. this.emissiveMap = source.emissiveMap;
  12579. this.emissiveIntensity = source.emissiveIntensity;
  12580. this.bumpMap = source.bumpMap;
  12581. this.bumpScale = source.bumpScale;
  12582. this.normalMap = source.normalMap;
  12583. this.normalScale.copy( source.normalScale );
  12584. this.displacementMap = source.displacementMap;
  12585. this.displacementScale = source.displacementScale;
  12586. this.displacementBias = source.displacementBias;
  12587. this.specularMap = source.specularMap;
  12588. this.alphaMap = source.alphaMap;
  12589. this.envMap = source.envMap;
  12590. this.combine = source.combine;
  12591. this.reflectivity = source.reflectivity;
  12592. this.refractionRatio = source.refractionRatio;
  12593. this.fog = source.fog;
  12594. this.shading = source.shading;
  12595. this.wireframe = source.wireframe;
  12596. this.wireframeLinewidth = source.wireframeLinewidth;
  12597. this.wireframeLinecap = source.wireframeLinecap;
  12598. this.wireframeLinejoin = source.wireframeLinejoin;
  12599. this.vertexColors = source.vertexColors;
  12600. this.skinning = source.skinning;
  12601. this.morphTargets = source.morphTargets;
  12602. this.morphNormals = source.morphNormals;
  12603. return this;
  12604. };
  12605. // File:src/materials/MeshStandardMaterial.js
  12606. /**
  12607. * @author WestLangley / http://github.com/WestLangley
  12608. *
  12609. * parameters = {
  12610. * color: <hex>,
  12611. * roughness: <float>,
  12612. * metalness: <float>,
  12613. * opacity: <float>,
  12614. *
  12615. * map: new THREE.Texture( <Image> ),
  12616. *
  12617. * lightMap: new THREE.Texture( <Image> ),
  12618. * lightMapIntensity: <float>
  12619. *
  12620. * aoMap: new THREE.Texture( <Image> ),
  12621. * aoMapIntensity: <float>
  12622. *
  12623. * emissive: <hex>,
  12624. * emissiveIntensity: <float>
  12625. * emissiveMap: new THREE.Texture( <Image> ),
  12626. *
  12627. * bumpMap: new THREE.Texture( <Image> ),
  12628. * bumpScale: <float>,
  12629. *
  12630. * normalMap: new THREE.Texture( <Image> ),
  12631. * normalScale: <Vector2>,
  12632. *
  12633. * displacementMap: new THREE.Texture( <Image> ),
  12634. * displacementScale: <float>,
  12635. * displacementBias: <float>,
  12636. *
  12637. * roughnessMap: new THREE.Texture( <Image> ),
  12638. *
  12639. * metalnessMap: new THREE.Texture( <Image> ),
  12640. *
  12641. * alphaMap: new THREE.Texture( <Image> ),
  12642. *
  12643. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  12644. * envMapIntensity: <float>
  12645. *
  12646. * refractionRatio: <float>,
  12647. *
  12648. * shading: THREE.SmoothShading,
  12649. * blending: THREE.NormalBlending,
  12650. * depthTest: <bool>,
  12651. * depthWrite: <bool>,
  12652. *
  12653. * wireframe: <boolean>,
  12654. * wireframeLinewidth: <float>,
  12655. *
  12656. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12657. *
  12658. * skinning: <bool>,
  12659. * morphTargets: <bool>,
  12660. * morphNormals: <bool>,
  12661. *
  12662. * fog: <bool>
  12663. * }
  12664. */
  12665. THREE.MeshStandardMaterial = function ( parameters ) {
  12666. THREE.Material.call( this );
  12667. this.defines = { 'STANDARD': '' };
  12668. this.type = 'MeshStandardMaterial';
  12669. this.color = new THREE.Color( 0xffffff ); // diffuse
  12670. this.roughness = 0.5;
  12671. this.metalness = 0.5;
  12672. this.map = null;
  12673. this.lightMap = null;
  12674. this.lightMapIntensity = 1.0;
  12675. this.aoMap = null;
  12676. this.aoMapIntensity = 1.0;
  12677. this.emissive = new THREE.Color( 0x000000 );
  12678. this.emissiveIntensity = 1.0;
  12679. this.emissiveMap = null;
  12680. this.bumpMap = null;
  12681. this.bumpScale = 1;
  12682. this.normalMap = null;
  12683. this.normalScale = new THREE.Vector2( 1, 1 );
  12684. this.displacementMap = null;
  12685. this.displacementScale = 1;
  12686. this.displacementBias = 0;
  12687. this.roughnessMap = null;
  12688. this.metalnessMap = null;
  12689. this.alphaMap = null;
  12690. this.envMap = null;
  12691. this.envMapIntensity = 1.0;
  12692. this.refractionRatio = 0.98;
  12693. this.fog = true;
  12694. this.shading = THREE.SmoothShading;
  12695. this.blending = THREE.NormalBlending;
  12696. this.wireframe = false;
  12697. this.wireframeLinewidth = 1;
  12698. this.wireframeLinecap = 'round';
  12699. this.wireframeLinejoin = 'round';
  12700. this.vertexColors = THREE.NoColors;
  12701. this.skinning = false;
  12702. this.morphTargets = false;
  12703. this.morphNormals = false;
  12704. this.setValues( parameters );
  12705. };
  12706. THREE.MeshStandardMaterial.prototype = Object.create( THREE.Material.prototype );
  12707. THREE.MeshStandardMaterial.prototype.constructor = THREE.MeshStandardMaterial;
  12708. THREE.MeshStandardMaterial.prototype.copy = function ( source ) {
  12709. THREE.Material.prototype.copy.call( this, source );
  12710. this.defines = { 'STANDARD': '' };
  12711. this.color.copy( source.color );
  12712. this.roughness = source.roughness;
  12713. this.metalness = source.metalness;
  12714. this.map = source.map;
  12715. this.lightMap = source.lightMap;
  12716. this.lightMapIntensity = source.lightMapIntensity;
  12717. this.aoMap = source.aoMap;
  12718. this.aoMapIntensity = source.aoMapIntensity;
  12719. this.emissive.copy( source.emissive );
  12720. this.emissiveMap = source.emissiveMap;
  12721. this.emissiveIntensity = source.emissiveIntensity;
  12722. this.bumpMap = source.bumpMap;
  12723. this.bumpScale = source.bumpScale;
  12724. this.normalMap = source.normalMap;
  12725. this.normalScale.copy( source.normalScale );
  12726. this.displacementMap = source.displacementMap;
  12727. this.displacementScale = source.displacementScale;
  12728. this.displacementBias = source.displacementBias;
  12729. this.roughnessMap = source.roughnessMap;
  12730. this.metalnessMap = source.metalnessMap;
  12731. this.alphaMap = source.alphaMap;
  12732. this.envMap = source.envMap;
  12733. this.envMapIntensity = source.envMapIntensity;
  12734. this.refractionRatio = source.refractionRatio;
  12735. this.fog = source.fog;
  12736. this.shading = source.shading;
  12737. this.wireframe = source.wireframe;
  12738. this.wireframeLinewidth = source.wireframeLinewidth;
  12739. this.wireframeLinecap = source.wireframeLinecap;
  12740. this.wireframeLinejoin = source.wireframeLinejoin;
  12741. this.vertexColors = source.vertexColors;
  12742. this.skinning = source.skinning;
  12743. this.morphTargets = source.morphTargets;
  12744. this.morphNormals = source.morphNormals;
  12745. return this;
  12746. };
  12747. // File:src/materials/MeshPhysicalMaterial.js
  12748. /**
  12749. * @author WestLangley / http://github.com/WestLangley
  12750. *
  12751. * parameters = {
  12752. * reflectivity: <float>
  12753. * }
  12754. */
  12755. THREE.MeshPhysicalMaterial = function ( parameters ) {
  12756. THREE.MeshStandardMaterial.call( this );
  12757. this.defines = { 'PHYSICAL': '' };
  12758. this.type = 'MeshPhysicalMaterial';
  12759. this.reflectivity = 0.5; // maps to F0 = 0.04
  12760. this.setValues( parameters );
  12761. };
  12762. THREE.MeshPhysicalMaterial.prototype = Object.create( THREE.MeshStandardMaterial.prototype );
  12763. THREE.MeshPhysicalMaterial.prototype.constructor = THREE.MeshPhysicalMaterial;
  12764. THREE.MeshPhysicalMaterial.prototype.copy = function ( source ) {
  12765. THREE.MeshStandardMaterial.prototype.copy.call( this, source );
  12766. this.defines = { 'PHYSICAL': '' };
  12767. this.reflectivity = source.reflectivity;
  12768. return this;
  12769. };
  12770. // File:src/materials/MultiMaterial.js
  12771. /**
  12772. * @author mrdoob / http://mrdoob.com/
  12773. */
  12774. THREE.MultiMaterial = function ( materials ) {
  12775. this.uuid = THREE.Math.generateUUID();
  12776. this.type = 'MultiMaterial';
  12777. this.materials = materials instanceof Array ? materials : [];
  12778. this.visible = true;
  12779. };
  12780. THREE.MultiMaterial.prototype = {
  12781. constructor: THREE.MultiMaterial,
  12782. toJSON: function ( meta ) {
  12783. var output = {
  12784. metadata: {
  12785. version: 4.2,
  12786. type: 'material',
  12787. generator: 'MaterialExporter'
  12788. },
  12789. uuid: this.uuid,
  12790. type: this.type,
  12791. materials: []
  12792. };
  12793. var materials = this.materials;
  12794. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  12795. var material = materials[ i ].toJSON( meta );
  12796. delete material.metadata;
  12797. output.materials.push( material );
  12798. }
  12799. output.visible = this.visible;
  12800. return output;
  12801. },
  12802. clone: function () {
  12803. var material = new this.constructor();
  12804. for ( var i = 0; i < this.materials.length; i ++ ) {
  12805. material.materials.push( this.materials[ i ].clone() );
  12806. }
  12807. material.visible = this.visible;
  12808. return material;
  12809. }
  12810. };
  12811. // File:src/materials/PointsMaterial.js
  12812. /**
  12813. * @author mrdoob / http://mrdoob.com/
  12814. * @author alteredq / http://alteredqualia.com/
  12815. *
  12816. * parameters = {
  12817. * color: <hex>,
  12818. * opacity: <float>,
  12819. * map: new THREE.Texture( <Image> ),
  12820. *
  12821. * size: <float>,
  12822. * sizeAttenuation: <bool>,
  12823. *
  12824. * blending: THREE.NormalBlending,
  12825. * depthTest: <bool>,
  12826. * depthWrite: <bool>,
  12827. *
  12828. * vertexColors: <bool>,
  12829. *
  12830. * fog: <bool>
  12831. * }
  12832. */
  12833. THREE.PointsMaterial = function ( parameters ) {
  12834. THREE.Material.call( this );
  12835. this.type = 'PointsMaterial';
  12836. this.color = new THREE.Color( 0xffffff );
  12837. this.map = null;
  12838. this.size = 1;
  12839. this.sizeAttenuation = true;
  12840. this.blending = THREE.NormalBlending;
  12841. this.vertexColors = THREE.NoColors;
  12842. this.fog = true;
  12843. this.setValues( parameters );
  12844. };
  12845. THREE.PointsMaterial.prototype = Object.create( THREE.Material.prototype );
  12846. THREE.PointsMaterial.prototype.constructor = THREE.PointsMaterial;
  12847. THREE.PointsMaterial.prototype.copy = function ( source ) {
  12848. THREE.Material.prototype.copy.call( this, source );
  12849. this.color.copy( source.color );
  12850. this.map = source.map;
  12851. this.size = source.size;
  12852. this.sizeAttenuation = source.sizeAttenuation;
  12853. this.vertexColors = source.vertexColors;
  12854. this.fog = source.fog;
  12855. return this;
  12856. };
  12857. // File:src/materials/ShaderMaterial.js
  12858. /**
  12859. * @author alteredq / http://alteredqualia.com/
  12860. *
  12861. * parameters = {
  12862. * defines: { "label" : "value" },
  12863. * uniforms: { "parameter1": { type: "1f", value: 1.0 }, "parameter2": { type: "1i" value2: 2 } },
  12864. *
  12865. * fragmentShader: <string>,
  12866. * vertexShader: <string>,
  12867. *
  12868. * shading: THREE.SmoothShading,
  12869. *
  12870. * wireframe: <boolean>,
  12871. * wireframeLinewidth: <float>,
  12872. *
  12873. * lights: <bool>,
  12874. *
  12875. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  12876. *
  12877. * skinning: <bool>,
  12878. * morphTargets: <bool>,
  12879. * morphNormals: <bool>,
  12880. *
  12881. * fog: <bool>
  12882. * }
  12883. */
  12884. THREE.ShaderMaterial = function ( parameters ) {
  12885. THREE.Material.call( this );
  12886. this.type = 'ShaderMaterial';
  12887. this.defines = {};
  12888. this.uniforms = {};
  12889. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  12890. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  12891. this.shading = THREE.SmoothShading;
  12892. this.linewidth = 1;
  12893. this.wireframe = false;
  12894. this.wireframeLinewidth = 1;
  12895. this.fog = false; // set to use scene fog
  12896. this.lights = false; // set to use scene lights
  12897. this.clipping = false; // set to use user-defined clipping planes
  12898. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  12899. this.skinning = false; // set to use skinning attribute streams
  12900. this.morphTargets = false; // set to use morph targets
  12901. this.morphNormals = false; // set to use morph normals
  12902. this.extensions = {
  12903. derivatives: false, // set to use derivatives
  12904. fragDepth: false, // set to use fragment depth values
  12905. drawBuffers: false, // set to use draw buffers
  12906. shaderTextureLOD: false // set to use shader texture LOD
  12907. };
  12908. // When rendered geometry doesn't include these attributes but the material does,
  12909. // use these default values in WebGL. This avoids errors when buffer data is missing.
  12910. this.defaultAttributeValues = {
  12911. 'color': [ 1, 1, 1 ],
  12912. 'uv': [ 0, 0 ],
  12913. 'uv2': [ 0, 0 ]
  12914. };
  12915. this.index0AttributeName = undefined;
  12916. if ( parameters !== undefined ) {
  12917. if ( parameters.attributes !== undefined ) {
  12918. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  12919. }
  12920. this.setValues( parameters );
  12921. }
  12922. };
  12923. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  12924. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  12925. THREE.ShaderMaterial.prototype.copy = function ( source ) {
  12926. THREE.Material.prototype.copy.call( this, source );
  12927. this.fragmentShader = source.fragmentShader;
  12928. this.vertexShader = source.vertexShader;
  12929. this.uniforms = THREE.UniformsUtils.clone( source.uniforms );
  12930. this.defines = source.defines;
  12931. this.shading = source.shading;
  12932. this.wireframe = source.wireframe;
  12933. this.wireframeLinewidth = source.wireframeLinewidth;
  12934. this.fog = source.fog;
  12935. this.lights = source.lights;
  12936. this.clipping = source.clipping;
  12937. this.vertexColors = source.vertexColors;
  12938. this.skinning = source.skinning;
  12939. this.morphTargets = source.morphTargets;
  12940. this.morphNormals = source.morphNormals;
  12941. this.extensions = source.extensions;
  12942. return this;
  12943. };
  12944. THREE.ShaderMaterial.prototype.toJSON = function ( meta ) {
  12945. var data = THREE.Material.prototype.toJSON.call( this, meta );
  12946. data.uniforms = this.uniforms;
  12947. data.vertexShader = this.vertexShader;
  12948. data.fragmentShader = this.fragmentShader;
  12949. return data;
  12950. };
  12951. // File:src/materials/RawShaderMaterial.js
  12952. /**
  12953. * @author mrdoob / http://mrdoob.com/
  12954. */
  12955. THREE.RawShaderMaterial = function ( parameters ) {
  12956. THREE.ShaderMaterial.call( this, parameters );
  12957. this.type = 'RawShaderMaterial';
  12958. };
  12959. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  12960. THREE.RawShaderMaterial.prototype.constructor = THREE.RawShaderMaterial;
  12961. // File:src/materials/SpriteMaterial.js
  12962. /**
  12963. * @author alteredq / http://alteredqualia.com/
  12964. *
  12965. * parameters = {
  12966. * color: <hex>,
  12967. * opacity: <float>,
  12968. * map: new THREE.Texture( <Image> ),
  12969. *
  12970. * uvOffset: new THREE.Vector2(),
  12971. * uvScale: new THREE.Vector2(),
  12972. *
  12973. * fog: <bool>
  12974. * }
  12975. */
  12976. THREE.SpriteMaterial = function ( parameters ) {
  12977. THREE.Material.call( this );
  12978. this.type = 'SpriteMaterial';
  12979. this.color = new THREE.Color( 0xffffff );
  12980. this.map = null;
  12981. this.rotation = 0;
  12982. this.fog = false;
  12983. // set parameters
  12984. this.setValues( parameters );
  12985. };
  12986. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  12987. THREE.SpriteMaterial.prototype.constructor = THREE.SpriteMaterial;
  12988. THREE.SpriteMaterial.prototype.copy = function ( source ) {
  12989. THREE.Material.prototype.copy.call( this, source );
  12990. this.color.copy( source.color );
  12991. this.map = source.map;
  12992. this.rotation = source.rotation;
  12993. this.fog = source.fog;
  12994. return this;
  12995. };
  12996. // File:src/textures/Texture.js
  12997. /**
  12998. * @author mrdoob / http://mrdoob.com/
  12999. * @author alteredq / http://alteredqualia.com/
  13000. * @author szimek / https://github.com/szimek/
  13001. */
  13002. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  13003. Object.defineProperty( this, 'id', { value: THREE.TextureIdCount ++ } );
  13004. this.uuid = THREE.Math.generateUUID();
  13005. this.name = '';
  13006. this.sourceFile = '';
  13007. this.image = image !== undefined ? image : THREE.Texture.DEFAULT_IMAGE;
  13008. this.mipmaps = [];
  13009. this.mapping = mapping !== undefined ? mapping : THREE.Texture.DEFAULT_MAPPING;
  13010. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  13011. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  13012. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  13013. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  13014. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  13015. this.format = format !== undefined ? format : THREE.RGBAFormat;
  13016. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  13017. this.offset = new THREE.Vector2( 0, 0 );
  13018. this.repeat = new THREE.Vector2( 1, 1 );
  13019. this.generateMipmaps = true;
  13020. this.premultiplyAlpha = false;
  13021. this.flipY = true;
  13022. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  13023. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  13024. //
  13025. // Also changing the encoding after already used by a Material will not automatically make the Material
  13026. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  13027. this.encoding = encoding !== undefined ? encoding : THREE.LinearEncoding;
  13028. this.version = 0;
  13029. this.onUpdate = null;
  13030. };
  13031. THREE.Texture.DEFAULT_IMAGE = undefined;
  13032. THREE.Texture.DEFAULT_MAPPING = THREE.UVMapping;
  13033. THREE.Texture.prototype = {
  13034. constructor: THREE.Texture,
  13035. set needsUpdate ( value ) {
  13036. if ( value === true ) this.version ++;
  13037. },
  13038. clone: function () {
  13039. return new this.constructor().copy( this );
  13040. },
  13041. copy: function ( source ) {
  13042. this.image = source.image;
  13043. this.mipmaps = source.mipmaps.slice( 0 );
  13044. this.mapping = source.mapping;
  13045. this.wrapS = source.wrapS;
  13046. this.wrapT = source.wrapT;
  13047. this.magFilter = source.magFilter;
  13048. this.minFilter = source.minFilter;
  13049. this.anisotropy = source.anisotropy;
  13050. this.format = source.format;
  13051. this.type = source.type;
  13052. this.offset.copy( source.offset );
  13053. this.repeat.copy( source.repeat );
  13054. this.generateMipmaps = source.generateMipmaps;
  13055. this.premultiplyAlpha = source.premultiplyAlpha;
  13056. this.flipY = source.flipY;
  13057. this.unpackAlignment = source.unpackAlignment;
  13058. this.encoding = source.encoding;
  13059. return this;
  13060. },
  13061. toJSON: function ( meta ) {
  13062. if ( meta.textures[ this.uuid ] !== undefined ) {
  13063. return meta.textures[ this.uuid ];
  13064. }
  13065. function getDataURL( image ) {
  13066. var canvas;
  13067. if ( image.toDataURL !== undefined ) {
  13068. canvas = image;
  13069. } else {
  13070. canvas = document.createElement( 'canvas' );
  13071. canvas.width = image.width;
  13072. canvas.height = image.height;
  13073. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  13074. }
  13075. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  13076. return canvas.toDataURL( 'image/jpeg', 0.6 );
  13077. } else {
  13078. return canvas.toDataURL( 'image/png' );
  13079. }
  13080. }
  13081. var output = {
  13082. metadata: {
  13083. version: 4.4,
  13084. type: 'Texture',
  13085. generator: 'Texture.toJSON'
  13086. },
  13087. uuid: this.uuid,
  13088. name: this.name,
  13089. mapping: this.mapping,
  13090. repeat: [ this.repeat.x, this.repeat.y ],
  13091. offset: [ this.offset.x, this.offset.y ],
  13092. wrap: [ this.wrapS, this.wrapT ],
  13093. minFilter: this.minFilter,
  13094. magFilter: this.magFilter,
  13095. anisotropy: this.anisotropy
  13096. };
  13097. if ( this.image !== undefined ) {
  13098. // TODO: Move to THREE.Image
  13099. var image = this.image;
  13100. if ( image.uuid === undefined ) {
  13101. image.uuid = THREE.Math.generateUUID(); // UGH
  13102. }
  13103. if ( meta.images[ image.uuid ] === undefined ) {
  13104. meta.images[ image.uuid ] = {
  13105. uuid: image.uuid,
  13106. url: getDataURL( image )
  13107. };
  13108. }
  13109. output.image = image.uuid;
  13110. }
  13111. meta.textures[ this.uuid ] = output;
  13112. return output;
  13113. },
  13114. dispose: function () {
  13115. this.dispatchEvent( { type: 'dispose' } );
  13116. },
  13117. transformUv: function ( uv ) {
  13118. if ( this.mapping !== THREE.UVMapping ) return;
  13119. uv.multiply( this.repeat );
  13120. uv.add( this.offset );
  13121. if ( uv.x < 0 || uv.x > 1 ) {
  13122. switch ( this.wrapS ) {
  13123. case THREE.RepeatWrapping:
  13124. uv.x = uv.x - Math.floor( uv.x );
  13125. break;
  13126. case THREE.ClampToEdgeWrapping:
  13127. uv.x = uv.x < 0 ? 0 : 1;
  13128. break;
  13129. case THREE.MirroredRepeatWrapping:
  13130. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  13131. uv.x = Math.ceil( uv.x ) - uv.x;
  13132. } else {
  13133. uv.x = uv.x - Math.floor( uv.x );
  13134. }
  13135. break;
  13136. }
  13137. }
  13138. if ( uv.y < 0 || uv.y > 1 ) {
  13139. switch ( this.wrapT ) {
  13140. case THREE.RepeatWrapping:
  13141. uv.y = uv.y - Math.floor( uv.y );
  13142. break;
  13143. case THREE.ClampToEdgeWrapping:
  13144. uv.y = uv.y < 0 ? 0 : 1;
  13145. break;
  13146. case THREE.MirroredRepeatWrapping:
  13147. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  13148. uv.y = Math.ceil( uv.y ) - uv.y;
  13149. } else {
  13150. uv.y = uv.y - Math.floor( uv.y );
  13151. }
  13152. break;
  13153. }
  13154. }
  13155. if ( this.flipY ) {
  13156. uv.y = 1 - uv.y;
  13157. }
  13158. }
  13159. };
  13160. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  13161. THREE.TextureIdCount = 0;
  13162. // File:src/textures/DepthTexture.js
  13163. /**
  13164. * @author Matt DesLauriers / @mattdesl
  13165. */
  13166. THREE.DepthTexture = function ( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  13167. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, THREE.DepthFormat, type, anisotropy );
  13168. this.image = { width: width, height: height };
  13169. this.type = type !== undefined ? type : THREE.UnsignedShortType;
  13170. this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter;
  13171. this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter;
  13172. this.flipY = false;
  13173. this.generateMipmaps = false;
  13174. };
  13175. THREE.DepthTexture.prototype = Object.create( THREE.Texture.prototype );
  13176. THREE.DepthTexture.prototype.constructor = THREE.DepthTexture;
  13177. // File:src/textures/CanvasTexture.js
  13178. /**
  13179. * @author mrdoob / http://mrdoob.com/
  13180. */
  13181. THREE.CanvasTexture = function ( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13182. THREE.Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13183. this.needsUpdate = true;
  13184. };
  13185. THREE.CanvasTexture.prototype = Object.create( THREE.Texture.prototype );
  13186. THREE.CanvasTexture.prototype.constructor = THREE.CanvasTexture;
  13187. // File:src/textures/CubeTexture.js
  13188. /**
  13189. * @author mrdoob / http://mrdoob.com/
  13190. */
  13191. THREE.CubeTexture = function ( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  13192. images = images !== undefined ? images : [];
  13193. mapping = mapping !== undefined ? mapping : THREE.CubeReflectionMapping;
  13194. THREE.Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13195. this.flipY = false;
  13196. };
  13197. THREE.CubeTexture.prototype = Object.create( THREE.Texture.prototype );
  13198. THREE.CubeTexture.prototype.constructor = THREE.CubeTexture;
  13199. Object.defineProperty( THREE.CubeTexture.prototype, 'images', {
  13200. get: function () {
  13201. return this.image;
  13202. },
  13203. set: function ( value ) {
  13204. this.image = value;
  13205. }
  13206. } );
  13207. // File:src/textures/CompressedTexture.js
  13208. /**
  13209. * @author alteredq / http://alteredqualia.com/
  13210. */
  13211. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13212. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13213. this.image = { width: width, height: height };
  13214. this.mipmaps = mipmaps;
  13215. // no flipping for cube textures
  13216. // (also flipping doesn't work for compressed textures )
  13217. this.flipY = false;
  13218. // can't generate mipmaps for compressed textures
  13219. // mips must be embedded in DDS files
  13220. this.generateMipmaps = false;
  13221. };
  13222. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  13223. THREE.CompressedTexture.prototype.constructor = THREE.CompressedTexture;
  13224. // File:src/textures/DataTexture.js
  13225. /**
  13226. * @author alteredq / http://alteredqualia.com/
  13227. */
  13228. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  13229. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  13230. this.image = { data: data, width: width, height: height };
  13231. this.magFilter = magFilter !== undefined ? magFilter : THREE.NearestFilter;
  13232. this.minFilter = minFilter !== undefined ? minFilter : THREE.NearestFilter;
  13233. this.flipY = false;
  13234. this.generateMipmaps = false;
  13235. };
  13236. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  13237. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  13238. // File:src/textures/VideoTexture.js
  13239. /**
  13240. * @author mrdoob / http://mrdoob.com/
  13241. */
  13242. THREE.VideoTexture = function ( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  13243. THREE.Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  13244. this.generateMipmaps = false;
  13245. var scope = this;
  13246. function update() {
  13247. requestAnimationFrame( update );
  13248. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  13249. scope.needsUpdate = true;
  13250. }
  13251. }
  13252. update();
  13253. };
  13254. THREE.VideoTexture.prototype = Object.create( THREE.Texture.prototype );
  13255. THREE.VideoTexture.prototype.constructor = THREE.VideoTexture;
  13256. // File:src/objects/Group.js
  13257. /**
  13258. * @author mrdoob / http://mrdoob.com/
  13259. */
  13260. THREE.Group = function () {
  13261. THREE.Object3D.call( this );
  13262. this.type = 'Group';
  13263. };
  13264. THREE.Group.prototype = Object.create( THREE.Object3D.prototype );
  13265. THREE.Group.prototype.constructor = THREE.Group;
  13266. // File:src/objects/Points.js
  13267. /**
  13268. * @author alteredq / http://alteredqualia.com/
  13269. */
  13270. THREE.Points = function ( geometry, material ) {
  13271. THREE.Object3D.call( this );
  13272. this.type = 'Points';
  13273. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  13274. this.material = material !== undefined ? material : new THREE.PointsMaterial( { color: Math.random() * 0xffffff } );
  13275. };
  13276. THREE.Points.prototype = Object.create( THREE.Object3D.prototype );
  13277. THREE.Points.prototype.constructor = THREE.Points;
  13278. THREE.Points.prototype.raycast = ( function () {
  13279. var inverseMatrix = new THREE.Matrix4();
  13280. var ray = new THREE.Ray();
  13281. var sphere = new THREE.Sphere();
  13282. return function raycast( raycaster, intersects ) {
  13283. var object = this;
  13284. var geometry = this.geometry;
  13285. var matrixWorld = this.matrixWorld;
  13286. var threshold = raycaster.params.Points.threshold;
  13287. // Checking boundingSphere distance to ray
  13288. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13289. sphere.copy( geometry.boundingSphere );
  13290. sphere.applyMatrix4( matrixWorld );
  13291. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13292. //
  13293. inverseMatrix.getInverse( matrixWorld );
  13294. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13295. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  13296. var localThresholdSq = localThreshold * localThreshold;
  13297. var position = new THREE.Vector3();
  13298. function testPoint( point, index ) {
  13299. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  13300. if ( rayPointDistanceSq < localThresholdSq ) {
  13301. var intersectPoint = ray.closestPointToPoint( point );
  13302. intersectPoint.applyMatrix4( matrixWorld );
  13303. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  13304. if ( distance < raycaster.near || distance > raycaster.far ) return;
  13305. intersects.push( {
  13306. distance: distance,
  13307. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  13308. point: intersectPoint.clone(),
  13309. index: index,
  13310. face: null,
  13311. object: object
  13312. } );
  13313. }
  13314. }
  13315. if ( geometry instanceof THREE.BufferGeometry ) {
  13316. var index = geometry.index;
  13317. var attributes = geometry.attributes;
  13318. var positions = attributes.position.array;
  13319. if ( index !== null ) {
  13320. var indices = index.array;
  13321. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  13322. var a = indices[ i ];
  13323. position.fromArray( positions, a * 3 );
  13324. testPoint( position, a );
  13325. }
  13326. } else {
  13327. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  13328. position.fromArray( positions, i * 3 );
  13329. testPoint( position, i );
  13330. }
  13331. }
  13332. } else {
  13333. var vertices = geometry.vertices;
  13334. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  13335. testPoint( vertices[ i ], i );
  13336. }
  13337. }
  13338. };
  13339. }() );
  13340. THREE.Points.prototype.clone = function () {
  13341. return new this.constructor( this.geometry, this.material ).copy( this );
  13342. };
  13343. // File:src/objects/Line.js
  13344. /**
  13345. * @author mrdoob / http://mrdoob.com/
  13346. */
  13347. THREE.Line = function ( geometry, material, mode ) {
  13348. if ( mode === 1 ) {
  13349. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  13350. return new THREE.LineSegments( geometry, material );
  13351. }
  13352. THREE.Object3D.call( this );
  13353. this.type = 'Line';
  13354. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  13355. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  13356. };
  13357. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  13358. THREE.Line.prototype.constructor = THREE.Line;
  13359. THREE.Line.prototype.raycast = ( function () {
  13360. var inverseMatrix = new THREE.Matrix4();
  13361. var ray = new THREE.Ray();
  13362. var sphere = new THREE.Sphere();
  13363. return function raycast( raycaster, intersects ) {
  13364. var precision = raycaster.linePrecision;
  13365. var precisionSq = precision * precision;
  13366. var geometry = this.geometry;
  13367. var matrixWorld = this.matrixWorld;
  13368. // Checking boundingSphere distance to ray
  13369. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13370. sphere.copy( geometry.boundingSphere );
  13371. sphere.applyMatrix4( matrixWorld );
  13372. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13373. //
  13374. inverseMatrix.getInverse( matrixWorld );
  13375. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13376. var vStart = new THREE.Vector3();
  13377. var vEnd = new THREE.Vector3();
  13378. var interSegment = new THREE.Vector3();
  13379. var interRay = new THREE.Vector3();
  13380. var step = this instanceof THREE.LineSegments ? 2 : 1;
  13381. if ( geometry instanceof THREE.BufferGeometry ) {
  13382. var index = geometry.index;
  13383. var attributes = geometry.attributes;
  13384. var positions = attributes.position.array;
  13385. if ( index !== null ) {
  13386. var indices = index.array;
  13387. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  13388. var a = indices[ i ];
  13389. var b = indices[ i + 1 ];
  13390. vStart.fromArray( positions, a * 3 );
  13391. vEnd.fromArray( positions, b * 3 );
  13392. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13393. if ( distSq > precisionSq ) continue;
  13394. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13395. var distance = raycaster.ray.origin.distanceTo( interRay );
  13396. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13397. intersects.push( {
  13398. distance: distance,
  13399. // What do we want? intersection point on the ray or on the segment??
  13400. // point: raycaster.ray.at( distance ),
  13401. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13402. index: i,
  13403. face: null,
  13404. faceIndex: null,
  13405. object: this
  13406. } );
  13407. }
  13408. } else {
  13409. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  13410. vStart.fromArray( positions, 3 * i );
  13411. vEnd.fromArray( positions, 3 * i + 3 );
  13412. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  13413. if ( distSq > precisionSq ) continue;
  13414. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13415. var distance = raycaster.ray.origin.distanceTo( interRay );
  13416. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13417. intersects.push( {
  13418. distance: distance,
  13419. // What do we want? intersection point on the ray or on the segment??
  13420. // point: raycaster.ray.at( distance ),
  13421. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13422. index: i,
  13423. face: null,
  13424. faceIndex: null,
  13425. object: this
  13426. } );
  13427. }
  13428. }
  13429. } else if ( geometry instanceof THREE.Geometry ) {
  13430. var vertices = geometry.vertices;
  13431. var nbVertices = vertices.length;
  13432. for ( var i = 0; i < nbVertices - 1; i += step ) {
  13433. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  13434. if ( distSq > precisionSq ) continue;
  13435. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  13436. var distance = raycaster.ray.origin.distanceTo( interRay );
  13437. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  13438. intersects.push( {
  13439. distance: distance,
  13440. // What do we want? intersection point on the ray or on the segment??
  13441. // point: raycaster.ray.at( distance ),
  13442. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  13443. index: i,
  13444. face: null,
  13445. faceIndex: null,
  13446. object: this
  13447. } );
  13448. }
  13449. }
  13450. };
  13451. }() );
  13452. THREE.Line.prototype.clone = function () {
  13453. return new this.constructor( this.geometry, this.material ).copy( this );
  13454. };
  13455. // DEPRECATED
  13456. THREE.LineStrip = 0;
  13457. THREE.LinePieces = 1;
  13458. // File:src/objects/LineSegments.js
  13459. /**
  13460. * @author mrdoob / http://mrdoob.com/
  13461. */
  13462. THREE.LineSegments = function ( geometry, material ) {
  13463. THREE.Line.call( this, geometry, material );
  13464. this.type = 'LineSegments';
  13465. };
  13466. THREE.LineSegments.prototype = Object.create( THREE.Line.prototype );
  13467. THREE.LineSegments.prototype.constructor = THREE.LineSegments;
  13468. // File:src/objects/Mesh.js
  13469. /**
  13470. * @author mrdoob / http://mrdoob.com/
  13471. * @author alteredq / http://alteredqualia.com/
  13472. * @author mikael emtinger / http://gomo.se/
  13473. * @author jonobr1 / http://jonobr1.com/
  13474. */
  13475. THREE.Mesh = function ( geometry, material ) {
  13476. THREE.Object3D.call( this );
  13477. this.type = 'Mesh';
  13478. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  13479. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13480. this.drawMode = THREE.TrianglesDrawMode;
  13481. this.updateMorphTargets();
  13482. };
  13483. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  13484. THREE.Mesh.prototype.constructor = THREE.Mesh;
  13485. THREE.Mesh.prototype.setDrawMode = function ( value ) {
  13486. this.drawMode = value;
  13487. };
  13488. THREE.Mesh.prototype.updateMorphTargets = function () {
  13489. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  13490. this.morphTargetBase = - 1;
  13491. this.morphTargetInfluences = [];
  13492. this.morphTargetDictionary = {};
  13493. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  13494. this.morphTargetInfluences.push( 0 );
  13495. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  13496. }
  13497. }
  13498. };
  13499. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  13500. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  13501. return this.morphTargetDictionary[ name ];
  13502. }
  13503. console.warn( 'THREE.Mesh.getMorphTargetIndexByName: morph target ' + name + ' does not exist. Returning 0.' );
  13504. return 0;
  13505. };
  13506. THREE.Mesh.prototype.raycast = ( function () {
  13507. var inverseMatrix = new THREE.Matrix4();
  13508. var ray = new THREE.Ray();
  13509. var sphere = new THREE.Sphere();
  13510. var vA = new THREE.Vector3();
  13511. var vB = new THREE.Vector3();
  13512. var vC = new THREE.Vector3();
  13513. var tempA = new THREE.Vector3();
  13514. var tempB = new THREE.Vector3();
  13515. var tempC = new THREE.Vector3();
  13516. var uvA = new THREE.Vector2();
  13517. var uvB = new THREE.Vector2();
  13518. var uvC = new THREE.Vector2();
  13519. var barycoord = new THREE.Vector3();
  13520. var intersectionPoint = new THREE.Vector3();
  13521. var intersectionPointWorld = new THREE.Vector3();
  13522. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  13523. THREE.Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  13524. uv1.multiplyScalar( barycoord.x );
  13525. uv2.multiplyScalar( barycoord.y );
  13526. uv3.multiplyScalar( barycoord.z );
  13527. uv1.add( uv2 ).add( uv3 );
  13528. return uv1.clone();
  13529. }
  13530. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  13531. var intersect;
  13532. var material = object.material;
  13533. if ( material.side === THREE.BackSide ) {
  13534. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  13535. } else {
  13536. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== THREE.DoubleSide, point );
  13537. }
  13538. if ( intersect === null ) return null;
  13539. intersectionPointWorld.copy( point );
  13540. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  13541. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  13542. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  13543. return {
  13544. distance: distance,
  13545. point: intersectionPointWorld.clone(),
  13546. object: object
  13547. };
  13548. }
  13549. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  13550. vA.fromArray( positions, a * 3 );
  13551. vB.fromArray( positions, b * 3 );
  13552. vC.fromArray( positions, c * 3 );
  13553. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  13554. if ( intersection ) {
  13555. if ( uvs ) {
  13556. uvA.fromArray( uvs, a * 2 );
  13557. uvB.fromArray( uvs, b * 2 );
  13558. uvC.fromArray( uvs, c * 2 );
  13559. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  13560. }
  13561. intersection.face = new THREE.Face3( a, b, c, THREE.Triangle.normal( vA, vB, vC ) );
  13562. intersection.faceIndex = a;
  13563. }
  13564. return intersection;
  13565. }
  13566. return function raycast( raycaster, intersects ) {
  13567. var geometry = this.geometry;
  13568. var material = this.material;
  13569. var matrixWorld = this.matrixWorld;
  13570. if ( material === undefined ) return;
  13571. // Checking boundingSphere distance to ray
  13572. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13573. sphere.copy( geometry.boundingSphere );
  13574. sphere.applyMatrix4( matrixWorld );
  13575. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13576. //
  13577. inverseMatrix.getInverse( matrixWorld );
  13578. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13579. // Check boundingBox before continuing
  13580. if ( geometry.boundingBox !== null ) {
  13581. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13582. }
  13583. var uvs, intersection;
  13584. if ( geometry instanceof THREE.BufferGeometry ) {
  13585. var a, b, c;
  13586. var index = geometry.index;
  13587. var attributes = geometry.attributes;
  13588. var positions = attributes.position.array;
  13589. if ( attributes.uv !== undefined ) {
  13590. uvs = attributes.uv.array;
  13591. }
  13592. if ( index !== null ) {
  13593. var indices = index.array;
  13594. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  13595. a = indices[ i ];
  13596. b = indices[ i + 1 ];
  13597. c = indices[ i + 2 ];
  13598. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13599. if ( intersection ) {
  13600. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  13601. intersects.push( intersection );
  13602. }
  13603. }
  13604. } else {
  13605. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  13606. a = i / 3;
  13607. b = a + 1;
  13608. c = a + 2;
  13609. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13610. if ( intersection ) {
  13611. intersection.index = a; // triangle number in positions buffer semantics
  13612. intersects.push( intersection );
  13613. }
  13614. }
  13615. }
  13616. } else if ( geometry instanceof THREE.Geometry ) {
  13617. var fvA, fvB, fvC;
  13618. var isFaceMaterial = material instanceof THREE.MultiMaterial;
  13619. var materials = isFaceMaterial === true ? material.materials : null;
  13620. var vertices = geometry.vertices;
  13621. var faces = geometry.faces;
  13622. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13623. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13624. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13625. var face = faces[ f ];
  13626. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  13627. if ( faceMaterial === undefined ) continue;
  13628. fvA = vertices[ face.a ];
  13629. fvB = vertices[ face.b ];
  13630. fvC = vertices[ face.c ];
  13631. if ( faceMaterial.morphTargets === true ) {
  13632. var morphTargets = geometry.morphTargets;
  13633. var morphInfluences = this.morphTargetInfluences;
  13634. vA.set( 0, 0, 0 );
  13635. vB.set( 0, 0, 0 );
  13636. vC.set( 0, 0, 0 );
  13637. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  13638. var influence = morphInfluences[ t ];
  13639. if ( influence === 0 ) continue;
  13640. var targets = morphTargets[ t ].vertices;
  13641. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  13642. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  13643. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  13644. }
  13645. vA.add( fvA );
  13646. vB.add( fvB );
  13647. vC.add( fvC );
  13648. fvA = vA;
  13649. fvB = vB;
  13650. fvC = vC;
  13651. }
  13652. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13653. if ( intersection ) {
  13654. if ( uvs ) {
  13655. var uvs_f = uvs[ f ];
  13656. uvA.copy( uvs_f[ 0 ] );
  13657. uvB.copy( uvs_f[ 1 ] );
  13658. uvC.copy( uvs_f[ 2 ] );
  13659. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13660. }
  13661. intersection.face = face;
  13662. intersection.faceIndex = f;
  13663. intersects.push( intersection );
  13664. }
  13665. }
  13666. }
  13667. };
  13668. }() );
  13669. THREE.Mesh.prototype.clone = function () {
  13670. return new this.constructor( this.geometry, this.material ).copy( this );
  13671. };
  13672. // File:src/objects/Bone.js
  13673. /**
  13674. * @author mikael emtinger / http://gomo.se/
  13675. * @author alteredq / http://alteredqualia.com/
  13676. * @author ikerr / http://verold.com
  13677. */
  13678. THREE.Bone = function ( skin ) {
  13679. THREE.Object3D.call( this );
  13680. this.type = 'Bone';
  13681. this.skin = skin;
  13682. };
  13683. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  13684. THREE.Bone.prototype.constructor = THREE.Bone;
  13685. THREE.Bone.prototype.copy = function ( source ) {
  13686. THREE.Object3D.prototype.copy.call( this, source );
  13687. this.skin = source.skin;
  13688. return this;
  13689. };
  13690. // File:src/objects/Skeleton.js
  13691. /**
  13692. * @author mikael emtinger / http://gomo.se/
  13693. * @author alteredq / http://alteredqualia.com/
  13694. * @author michael guerrero / http://realitymeltdown.com
  13695. * @author ikerr / http://verold.com
  13696. */
  13697. THREE.Skeleton = function ( bones, boneInverses, useVertexTexture ) {
  13698. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  13699. this.identityMatrix = new THREE.Matrix4();
  13700. // copy the bone array
  13701. bones = bones || [];
  13702. this.bones = bones.slice( 0 );
  13703. // create a bone texture or an array of floats
  13704. if ( this.useVertexTexture ) {
  13705. // layout (1 matrix = 4 pixels)
  13706. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  13707. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  13708. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  13709. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  13710. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  13711. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  13712. size = THREE.Math.nextPowerOfTwo( Math.ceil( size ) );
  13713. size = Math.max( size, 4 );
  13714. this.boneTextureWidth = size;
  13715. this.boneTextureHeight = size;
  13716. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  13717. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  13718. } else {
  13719. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  13720. }
  13721. // use the supplied bone inverses or calculate the inverses
  13722. if ( boneInverses === undefined ) {
  13723. this.calculateInverses();
  13724. } else {
  13725. if ( this.bones.length === boneInverses.length ) {
  13726. this.boneInverses = boneInverses.slice( 0 );
  13727. } else {
  13728. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  13729. this.boneInverses = [];
  13730. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13731. this.boneInverses.push( new THREE.Matrix4() );
  13732. }
  13733. }
  13734. }
  13735. };
  13736. THREE.Skeleton.prototype.calculateInverses = function () {
  13737. this.boneInverses = [];
  13738. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13739. var inverse = new THREE.Matrix4();
  13740. if ( this.bones[ b ] ) {
  13741. inverse.getInverse( this.bones[ b ].matrixWorld );
  13742. }
  13743. this.boneInverses.push( inverse );
  13744. }
  13745. };
  13746. THREE.Skeleton.prototype.pose = function () {
  13747. var bone;
  13748. // recover the bind-time world matrices
  13749. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13750. bone = this.bones[ b ];
  13751. if ( bone ) {
  13752. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  13753. }
  13754. }
  13755. // compute the local matrices, positions, rotations and scales
  13756. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13757. bone = this.bones[ b ];
  13758. if ( bone ) {
  13759. if ( bone.parent ) {
  13760. bone.matrix.getInverse( bone.parent.matrixWorld );
  13761. bone.matrix.multiply( bone.matrixWorld );
  13762. } else {
  13763. bone.matrix.copy( bone.matrixWorld );
  13764. }
  13765. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  13766. }
  13767. }
  13768. };
  13769. THREE.Skeleton.prototype.update = ( function () {
  13770. var offsetMatrix = new THREE.Matrix4();
  13771. return function update() {
  13772. // flatten bone matrices to array
  13773. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  13774. // compute the offset between the current and the original transform
  13775. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  13776. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  13777. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  13778. }
  13779. if ( this.useVertexTexture ) {
  13780. this.boneTexture.needsUpdate = true;
  13781. }
  13782. };
  13783. } )();
  13784. THREE.Skeleton.prototype.clone = function () {
  13785. return new THREE.Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  13786. };
  13787. // File:src/objects/SkinnedMesh.js
  13788. /**
  13789. * @author mikael emtinger / http://gomo.se/
  13790. * @author alteredq / http://alteredqualia.com/
  13791. * @author ikerr / http://verold.com
  13792. */
  13793. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  13794. THREE.Mesh.call( this, geometry, material );
  13795. this.type = 'SkinnedMesh';
  13796. this.bindMode = "attached";
  13797. this.bindMatrix = new THREE.Matrix4();
  13798. this.bindMatrixInverse = new THREE.Matrix4();
  13799. // init bones
  13800. // TODO: remove bone creation as there is no reason (other than
  13801. // convenience) for THREE.SkinnedMesh to do this.
  13802. var bones = [];
  13803. if ( this.geometry && this.geometry.bones !== undefined ) {
  13804. var bone, gbone;
  13805. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13806. gbone = this.geometry.bones[ b ];
  13807. bone = new THREE.Bone( this );
  13808. bones.push( bone );
  13809. bone.name = gbone.name;
  13810. bone.position.fromArray( gbone.pos );
  13811. bone.quaternion.fromArray( gbone.rotq );
  13812. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  13813. }
  13814. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  13815. gbone = this.geometry.bones[ b ];
  13816. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  13817. bones[ gbone.parent ] !== undefined ) {
  13818. bones[ gbone.parent ].add( bones[ b ] );
  13819. } else {
  13820. this.add( bones[ b ] );
  13821. }
  13822. }
  13823. }
  13824. this.normalizeSkinWeights();
  13825. this.updateMatrixWorld( true );
  13826. this.bind( new THREE.Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  13827. };
  13828. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  13829. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  13830. THREE.SkinnedMesh.prototype.bind = function( skeleton, bindMatrix ) {
  13831. this.skeleton = skeleton;
  13832. if ( bindMatrix === undefined ) {
  13833. this.updateMatrixWorld( true );
  13834. this.skeleton.calculateInverses();
  13835. bindMatrix = this.matrixWorld;
  13836. }
  13837. this.bindMatrix.copy( bindMatrix );
  13838. this.bindMatrixInverse.getInverse( bindMatrix );
  13839. };
  13840. THREE.SkinnedMesh.prototype.pose = function () {
  13841. this.skeleton.pose();
  13842. };
  13843. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  13844. if ( this.geometry instanceof THREE.Geometry ) {
  13845. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  13846. var sw = this.geometry.skinWeights[ i ];
  13847. var scale = 1.0 / sw.lengthManhattan();
  13848. if ( scale !== Infinity ) {
  13849. sw.multiplyScalar( scale );
  13850. } else {
  13851. sw.set( 1, 0, 0, 0 ); // do something reasonable
  13852. }
  13853. }
  13854. } else if ( this.geometry instanceof THREE.BufferGeometry ) {
  13855. var vec = new THREE.Vector4();
  13856. var skinWeight = this.geometry.attributes.skinWeight;
  13857. for ( var i = 0; i < skinWeight.count; i ++ ) {
  13858. vec.x = skinWeight.getX( i );
  13859. vec.y = skinWeight.getY( i );
  13860. vec.z = skinWeight.getZ( i );
  13861. vec.w = skinWeight.getW( i );
  13862. var scale = 1.0 / vec.lengthManhattan();
  13863. if ( scale !== Infinity ) {
  13864. vec.multiplyScalar( scale );
  13865. } else {
  13866. vec.set( 1, 0, 0, 0 ); // do something reasonable
  13867. }
  13868. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  13869. }
  13870. }
  13871. };
  13872. THREE.SkinnedMesh.prototype.updateMatrixWorld = function( force ) {
  13873. THREE.Mesh.prototype.updateMatrixWorld.call( this, true );
  13874. if ( this.bindMode === "attached" ) {
  13875. this.bindMatrixInverse.getInverse( this.matrixWorld );
  13876. } else if ( this.bindMode === "detached" ) {
  13877. this.bindMatrixInverse.getInverse( this.bindMatrix );
  13878. } else {
  13879. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  13880. }
  13881. };
  13882. THREE.SkinnedMesh.prototype.clone = function() {
  13883. return new this.constructor( this.geometry, this.material, this.useVertexTexture ).copy( this );
  13884. };
  13885. // File:src/objects/LOD.js
  13886. /**
  13887. * @author mikael emtinger / http://gomo.se/
  13888. * @author alteredq / http://alteredqualia.com/
  13889. * @author mrdoob / http://mrdoob.com/
  13890. */
  13891. THREE.LOD = function () {
  13892. THREE.Object3D.call( this );
  13893. this.type = 'LOD';
  13894. Object.defineProperties( this, {
  13895. levels: {
  13896. enumerable: true,
  13897. value: []
  13898. }
  13899. } );
  13900. };
  13901. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  13902. THREE.LOD.prototype.constructor = THREE.LOD;
  13903. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  13904. if ( distance === undefined ) distance = 0;
  13905. distance = Math.abs( distance );
  13906. var levels = this.levels;
  13907. for ( var l = 0; l < levels.length; l ++ ) {
  13908. if ( distance < levels[ l ].distance ) {
  13909. break;
  13910. }
  13911. }
  13912. levels.splice( l, 0, { distance: distance, object: object } );
  13913. this.add( object );
  13914. };
  13915. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  13916. var levels = this.levels;
  13917. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13918. if ( distance < levels[ i ].distance ) {
  13919. break;
  13920. }
  13921. }
  13922. return levels[ i - 1 ].object;
  13923. };
  13924. THREE.LOD.prototype.raycast = ( function () {
  13925. var matrixPosition = new THREE.Vector3();
  13926. return function raycast( raycaster, intersects ) {
  13927. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  13928. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  13929. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  13930. };
  13931. }() );
  13932. THREE.LOD.prototype.update = function () {
  13933. var v1 = new THREE.Vector3();
  13934. var v2 = new THREE.Vector3();
  13935. return function update( camera ) {
  13936. var levels = this.levels;
  13937. if ( levels.length > 1 ) {
  13938. v1.setFromMatrixPosition( camera.matrixWorld );
  13939. v2.setFromMatrixPosition( this.matrixWorld );
  13940. var distance = v1.distanceTo( v2 );
  13941. levels[ 0 ].object.visible = true;
  13942. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  13943. if ( distance >= levels[ i ].distance ) {
  13944. levels[ i - 1 ].object.visible = false;
  13945. levels[ i ].object.visible = true;
  13946. } else {
  13947. break;
  13948. }
  13949. }
  13950. for ( ; i < l; i ++ ) {
  13951. levels[ i ].object.visible = false;
  13952. }
  13953. }
  13954. };
  13955. }();
  13956. THREE.LOD.prototype.copy = function ( source ) {
  13957. THREE.Object3D.prototype.copy.call( this, source, false );
  13958. var levels = source.levels;
  13959. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13960. var level = levels[ i ];
  13961. this.addLevel( level.object.clone(), level.distance );
  13962. }
  13963. return this;
  13964. };
  13965. THREE.LOD.prototype.toJSON = function ( meta ) {
  13966. var data = THREE.Object3D.prototype.toJSON.call( this, meta );
  13967. data.object.levels = [];
  13968. var levels = this.levels;
  13969. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  13970. var level = levels[ i ];
  13971. data.object.levels.push( {
  13972. object: level.object.uuid,
  13973. distance: level.distance
  13974. } );
  13975. }
  13976. return data;
  13977. };
  13978. // File:src/objects/Sprite.js
  13979. /**
  13980. * @author mikael emtinger / http://gomo.se/
  13981. * @author alteredq / http://alteredqualia.com/
  13982. */
  13983. THREE.Sprite = ( function () {
  13984. var indices = new Uint16Array( [ 0, 1, 2, 0, 2, 3 ] );
  13985. var vertices = new Float32Array( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0, - 0.5, 0.5, 0 ] );
  13986. var uvs = new Float32Array( [ 0, 0, 1, 0, 1, 1, 0, 1 ] );
  13987. var geometry = new THREE.BufferGeometry();
  13988. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  13989. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  13990. geometry.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  13991. return function Sprite( material ) {
  13992. THREE.Object3D.call( this );
  13993. this.type = 'Sprite';
  13994. this.geometry = geometry;
  13995. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  13996. };
  13997. } )();
  13998. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  13999. THREE.Sprite.prototype.constructor = THREE.Sprite;
  14000. THREE.Sprite.prototype.raycast = ( function () {
  14001. var matrixPosition = new THREE.Vector3();
  14002. return function raycast( raycaster, intersects ) {
  14003. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  14004. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  14005. var guessSizeSq = this.scale.x * this.scale.y / 4;
  14006. if ( distanceSq > guessSizeSq ) {
  14007. return;
  14008. }
  14009. intersects.push( {
  14010. distance: Math.sqrt( distanceSq ),
  14011. point: this.position,
  14012. face: null,
  14013. object: this
  14014. } );
  14015. };
  14016. }() );
  14017. THREE.Sprite.prototype.clone = function () {
  14018. return new this.constructor( this.material ).copy( this );
  14019. };
  14020. // Backwards compatibility
  14021. THREE.Particle = THREE.Sprite;
  14022. // File:src/objects/LensFlare.js
  14023. /**
  14024. * @author mikael emtinger / http://gomo.se/
  14025. * @author alteredq / http://alteredqualia.com/
  14026. */
  14027. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  14028. THREE.Object3D.call( this );
  14029. this.lensFlares = [];
  14030. this.positionScreen = new THREE.Vector3();
  14031. this.customUpdateCallback = undefined;
  14032. if ( texture !== undefined ) {
  14033. this.add( texture, size, distance, blending, color );
  14034. }
  14035. };
  14036. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  14037. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  14038. /*
  14039. * Add: adds another flare
  14040. */
  14041. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  14042. if ( size === undefined ) size = - 1;
  14043. if ( distance === undefined ) distance = 0;
  14044. if ( opacity === undefined ) opacity = 1;
  14045. if ( color === undefined ) color = new THREE.Color( 0xffffff );
  14046. if ( blending === undefined ) blending = THREE.NormalBlending;
  14047. distance = Math.min( distance, Math.max( 0, distance ) );
  14048. this.lensFlares.push( {
  14049. texture: texture, // THREE.Texture
  14050. size: size, // size in pixels (-1 = use texture.width)
  14051. distance: distance, // distance (0-1) from light source (0=at light source)
  14052. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  14053. scale: 1, // scale
  14054. rotation: 0, // rotation
  14055. opacity: opacity, // opacity
  14056. color: color, // color
  14057. blending: blending // blending
  14058. } );
  14059. };
  14060. /*
  14061. * Update lens flares update positions on all flares based on the screen position
  14062. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  14063. */
  14064. THREE.LensFlare.prototype.updateLensFlares = function () {
  14065. var f, fl = this.lensFlares.length;
  14066. var flare;
  14067. var vecX = - this.positionScreen.x * 2;
  14068. var vecY = - this.positionScreen.y * 2;
  14069. for ( f = 0; f < fl; f ++ ) {
  14070. flare = this.lensFlares[ f ];
  14071. flare.x = this.positionScreen.x + vecX * flare.distance;
  14072. flare.y = this.positionScreen.y + vecY * flare.distance;
  14073. flare.wantedRotation = flare.x * Math.PI * 0.25;
  14074. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  14075. }
  14076. };
  14077. THREE.LensFlare.prototype.copy = function ( source ) {
  14078. THREE.Object3D.prototype.copy.call( this, source );
  14079. this.positionScreen.copy( source.positionScreen );
  14080. this.customUpdateCallback = source.customUpdateCallback;
  14081. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  14082. this.lensFlares.push( source.lensFlares[ i ] );
  14083. }
  14084. return this;
  14085. };
  14086. // File:src/scenes/Scene.js
  14087. /**
  14088. * @author mrdoob / http://mrdoob.com/
  14089. */
  14090. THREE.Scene = function () {
  14091. THREE.Object3D.call( this );
  14092. this.type = 'Scene';
  14093. this.fog = null;
  14094. this.overrideMaterial = null;
  14095. this.autoUpdate = true; // checked by the renderer
  14096. };
  14097. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  14098. THREE.Scene.prototype.constructor = THREE.Scene;
  14099. THREE.Scene.prototype.copy = function ( source, recursive ) {
  14100. THREE.Object3D.prototype.copy.call( this, source, recursive );
  14101. if ( source.fog !== null ) this.fog = source.fog.clone();
  14102. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  14103. this.autoUpdate = source.autoUpdate;
  14104. this.matrixAutoUpdate = source.matrixAutoUpdate;
  14105. return this;
  14106. };
  14107. // File:src/scenes/Fog.js
  14108. /**
  14109. * @author mrdoob / http://mrdoob.com/
  14110. * @author alteredq / http://alteredqualia.com/
  14111. */
  14112. THREE.Fog = function ( color, near, far ) {
  14113. this.name = '';
  14114. this.color = new THREE.Color( color );
  14115. this.near = ( near !== undefined ) ? near : 1;
  14116. this.far = ( far !== undefined ) ? far : 1000;
  14117. };
  14118. THREE.Fog.prototype.clone = function () {
  14119. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  14120. };
  14121. // File:src/scenes/FogExp2.js
  14122. /**
  14123. * @author mrdoob / http://mrdoob.com/
  14124. * @author alteredq / http://alteredqualia.com/
  14125. */
  14126. THREE.FogExp2 = function ( color, density ) {
  14127. this.name = '';
  14128. this.color = new THREE.Color( color );
  14129. this.density = ( density !== undefined ) ? density : 0.00025;
  14130. };
  14131. THREE.FogExp2.prototype.clone = function () {
  14132. return new THREE.FogExp2( this.color.getHex(), this.density );
  14133. };
  14134. // File:src/renderers/shaders/ShaderChunk.js
  14135. THREE.ShaderChunk = {};
  14136. // File:src/renderers/shaders/ShaderChunk/alphamap_fragment.glsl
  14137. THREE.ShaderChunk[ 'alphamap_fragment' ] = "#ifdef USE_ALPHAMAP\n diffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  14138. // File:src/renderers/shaders/ShaderChunk/alphamap_pars_fragment.glsl
  14139. THREE.ShaderChunk[ 'alphamap_pars_fragment' ] = "#ifdef USE_ALPHAMAP\n uniform sampler2D alphaMap;\n#endif\n";
  14140. // File:src/renderers/shaders/ShaderChunk/alphatest_fragment.glsl
  14141. THREE.ShaderChunk[ 'alphatest_fragment' ] = "#ifdef ALPHATEST\n if ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  14142. // File:src/renderers/shaders/ShaderChunk/aomap_fragment.glsl
  14143. THREE.ShaderChunk[ 'aomap_fragment' ] = "#ifdef USE_AOMAP\n float ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n reflectedLight.indirectDiffuse *= ambientOcclusion;\n #if defined( USE_ENVMAP ) && defined( PHYSICAL )\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n #endif\n#endif\n";
  14144. // File:src/renderers/shaders/ShaderChunk/aomap_pars_fragment.glsl
  14145. THREE.ShaderChunk[ 'aomap_pars_fragment' ] = "#ifdef USE_AOMAP\n uniform sampler2D aoMap;\n uniform float aoMapIntensity;\n#endif";
  14146. // File:src/renderers/shaders/ShaderChunk/begin_vertex.glsl
  14147. THREE.ShaderChunk[ 'begin_vertex' ] = "\nvec3 transformed = vec3( position );\n";
  14148. // File:src/renderers/shaders/ShaderChunk/beginnormal_vertex.glsl
  14149. THREE.ShaderChunk[ 'beginnormal_vertex' ] = "\nvec3 objectNormal = vec3( normal );\n";
  14150. // File:src/renderers/shaders/ShaderChunk/bsdfs.glsl
  14151. THREE.ShaderChunk[ 'bsdfs' ] = "bool testLightInRange( const in float lightDistance, const in float cutoffDistance ) {\n return any( bvec2( cutoffDistance == 0.0, lightDistance < cutoffDistance ) );\n}\nfloat punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n if( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n float maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n return distanceFalloff * maxDistanceCutoffFactor;\n#else\n return pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n }\n return 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n return RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n return ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n return 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n float a2 = pow2( alpha );\n float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n return 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n float a2 = pow2( alpha );\n float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n return RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float alpha = pow2( roughness );\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n float D = D_GGX( alpha, dotNH );\n return F * ( G * D );\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n return specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n return 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n vec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n float dotNH = saturate( dot( geometry.normal, halfDir ) );\n float dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n vec3 F = F_Schlick( specularColor, dotLH );\n float G = G_BlinnPhong_Implicit( );\n float D = D_BlinnPhong( shininess, dotNH );\n return F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n return ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n return sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  14152. // File:src/renderers/shaders/ShaderChunk/bumpmap_pars_fragment.glsl
  14153. THREE.ShaderChunk[ 'bumpmap_pars_fragment' ] = "#ifdef USE_BUMPMAP\n uniform sampler2D bumpMap;\n uniform float bumpScale;\n vec2 dHdxy_fwd() {\n vec2 dSTdx = dFdx( vUv );\n vec2 dSTdy = dFdy( vUv );\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 return vec2( dBx, dBy );\n }\n vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n vec3 vSigmaX = dFdx( surf_pos );\n vec3 vSigmaY = dFdy( surf_pos );\n vec3 vN = surf_norm;\n vec3 R1 = cross( vSigmaY, vN );\n vec3 R2 = cross( vN, vSigmaX );\n float fDet = dot( vSigmaX, R1 );\n vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n return normalize( abs( fDet ) * surf_norm - vGrad );\n }\n#endif\n";
  14154. // File:src/renderers/shaders/ShaderChunk/clipping_planes_fragment.glsl
  14155. THREE.ShaderChunk[ 'clipping_planes_fragment' ] = "#if NUM_CLIPPING_PLANES > 0\n for ( int i = 0; i < NUM_CLIPPING_PLANES; ++ i ) {\n vec4 plane = clippingPlanes[ i ];\n if ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n }\n#endif\n";
  14156. // File:src/renderers/shaders/ShaderChunk/clipping_planes_pars_fragment.glsl
  14157. THREE.ShaderChunk[ 'clipping_planes_pars_fragment' ] = "#if NUM_CLIPPING_PLANES > 0\n #if ! defined( PHYSICAL ) && ! defined( PHONG )\n varying vec3 vViewPosition;\n #endif\n uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  14158. // File:src/renderers/shaders/ShaderChunk/clipping_planes_pars_vertex.glsl
  14159. THREE.ShaderChunk[ 'clipping_planes_pars_vertex' ] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n varying vec3 vViewPosition;\n#endif\n";
  14160. // File:src/renderers/shaders/ShaderChunk/clipping_planes_vertex.glsl
  14161. THREE.ShaderChunk[ 'clipping_planes_vertex' ] = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n vViewPosition = - mvPosition.xyz;\n#endif\n";
  14162. // File:src/renderers/shaders/ShaderChunk/color_fragment.glsl
  14163. THREE.ShaderChunk[ 'color_fragment' ] = "#ifdef USE_COLOR\n diffuseColor.rgb *= vColor;\n#endif";
  14164. // File:src/renderers/shaders/ShaderChunk/color_pars_fragment.glsl
  14165. THREE.ShaderChunk[ 'color_pars_fragment' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif\n";
  14166. // File:src/renderers/shaders/ShaderChunk/color_pars_vertex.glsl
  14167. THREE.ShaderChunk[ 'color_pars_vertex' ] = "#ifdef USE_COLOR\n varying vec3 vColor;\n#endif";
  14168. // File:src/renderers/shaders/ShaderChunk/color_vertex.glsl
  14169. THREE.ShaderChunk[ 'color_vertex' ] = "#ifdef USE_COLOR\n vColor.xyz = color.xyz;\n#endif";
  14170. // File:src/renderers/shaders/ShaderChunk/common.glsl
  14171. THREE.ShaderChunk[ 'common' ] = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n return fract(sin(sn) * c);\n}\nstruct IncidentLight {\n vec3 color;\n vec3 direction;\n bool visible;\n};\nstruct ReflectedLight {\n vec3 directDiffuse;\n vec3 directSpecular;\n vec3 indirectDiffuse;\n vec3 indirectSpecular;\n};\nstruct GeometricContext {\n vec3 position;\n vec3 normal;\n vec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n float distance = dot( planeNormal, point - pointOnPlane );\n return - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n return lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\n";
  14172. // File:src/renderers/shaders/ShaderChunk/cube_uv_reflection_fragment.glsl
  14173. THREE.ShaderChunk[ 'cube_uv_reflection_fragment' ] = "#ifdef ENVMAP_TYPE_CUBE_UV\nconst float cubeUV_textureSize = 1024.0;\nint getFaceFromDirection(vec3 direction) {\n vec3 absDirection = abs(direction);\n int face = -1;\n if( absDirection.x > absDirection.z ) {\n if(absDirection.x > absDirection.y )\n face = direction.x > 0.0 ? 0 : 3;\n else\n face = direction.y > 0.0 ? 1 : 4;\n }\n else {\n if(absDirection.z > absDirection.y )\n face = direction.z > 0.0 ? 2 : 5;\n else\n face = direction.y > 0.0 ? 1 : 4;\n }\n return face;\n}\nfloat cubeUV_maxLods1 = log2(cubeUV_textureSize*0.25) - 1.0;\nfloat cubeUV_rangeClamp = exp2((6.0 - 1.0) * 2.0);\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n float scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n float dxRoughness = dFdx(roughness);\n float dyRoughness = dFdy(roughness);\n vec3 dx = dFdx( vec * scale * dxRoughness );\n vec3 dy = dFdy( vec * scale * dyRoughness );\n float d = max( dot( dx, dx ), dot( dy, dy ) );\n d = clamp(d, 1.0, cubeUV_rangeClamp);\n float mipLevel = 0.5 * log2(d);\n return vec2(floor(mipLevel), fract(mipLevel));\n}\nfloat cubeUV_maxLods2 = log2(cubeUV_textureSize*0.25) - 2.0;\nconst float cubeUV_rcpTextureSize = 1.0 / cubeUV_textureSize;\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n mipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n float a = 16.0 * cubeUV_rcpTextureSize;\n vec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n vec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n float powScale = exp2_packed.x * exp2_packed.y;\n float scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n float mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n bool bRes = mipLevel == 0.0;\n scale = bRes && (scale < a) ? a : scale;\n vec3 r;\n vec2 offset;\n int face = getFaceFromDirection(direction);\n float rcpPowScale = 1.0 / powScale;\n if( face == 0) {\n r = vec3(direction.x, -direction.z, direction.y);\n offset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n }\n else if( face == 1) {\n r = vec3(direction.y, direction.x, direction.z);\n offset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n }\n else if( face == 2) {\n r = vec3(direction.z, direction.x, direction.y);\n offset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n }\n else if( face == 3) {\n r = vec3(direction.x, direction.z, direction.y);\n offset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n }\n else if( face == 4) {\n r = vec3(direction.y, direction.x, -direction.z);\n offset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n }\n else {\n r = vec3(direction.z, -direction.x, direction.y);\n offset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n offset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n }\n r = normalize(r);\n float texelOffset = 0.5 * cubeUV_rcpTextureSize;\n vec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n vec2 base = offset + vec2( texelOffset );\n return base + s * ( scale - 2.0 * texelOffset );\n}\nfloat cubeUV_maxLods3 = log2(cubeUV_textureSize*0.25) - 3.0;\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n float roughnessVal = roughness* cubeUV_maxLods3;\n float r1 = floor(roughnessVal);\n float r2 = r1 + 1.0;\n float t = fract(roughnessVal);\n vec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n float s = mipInfo.y;\n float level0 = mipInfo.x;\n float level1 = level0 + 1.0;\n level1 = level1 > 5.0 ? 5.0 : level1;\n level0 += min( floor( s + 0.5 ), 5.0 );\n vec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n vec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n vec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n vec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n vec4 result = mix(color10, color20, t);\n return vec4(result.rgb, 1.0);\n}\n#endif\n";
  14174. // File:src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl
  14175. THREE.ShaderChunk[ 'defaultnormal_vertex' ] = "#ifdef FLIP_SIDED\n objectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  14176. // File:src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl
  14177. THREE.ShaderChunk[ 'displacementmap_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n transformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  14178. // File:src/renderers/shaders/ShaderChunk/displacementmap_pars_vertex.glsl
  14179. THREE.ShaderChunk[ 'displacementmap_pars_vertex' ] = "#ifdef USE_DISPLACEMENTMAP\n uniform sampler2D displacementMap;\n uniform float displacementScale;\n uniform float displacementBias;\n#endif\n";
  14180. // File:src/renderers/shaders/ShaderChunk/emissivemap_fragment.glsl
  14181. THREE.ShaderChunk[ 'emissivemap_fragment' ] = "#ifdef USE_EMISSIVEMAP\n vec4 emissiveColor = texture2D( emissiveMap, vUv );\n emissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n totalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  14182. // File:src/renderers/shaders/ShaderChunk/emissivemap_pars_fragment.glsl
  14183. THREE.ShaderChunk[ 'emissivemap_pars_fragment' ] = "#ifdef USE_EMISSIVEMAP\n uniform sampler2D emissiveMap;\n#endif\n";
  14184. // File:src/renderers/shaders/ShaderChunk/encodings_pars_fragment.glsl
  14185. THREE.ShaderChunk[ 'encodings_pars_fragment' ] = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  14186. // File:src/renderers/shaders/ShaderChunk/encodings_fragment.glsl
  14187. THREE.ShaderChunk[ 'encodings_fragment' ] = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  14188. // File:src/renderers/shaders/ShaderChunk/envmap_fragment.glsl
  14189. THREE.ShaderChunk[ 'envmap_fragment' ] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( cameraToVertex, worldNormal );\n #else\n vec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #else\n vec3 reflectVec = vReflect;\n #endif\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n vec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\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 #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 envColor = envMapTexelToLinear( envColor );\n #ifdef ENVMAP_BLENDING_MULTIPLY\n outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_MIX )\n outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n #elif defined( ENVMAP_BLENDING_ADD )\n outgoingLight += envColor.xyz * specularStrength * reflectivity;\n #endif\n#endif\n";
  14190. // File:src/renderers/shaders/ShaderChunk/envmap_pars_fragment.glsl
  14191. THREE.ShaderChunk[ 'envmap_pars_fragment' ] = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n uniform float reflectivity;\n uniform float envMapIntenstiy;\n#endif\n#ifdef USE_ENVMAP\n #if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n varying vec3 vWorldPosition;\n #endif\n #ifdef ENVMAP_TYPE_CUBE\n uniform samplerCube envMap;\n #else\n uniform sampler2D envMap;\n #endif\n uniform float flipEnvMap;\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n uniform float refractionRatio;\n #else\n varying vec3 vReflect;\n #endif\n#endif\n";
  14192. // File:src/renderers/shaders/ShaderChunk/envmap_pars_vertex.glsl
  14193. THREE.ShaderChunk[ 'envmap_pars_vertex' ] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n varying vec3 vWorldPosition;\n #else\n varying vec3 vReflect;\n uniform float refractionRatio;\n #endif\n#endif\n";
  14194. // File:src/renderers/shaders/ShaderChunk/envmap_vertex.glsl
  14195. THREE.ShaderChunk[ 'envmap_vertex' ] = "#ifdef USE_ENVMAP\n #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n vWorldPosition = worldPosition.xyz;\n #else\n vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n #ifdef ENVMAP_MODE_REFLECTION\n vReflect = reflect( cameraToVertex, worldNormal );\n #else\n vReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n #endif\n #endif\n#endif\n";
  14196. // File:src/renderers/shaders/ShaderChunk/fog_fragment.glsl
  14197. THREE.ShaderChunk[ 'fog_fragment' ] = "#ifdef USE_FOG\n #ifdef USE_LOGDEPTHBUF_EXT\n float depth = gl_FragDepthEXT / gl_FragCoord.w;\n #else\n float depth = gl_FragCoord.z / gl_FragCoord.w;\n #endif\n #ifdef FOG_EXP2\n float fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n #else\n float fogFactor = smoothstep( fogNear, fogFar, depth );\n #endif\n gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  14198. // File:src/renderers/shaders/ShaderChunk/fog_pars_fragment.glsl
  14199. THREE.ShaderChunk[ 'fog_pars_fragment' ] = "#ifdef USE_FOG\n uniform vec3 fogColor;\n #ifdef FOG_EXP2\n uniform float fogDensity;\n #else\n uniform float fogNear;\n uniform float fogFar;\n #endif\n#endif";
  14200. // File:src/renderers/shaders/ShaderChunk/lightmap_fragment.glsl
  14201. THREE.ShaderChunk[ 'lightmap_fragment' ] = "#ifdef USE_LIGHTMAP\n reflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  14202. // File:src/renderers/shaders/ShaderChunk/lightmap_pars_fragment.glsl
  14203. THREE.ShaderChunk[ 'lightmap_pars_fragment' ] = "#ifdef USE_LIGHTMAP\n uniform sampler2D lightMap;\n uniform float lightMapIntensity;\n#endif";
  14204. // File:src/renderers/shaders/ShaderChunk/lights_lambert_vertex.glsl
  14205. THREE.ShaderChunk[ 'lights_lambert_vertex' ] = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n vLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n getPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n dotNL = dot( geometry.normal, directLight.direction );\n directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n getSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n dotNL = dot( geometry.normal, directLight.direction );\n directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_DIR_LIGHTS > 0\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n getDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n dotNL = dot( geometry.normal, directLight.direction );\n directLightColor_Diffuse = PI * directLight.color;\n vLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n #ifdef DOUBLE_SIDED\n vLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n #endif\n }\n#endif\n#if NUM_HEMI_LIGHTS > 0\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n vLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n #ifdef DOUBLE_SIDED\n vLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n #endif\n }\n#endif\n";
  14206. // File:src/renderers/shaders/ShaderChunk/lights_pars.glsl
  14207. THREE.ShaderChunk[ 'lights_pars' ] = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n vec3 irradiance = ambientLightColor;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n return irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n struct DirectionalLight {\n vec3 direction;\n vec3 color;\n int shadow;\n float shadowBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n void getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n directLight.color = directionalLight.color;\n directLight.direction = directionalLight.direction;\n directLight.visible = true;\n }\n#endif\n#if NUM_POINT_LIGHTS > 0\n struct PointLight {\n vec3 position;\n vec3 color;\n float distance;\n float decay;\n int shadow;\n float shadowBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n void getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n vec3 lVector = pointLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n float lightDistance = length( lVector );\n if ( testLightInRange( lightDistance, pointLight.distance ) ) {\n directLight.color = pointLight.color;\n directLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n directLight.visible = true;\n } else {\n directLight.color = vec3( 0.0 );\n directLight.visible = false;\n }\n }\n#endif\n#if NUM_SPOT_LIGHTS > 0\n struct SpotLight {\n vec3 position;\n vec3 direction;\n vec3 color;\n float distance;\n float decay;\n float coneCos;\n float penumbraCos;\n int shadow;\n float shadowBias;\n float shadowRadius;\n vec2 shadowMapSize;\n };\n uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n void getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n vec3 lVector = spotLight.position - geometry.position;\n directLight.direction = normalize( lVector );\n float lightDistance = length( lVector );\n float angleCos = dot( directLight.direction, spotLight.direction );\n if ( all( bvec2( angleCos > spotLight.coneCos, testLightInRange( lightDistance, spotLight.distance ) ) ) ) {\n float spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n directLight.color = spotLight.color;\n directLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n directLight.visible = true;\n } else {\n directLight.color = vec3( 0.0 );\n directLight.visible = false;\n }\n }\n#endif\n#if NUM_HEMI_LIGHTS > 0\n struct HemisphereLight {\n vec3 direction;\n vec3 skyColor;\n vec3 groundColor;\n };\n uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n float dotNL = dot( geometry.normal, hemiLight.direction );\n float hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n return irradiance;\n }\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n vec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n vec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n #else\n vec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec3 queryVec = flipNormal * vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n vec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n #else\n vec4 envMapColor = vec4( 0.0 );\n #endif\n return PI * envMapColor.rgb * envMapIntensity;\n }\n float getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n float maxMIPLevelScalar = float( maxMIPLevel );\n float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n }\n vec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n #ifdef ENVMAP_MODE_REFLECTION\n vec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n #else\n vec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n #endif\n #ifdef DOUBLE_SIDED\n float flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n #else\n float flipNormal = 1.0;\n #endif\n reflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n float specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n #ifdef ENVMAP_TYPE_CUBE\n vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n #else\n vec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #elif defined( ENVMAP_TYPE_CUBE_UV )\n vec3 queryReflectVec = flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n vec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\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 #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n #else\n vec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\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 #ifdef TEXTURE_LOD_EXT\n vec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n #else\n vec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n #endif\n envMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n #endif\n return envMapColor.rgb * envMapIntensity;\n }\n#endif\n";
  14208. // File:src/renderers/shaders/ShaderChunk/lights_phong_fragment.glsl
  14209. THREE.ShaderChunk[ 'lights_phong_fragment' ] = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  14210. // File:src/renderers/shaders/ShaderChunk/lights_phong_pars_fragment.glsl
  14211. THREE.ShaderChunk[ 'lights_phong_pars_fragment' ] = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n vec3 diffuseColor;\n vec3 specularColor;\n float specularShininess;\n float specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct RE_Direct_BlinnPhong\n#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material ) (0)\n";
  14212. // File:src/renderers/shaders/ShaderChunk/lights_physical_fragment.glsl
  14213. THREE.ShaderChunk[ 'lights_physical_fragment' ] = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );\n#else\n material.specularColor = mix( vec3( 0.16 * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n#endif\n";
  14214. // File:src/renderers/shaders/ShaderChunk/lights_physical_pars_fragment.glsl
  14215. THREE.ShaderChunk[ 'lights_physical_pars_fragment' ] = "struct PhysicalMaterial {\n vec3 diffuseColor;\n float specularRoughness;\n vec3 specularColor;\n #ifndef STANDARD\n #endif\n};\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n float dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n vec3 irradiance = dotNL * directLight.color;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n irradiance *= PI;\n #endif\n reflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n reflectedLight.directSpecular += irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n reflectedLight.indirectSpecular += radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n}\n#define RE_Direct RE_Direct_Physical\n#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular RE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n";
  14216. // File:src/renderers/shaders/ShaderChunk/lights_template.glsl
  14217. THREE.ShaderChunk[ 'lights_template' ] = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n PointLight pointLight;\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n getPointDirectLightIrradiance( pointLight, geometry, directLight );\n #ifdef USE_SHADOWMAP\n directLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n SpotLight spotLight;\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n getSpotDirectLightIrradiance( spotLight, geometry, directLight );\n #ifdef USE_SHADOWMAP\n directLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n DirectionalLight directionalLight;\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n getDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n #ifdef USE_SHADOWMAP\n directLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n #endif\n RE_Direct( directLight, geometry, material, reflectedLight );\n }\n#endif\n#if defined( RE_IndirectDiffuse )\n vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n #ifdef USE_LIGHTMAP\n vec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n #ifndef PHYSICALLY_CORRECT_LIGHTS\n lightMapIrradiance *= PI;\n #endif\n irradiance += lightMapIrradiance;\n #endif\n #if ( NUM_HEMI_LIGHTS > 0 )\n for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n }\n #endif\n #if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n irradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n #endif\n RE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n vec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n RE_IndirectSpecular( radiance, geometry, material, reflectedLight );\n#endif\n";
  14218. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_fragment.glsl
  14219. THREE.ShaderChunk[ 'logdepthbuf_fragment' ] = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  14220. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_fragment.glsl
  14221. THREE.ShaderChunk[ 'logdepthbuf_pars_fragment' ] = "#ifdef USE_LOGDEPTHBUF\n uniform float logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n#endif\n";
  14222. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_pars_vertex.glsl
  14223. THREE.ShaderChunk[ 'logdepthbuf_pars_vertex' ] = "#ifdef USE_LOGDEPTHBUF\n #ifdef USE_LOGDEPTHBUF_EXT\n varying float vFragDepth;\n #endif\n uniform float logDepthBufFC;\n#endif";
  14224. // File:src/renderers/shaders/ShaderChunk/logdepthbuf_vertex.glsl
  14225. THREE.ShaderChunk[ 'logdepthbuf_vertex' ] = "#ifdef USE_LOGDEPTHBUF\n gl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n #ifdef USE_LOGDEPTHBUF_EXT\n vFragDepth = 1.0 + gl_Position.w;\n #else\n gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n #endif\n#endif\n";
  14226. // File:src/renderers/shaders/ShaderChunk/map_fragment.glsl
  14227. THREE.ShaderChunk[ 'map_fragment' ] = "#ifdef USE_MAP\n vec4 texelColor = texture2D( map, vUv );\n texelColor = mapTexelToLinear( texelColor );\n diffuseColor *= texelColor;\n#endif\n";
  14228. // File:src/renderers/shaders/ShaderChunk/map_pars_fragment.glsl
  14229. THREE.ShaderChunk[ 'map_pars_fragment' ] = "#ifdef USE_MAP\n uniform sampler2D map;\n#endif\n";
  14230. // File:src/renderers/shaders/ShaderChunk/map_particle_fragment.glsl
  14231. THREE.ShaderChunk[ 'map_particle_fragment' ] = "#ifdef USE_MAP\n vec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n diffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  14232. // File:src/renderers/shaders/ShaderChunk/map_particle_pars_fragment.glsl
  14233. THREE.ShaderChunk[ 'map_particle_pars_fragment' ] = "#ifdef USE_MAP\n uniform vec4 offsetRepeat;\n uniform sampler2D map;\n#endif\n";
  14234. // File:src/renderers/shaders/ShaderChunk/metalnessmap_fragment.glsl
  14235. THREE.ShaderChunk[ 'metalnessmap_fragment' ] = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n vec4 texelMetalness = texture2D( metalnessMap, vUv );\n metalnessFactor *= texelMetalness.r;\n#endif\n";
  14236. // File:src/renderers/shaders/ShaderChunk/metalnessmap_pars_fragment.glsl
  14237. THREE.ShaderChunk[ 'metalnessmap_pars_fragment' ] = "#ifdef USE_METALNESSMAP\n uniform sampler2D metalnessMap;\n#endif";
  14238. // File:src/renderers/shaders/ShaderChunk/morphnormal_vertex.glsl
  14239. THREE.ShaderChunk[ 'morphnormal_vertex' ] = "#ifdef USE_MORPHNORMALS\n objectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n objectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n objectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n objectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  14240. // File:src/renderers/shaders/ShaderChunk/morphtarget_pars_vertex.glsl
  14241. THREE.ShaderChunk[ 'morphtarget_pars_vertex' ] = "#ifdef USE_MORPHTARGETS\n #ifndef USE_MORPHNORMALS\n uniform float morphTargetInfluences[ 8 ];\n #else\n uniform float morphTargetInfluences[ 4 ];\n #endif\n#endif";
  14242. // File:src/renderers/shaders/ShaderChunk/morphtarget_vertex.glsl
  14243. THREE.ShaderChunk[ 'morphtarget_vertex' ] = "#ifdef USE_MORPHTARGETS\n transformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n transformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n transformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n transformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n #ifndef USE_MORPHNORMALS\n transformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n transformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n transformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n transformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n #endif\n#endif\n";
  14244. // File:src/renderers/shaders/ShaderChunk/normal_fragment.glsl
  14245. THREE.ShaderChunk[ 'normal_fragment' ] = "#ifdef FLAT_SHADED\n vec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n vec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n vec3 normal = normalize( cross( fdx, fdy ) );\n#else\n vec3 normal = normalize( vNormal );\n #ifdef DOUBLE_SIDED\n normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );\n #endif\n#endif\n#ifdef USE_NORMALMAP\n normal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  14246. // File:src/renderers/shaders/ShaderChunk/normalmap_pars_fragment.glsl
  14247. THREE.ShaderChunk[ 'normalmap_pars_fragment' ] = "#ifdef USE_NORMALMAP\n uniform sampler2D normalMap;\n uniform vec2 normalScale;\n vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\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 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 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#endif\n";
  14248. // File:src/renderers/shaders/ShaderChunk/packing.glsl
  14249. THREE.ShaderChunk[ 'packing' ] = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nvec4 packDepthToRGBA( const in float value ) {\n const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );\n const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );\n vec4 res = mod( value * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );\n res -= res.xxyz * bit_mask;\n return res;\n}\nfloat unpackRGBAToDepth( const in vec4 rgba ) {\n const vec4 bitSh = vec4( 1.0 / ( 256.0 * 256.0 * 256.0 ), 1.0 / ( 256.0 * 256.0 ), 1.0 / 256.0, 1.0 );\n return dot( rgba, bitSh );\n}\nfloat viewZToOrthoDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat OrthoDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  14250. // File:src/renderers/shaders/ShaderChunk/premultiplied_alpha_fragment.glsl
  14251. THREE.ShaderChunk[ 'premultiplied_alpha_fragment' ] = "#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  14252. // File:src/renderers/shaders/ShaderChunk/project_vertex.glsl
  14253. THREE.ShaderChunk[ 'project_vertex' ] = "#ifdef USE_SKINNING\n vec4 mvPosition = modelViewMatrix * skinned;\n#else\n vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  14254. // File:src/renderers/shaders/ShaderChunk/roughnessmap_fragment.glsl
  14255. THREE.ShaderChunk[ 'roughnessmap_fragment' ] = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n vec4 texelRoughness = texture2D( roughnessMap, vUv );\n roughnessFactor *= texelRoughness.r;\n#endif\n";
  14256. // File:src/renderers/shaders/ShaderChunk/roughnessmap_pars_fragment.glsl
  14257. THREE.ShaderChunk[ 'roughnessmap_pars_fragment' ] = "#ifdef USE_ROUGHNESSMAP\n uniform sampler2D roughnessMap;\n#endif";
  14258. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_fragment.glsl
  14259. THREE.ShaderChunk[ 'shadowmap_pars_fragment' ] = "#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n #endif\n #if NUM_SPOT_LIGHTS > 0\n uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n #endif\n #if NUM_POINT_LIGHTS > 0\n uniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n #endif\n float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n }\n float texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n const vec2 offset = vec2( 0.0, 1.0 );\n vec2 texelSize = vec2( 1.0 ) / size;\n vec2 centroidUV = floor( uv * size + 0.5 ) / size;\n float lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n float lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n float rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n float rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n vec2 f = fract( uv * size + 0.5 );\n float a = mix( lb, lt, f.y );\n float b = mix( rb, rt, f.y );\n float c = mix( a, b, f.x );\n return c;\n }\n float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n shadowCoord.xyz /= shadowCoord.w;\n shadowCoord.z += shadowBias;\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 bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n bool frustumTest = all( frustumTestVec );\n if ( frustumTest ) {\n #if defined( SHADOWMAP_TYPE_PCF )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n return (\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 9.0 );\n #elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n float dx0 = - texelSize.x * shadowRadius;\n float dy0 = - texelSize.y * shadowRadius;\n float dx1 = + texelSize.x * shadowRadius;\n float dy1 = + texelSize.y * shadowRadius;\n return (\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n texture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n ) * ( 1.0 / 9.0 );\n #else\n return texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n #endif\n }\n return 1.0;\n }\n vec2 cubeToUV( vec3 v, float texelSizeY ) {\n vec3 absV = abs( v );\n float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n absV *= scaleToCube;\n v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n vec2 planar = v.xy;\n float almostATexel = 1.5 * texelSizeY;\n float almostOne = 1.0 - almostATexel;\n if ( absV.z >= almostOne ) {\n if ( v.z > 0.0 )\n planar.x = 4.0 - v.x;\n } else if ( absV.x >= almostOne ) {\n float signX = sign( v.x );\n planar.x = v.z * signX + 2.0 * signX;\n } else if ( absV.y >= almostOne ) {\n float signY = sign( v.y );\n planar.x = v.x + 2.0 * signY + 2.0;\n planar.y = v.z * signY - 2.0;\n }\n return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n }\n float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n vec3 lightToPosition = shadowCoord.xyz;\n vec3 bd3D = normalize( lightToPosition );\n float dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n #if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n return (\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n ) * ( 1.0 / 9.0 );\n #else\n return texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n #endif\n }\n#endif\n";
  14260. // File:src/renderers/shaders/ShaderChunk/shadowmap_pars_vertex.glsl
  14261. THREE.ShaderChunk[ 'shadowmap_pars_vertex' ] = "#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n #endif\n #if NUM_SPOT_LIGHTS > 0\n uniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n varying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n #endif\n #if NUM_POINT_LIGHTS > 0\n uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n varying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n #endif\n#endif\n";
  14262. // File:src/renderers/shaders/ShaderChunk/shadowmap_vertex.glsl
  14263. THREE.ShaderChunk[ 'shadowmap_vertex' ] = "#ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n }\n #endif\n #if NUM_SPOT_LIGHTS > 0\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n vSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n }\n #endif\n #if NUM_POINT_LIGHTS > 0\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n }\n #endif\n#endif\n";
  14264. // File:src/renderers/shaders/ShaderChunk/shadowmask_pars_fragment.glsl
  14265. THREE.ShaderChunk[ 'shadowmask_pars_fragment' ] = "float getShadowMask() {\n float shadow = 1.0;\n #ifdef USE_SHADOWMAP\n #if NUM_DIR_LIGHTS > 0\n DirectionalLight directionalLight;\n for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n directionalLight = directionalLights[ i ];\n shadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n }\n #endif\n #if NUM_SPOT_LIGHTS > 0\n SpotLight spotLight;\n for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n spotLight = spotLights[ i ];\n shadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n }\n #endif\n #if NUM_POINT_LIGHTS > 0\n PointLight pointLight;\n for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n pointLight = pointLights[ i ];\n shadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n }\n #endif\n #endif\n return shadow;\n}\n";
  14266. // File:src/renderers/shaders/ShaderChunk/skinbase_vertex.glsl
  14267. THREE.ShaderChunk[ 'skinbase_vertex' ] = "#ifdef USE_SKINNING\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#endif";
  14268. // File:src/renderers/shaders/ShaderChunk/skinning_pars_vertex.glsl
  14269. THREE.ShaderChunk[ 'skinning_pars_vertex' ] = "#ifdef USE_SKINNING\n uniform mat4 bindMatrix;\n uniform mat4 bindMatrixInverse;\n #ifdef BONE_TEXTURE\n uniform sampler2D boneTexture;\n uniform int boneTextureWidth;\n uniform int boneTextureHeight;\n mat4 getBoneMatrix( const in float i ) {\n float j = i * 4.0;\n float x = mod( j, float( boneTextureWidth ) );\n float y = floor( j / float( boneTextureWidth ) );\n float dx = 1.0 / float( boneTextureWidth );\n float dy = 1.0 / float( boneTextureHeight );\n y = dy * ( y + 0.5 );\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 mat4 bone = mat4( v1, v2, v3, v4 );\n return bone;\n }\n #else\n uniform mat4 boneMatrices[ MAX_BONES ];\n mat4 getBoneMatrix( const in float i ) {\n mat4 bone = boneMatrices[ int(i) ];\n return bone;\n }\n #endif\n#endif\n";
  14270. // File:src/renderers/shaders/ShaderChunk/skinning_vertex.glsl
  14271. THREE.ShaderChunk[ 'skinning_vertex' ] = "#ifdef USE_SKINNING\n vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\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#endif\n";
  14272. // File:src/renderers/shaders/ShaderChunk/skinnormal_vertex.glsl
  14273. THREE.ShaderChunk[ 'skinnormal_vertex' ] = "#ifdef USE_SKINNING\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 objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  14274. // File:src/renderers/shaders/ShaderChunk/specularmap_fragment.glsl
  14275. THREE.ShaderChunk[ 'specularmap_fragment' ] = "float specularStrength;\n#ifdef USE_SPECULARMAP\n vec4 texelSpecular = texture2D( specularMap, vUv );\n specularStrength = texelSpecular.r;\n#else\n specularStrength = 1.0;\n#endif";
  14276. // File:src/renderers/shaders/ShaderChunk/specularmap_pars_fragment.glsl
  14277. THREE.ShaderChunk[ 'specularmap_pars_fragment' ] = "#ifdef USE_SPECULARMAP\n uniform sampler2D specularMap;\n#endif";
  14278. // File:src/renderers/shaders/ShaderChunk/tonemapping_fragment.glsl
  14279. THREE.ShaderChunk[ 'tonemapping_fragment' ] = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  14280. // File:src/renderers/shaders/ShaderChunk/tonemapping_pars_fragment.glsl
  14281. THREE.ShaderChunk[ 'tonemapping_pars_fragment' ] = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  14282. // File:src/renderers/shaders/ShaderChunk/uv2_pars_fragment.glsl
  14283. THREE.ShaderChunk[ 'uv2_pars_fragment' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n varying vec2 vUv2;\n#endif";
  14284. // File:src/renderers/shaders/ShaderChunk/uv2_pars_vertex.glsl
  14285. THREE.ShaderChunk[ 'uv2_pars_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n attribute vec2 uv2;\n varying vec2 vUv2;\n#endif";
  14286. // File:src/renderers/shaders/ShaderChunk/uv2_vertex.glsl
  14287. THREE.ShaderChunk[ 'uv2_vertex' ] = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n vUv2 = uv2;\n#endif";
  14288. // File:src/renderers/shaders/ShaderChunk/uv_pars_fragment.glsl
  14289. THREE.ShaderChunk[ 'uv_pars_fragment' ] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n#endif";
  14290. // File:src/renderers/shaders/ShaderChunk/uv_pars_vertex.glsl
  14291. THREE.ShaderChunk[ 'uv_pars_vertex' ] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n varying vec2 vUv;\n uniform vec4 offsetRepeat;\n#endif\n";
  14292. // File:src/renderers/shaders/ShaderChunk/uv_vertex.glsl
  14293. THREE.ShaderChunk[ 'uv_vertex' ] = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n vUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  14294. // File:src/renderers/shaders/ShaderChunk/worldpos_vertex.glsl
  14295. THREE.ShaderChunk[ 'worldpos_vertex' ] = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n #ifdef USE_SKINNING\n vec4 worldPosition = modelMatrix * skinned;\n #else\n vec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n #endif\n#endif\n";
  14296. // File:src/renderers/shaders/UniformsUtils.js
  14297. /**
  14298. * Uniform Utilities
  14299. */
  14300. THREE.UniformsUtils = {
  14301. merge: function ( uniforms ) {
  14302. var merged = {};
  14303. for ( var u = 0; u < uniforms.length; u ++ ) {
  14304. var tmp = this.clone( uniforms[ u ] );
  14305. for ( var p in tmp ) {
  14306. merged[ p ] = tmp[ p ];
  14307. }
  14308. }
  14309. return merged;
  14310. },
  14311. clone: function ( uniforms_src ) {
  14312. var uniforms_dst = {};
  14313. for ( var u in uniforms_src ) {
  14314. uniforms_dst[ u ] = {};
  14315. for ( var p in uniforms_src[ u ] ) {
  14316. var parameter_src = uniforms_src[ u ][ p ];
  14317. if ( parameter_src instanceof THREE.Color ||
  14318. parameter_src instanceof THREE.Vector2 ||
  14319. parameter_src instanceof THREE.Vector3 ||
  14320. parameter_src instanceof THREE.Vector4 ||
  14321. parameter_src instanceof THREE.Matrix3 ||
  14322. parameter_src instanceof THREE.Matrix4 ||
  14323. parameter_src instanceof THREE.Texture ) {
  14324. uniforms_dst[ u ][ p ] = parameter_src.clone();
  14325. } else if ( Array.isArray( parameter_src ) ) {
  14326. uniforms_dst[ u ][ p ] = parameter_src.slice();
  14327. } else {
  14328. uniforms_dst[ u ][ p ] = parameter_src;
  14329. }
  14330. }
  14331. }
  14332. return uniforms_dst;
  14333. }
  14334. };
  14335. // File:src/renderers/shaders/UniformsLib.js
  14336. /**
  14337. * Uniforms library for shared webgl shaders
  14338. */
  14339. THREE.UniformsLib = {
  14340. common: {
  14341. "diffuse": { type: "c", value: new THREE.Color( 0xeeeeee ) },
  14342. "opacity": { type: "1f", value: 1.0 },
  14343. "map": { type: "t", value: null },
  14344. "offsetRepeat": { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  14345. "specularMap": { type: "t", value: null },
  14346. "alphaMap": { type: "t", value: null },
  14347. "envMap": { type: "t", value: null },
  14348. "flipEnvMap": { type: "1f", value: - 1 },
  14349. "reflectivity": { type: "1f", value: 1.0 },
  14350. "refractionRatio": { type: "1f", value: 0.98 }
  14351. },
  14352. aomap: {
  14353. "aoMap": { type: "t", value: null },
  14354. "aoMapIntensity": { type: "1f", value: 1 }
  14355. },
  14356. lightmap: {
  14357. "lightMap": { type: "t", value: null },
  14358. "lightMapIntensity": { type: "1f", value: 1 }
  14359. },
  14360. emissivemap: {
  14361. "emissiveMap": { type: "t", value: null }
  14362. },
  14363. bumpmap: {
  14364. "bumpMap": { type: "t", value: null },
  14365. "bumpScale": { type: "1f", value: 1 }
  14366. },
  14367. normalmap: {
  14368. "normalMap": { type: "t", value: null },
  14369. "normalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  14370. },
  14371. displacementmap: {
  14372. "displacementMap": { type: "t", value: null },
  14373. "displacementScale": { type: "1f", value: 1 },
  14374. "displacementBias": { type: "1f", value: 0 }
  14375. },
  14376. roughnessmap: {
  14377. "roughnessMap": { type: "t", value: null }
  14378. },
  14379. metalnessmap: {
  14380. "metalnessMap": { type: "t", value: null }
  14381. },
  14382. fog: {
  14383. "fogDensity": { type: "1f", value: 0.00025 },
  14384. "fogNear": { type: "1f", value: 1 },
  14385. "fogFar": { type: "1f", value: 2000 },
  14386. "fogColor": { type: "c", value: new THREE.Color( 0xffffff ) }
  14387. },
  14388. lights: {
  14389. "ambientLightColor": { type: "3fv", value: [] },
  14390. "directionalLights": { type: "sa", value: [], properties: {
  14391. "direction": { type: "v3" },
  14392. "color": { type: "c" },
  14393. "shadow": { type: "1i" },
  14394. "shadowBias": { type: "1f" },
  14395. "shadowRadius": { type: "1f" },
  14396. "shadowMapSize": { type: "v2" }
  14397. } },
  14398. "directionalShadowMap": { type: "tv", value: [] },
  14399. "directionalShadowMatrix": { type: "m4v", value: [] },
  14400. "spotLights": { type: "sa", value: [], properties: {
  14401. "color": { type: "c" },
  14402. "position": { type: "v3" },
  14403. "direction": { type: "v3" },
  14404. "distance": { type: "1f" },
  14405. "coneCos": { type: "1f" },
  14406. "penumbraCos": { type: "1f" },
  14407. "decay": { type: "1f" },
  14408. "shadow": { type: "1i" },
  14409. "shadowBias": { type: "1f" },
  14410. "shadowRadius": { type: "1f" },
  14411. "shadowMapSize": { type: "v2" }
  14412. } },
  14413. "spotShadowMap": { type: "tv", value: [] },
  14414. "spotShadowMatrix": { type: "m4v", value: [] },
  14415. "pointLights": { type: "sa", value: [], properties: {
  14416. "color": { type: "c" },
  14417. "position": { type: "v3" },
  14418. "decay": { type: "1f" },
  14419. "distance": { type: "1f" },
  14420. "shadow": { type: "1i" },
  14421. "shadowBias": { type: "1f" },
  14422. "shadowRadius": { type: "1f" },
  14423. "shadowMapSize": { type: "v2" }
  14424. } },
  14425. "pointShadowMap": { type: "tv", value: [] },
  14426. "pointShadowMatrix": { type: "m4v", value: [] },
  14427. "hemisphereLights": { type: "sa", value: [], properties: {
  14428. "direction": { type: "v3" },
  14429. "skyColor": { type: "c" },
  14430. "groundColor": { type: "c" }
  14431. } }
  14432. },
  14433. points: {
  14434. "diffuse": { type: "c", value: new THREE.Color( 0xeeeeee ) },
  14435. "opacity": { type: "1f", value: 1.0 },
  14436. "size": { type: "1f", value: 1.0 },
  14437. "scale": { type: "1f", value: 1.0 },
  14438. "map": { type: "t", value: null },
  14439. "offsetRepeat": { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) }
  14440. }
  14441. };
  14442. // File:src/renderers/shaders/ShaderLib/cube_frag.glsl
  14443. THREE.ShaderChunk[ 'cube_frag' ] = "uniform samplerCube tCube;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n #include <logdepthbuf_fragment>\n}\n";
  14444. // File:src/renderers/shaders/ShaderLib/cube_vert.glsl
  14445. THREE.ShaderChunk[ 'cube_vert' ] = "varying vec3 vWorldPosition;\n#include <common>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n vWorldPosition = transformDirection( position, modelMatrix );\n #include <begin_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n}\n";
  14446. // File:src/renderers/shaders/ShaderLib/depth_frag.glsl
  14447. THREE.ShaderChunk[ 'depth_frag' ] = "#if DEPTH_PACKING == 3200\n uniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n vec4 diffuseColor = vec4( 1.0 );\n #if DEPTH_PACKING == 3200\n diffuseColor.a = opacity;\n #endif\n #include <map_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <logdepthbuf_fragment>\n #if DEPTH_PACKING == 3200\n gl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n #elif DEPTH_PACKING == 3201\n gl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n #endif\n}\n";
  14448. // File:src/renderers/shaders/ShaderLib/depth_vert.glsl
  14449. THREE.ShaderChunk[ 'depth_vert' ] = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <skinbase_vertex>\n #include <begin_vertex>\n #include <displacementmap_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n}\n";
  14450. // File:src/renderers/shaders/ShaderLib/distanceRGBA_frag.glsl
  14451. THREE.ShaderChunk[ 'distanceRGBA_frag' ] = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n #include <clipping_planes_fragment>\n gl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  14452. // File:src/renderers/shaders/ShaderLib/distanceRGBA_vert.glsl
  14453. THREE.ShaderChunk[ 'distanceRGBA_vert' ] = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <skinbase_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <worldpos_vertex>\n #include <clipping_planes_vertex>\n vWorldPosition = worldPosition;\n}\n";
  14454. // File:src/renderers/shaders/ShaderLib/equirect_frag.glsl
  14455. THREE.ShaderChunk[ 'equirect_frag' ] = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n vec3 direction = normalize( vWorldPosition );\n vec2 sampleUV;\n sampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n sampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n gl_FragColor = texture2D( tEquirect, sampleUV );\n #include <logdepthbuf_fragment>\n}\n";
  14456. // File:src/renderers/shaders/ShaderLib/equirect_vert.glsl
  14457. THREE.ShaderChunk[ 'equirect_vert' ] = "varying vec3 vWorldPosition;\n#include <common>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n vWorldPosition = transformDirection( position, modelMatrix );\n #include <begin_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n}\n";
  14458. // File:src/renderers/shaders/ShaderLib/linedashed_frag.glsl
  14459. THREE.ShaderChunk[ 'linedashed_frag' ] = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n if ( mod( vLineDistance, totalSize ) > dashSize ) {\n discard;\n }\n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <logdepthbuf_fragment>\n #include <color_fragment>\n outgoingLight = diffuseColor.rgb;\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}\n";
  14460. // File:src/renderers/shaders/ShaderLib/linedashed_vert.glsl
  14461. THREE.ShaderChunk[ 'linedashed_vert' ] = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <color_vertex>\n vLineDistance = scale * lineDistance;\n vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n gl_Position = projectionMatrix * mvPosition;\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n}\n";
  14462. // File:src/renderers/shaders/ShaderLib/meshbasic_frag.glsl
  14463. THREE.ShaderChunk[ 'meshbasic_frag' ] = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <specularmap_fragment>\n ReflectedLight reflectedLight;\n reflectedLight.directDiffuse = vec3( 0.0 );\n reflectedLight.directSpecular = vec3( 0.0 );\n reflectedLight.indirectDiffuse = diffuseColor.rgb;\n reflectedLight.indirectSpecular = vec3( 0.0 );\n #include <aomap_fragment>\n vec3 outgoingLight = reflectedLight.indirectDiffuse;\n #include <envmap_fragment>\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}\n";
  14464. // File:src/renderers/shaders/ShaderLib/meshbasic_vert.glsl
  14465. THREE.ShaderChunk[ 'meshbasic_vert' ] = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <uv2_vertex>\n #include <color_vertex>\n #include <skinbase_vertex>\n #ifdef USE_ENVMAP\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #endif\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <worldpos_vertex>\n #include <clipping_planes_vertex>\n #include <envmap_vertex>\n}\n";
  14466. // File:src/renderers/shaders/ShaderLib/meshlambert_frag.glsl
  14467. THREE.ShaderChunk[ 'meshlambert_frag' ] = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n varying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <specularmap_fragment>\n #include <emissivemap_fragment>\n reflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n #include <lightmap_fragment>\n reflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n #ifdef DOUBLE_SIDED\n reflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n #else\n reflectedLight.directDiffuse = vLightFront;\n #endif\n reflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n #include <aomap_fragment>\n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n #include <envmap_fragment>\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}\n";
  14468. // File:src/renderers/shaders/ShaderLib/meshlambert_vert.glsl
  14469. THREE.ShaderChunk[ 'meshlambert_vert' ] = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n varying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <uv2_vertex>\n #include <color_vertex>\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n #include <worldpos_vertex>\n #include <envmap_vertex>\n #include <lights_lambert_vertex>\n #include <shadowmap_vertex>\n}\n";
  14470. // File:src/renderers/shaders/ShaderLib/meshphong_frag.glsl
  14471. THREE.ShaderChunk[ 'meshphong_frag' ] = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <specularmap_fragment>\n #include <normal_fragment>\n #include <emissivemap_fragment>\n #include <lights_phong_fragment>\n #include <lights_template>\n #include <aomap_fragment>\n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n #include <envmap_fragment>\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}\n";
  14472. // File:src/renderers/shaders/ShaderLib/meshphong_vert.glsl
  14473. THREE.ShaderChunk[ 'meshphong_vert' ] = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <uv2_vertex>\n #include <color_vertex>\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n#endif\n #include <begin_vertex>\n #include <displacementmap_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n vViewPosition = - mvPosition.xyz;\n #include <worldpos_vertex>\n #include <envmap_vertex>\n #include <shadowmap_vertex>\n}\n";
  14474. // File:src/renderers/shaders/ShaderLib/meshphysical_frag.glsl
  14475. THREE.ShaderChunk[ 'meshphysical_frag' ] = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\nuniform float envMapIntensity;\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n vec4 diffuseColor = vec4( diffuse, opacity );\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n #include <logdepthbuf_fragment>\n #include <map_fragment>\n #include <color_fragment>\n #include <alphamap_fragment>\n #include <alphatest_fragment>\n #include <specularmap_fragment>\n #include <roughnessmap_fragment>\n #include <metalnessmap_fragment>\n #include <normal_fragment>\n #include <emissivemap_fragment>\n #include <lights_physical_fragment>\n #include <lights_template>\n #include <aomap_fragment>\n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}\n";
  14476. // File:src/renderers/shaders/ShaderLib/meshphysical_vert.glsl
  14477. THREE.ShaderChunk[ 'meshphysical_vert' ] = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n varying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <uv_vertex>\n #include <uv2_vertex>\n #include <color_vertex>\n #include <beginnormal_vertex>\n #include <morphnormal_vertex>\n #include <skinbase_vertex>\n #include <skinnormal_vertex>\n #include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n vNormal = normalize( transformedNormal );\n#endif\n #include <begin_vertex>\n #include <displacementmap_vertex>\n #include <morphtarget_vertex>\n #include <skinning_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n vViewPosition = - mvPosition.xyz;\n #include <worldpos_vertex>\n #include <shadowmap_vertex>\n}\n";
  14478. // File:src/renderers/shaders/ShaderLib/normal_frag.glsl
  14479. THREE.ShaderChunk[ 'normal_frag' ] = "uniform float opacity;\nvarying vec3 vNormal;\n#include <common>\n#include <packing>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n gl_FragColor = vec4( packNormalToRGB( vNormal ), opacity );\n #include <logdepthbuf_fragment>\n}\n";
  14480. // File:src/renderers/shaders/ShaderLib/normal_vert.glsl
  14481. THREE.ShaderChunk[ 'normal_vert' ] = "varying vec3 vNormal;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n vNormal = normalize( normalMatrix * normal );\n #include <begin_vertex>\n #include <morphtarget_vertex>\n #include <project_vertex>\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n}\n";
  14482. // File:src/renderers/shaders/ShaderLib/points_frag.glsl
  14483. THREE.ShaderChunk[ 'points_frag' ] = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n #include <clipping_planes_fragment>\n vec3 outgoingLight = vec3( 0.0 );\n vec4 diffuseColor = vec4( diffuse, opacity );\n #include <logdepthbuf_fragment>\n #include <map_particle_fragment>\n #include <color_fragment>\n #include <alphatest_fragment>\n outgoingLight = diffuseColor.rgb;\n gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n #include <premultiplied_alpha_fragment>\n #include <tonemapping_fragment>\n #include <encodings_fragment>\n #include <fog_fragment>\n}\n";
  14484. // File:src/renderers/shaders/ShaderLib/points_vert.glsl
  14485. THREE.ShaderChunk[ 'points_vert' ] = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n #include <color_vertex>\n #include <begin_vertex>\n #include <project_vertex>\n #ifdef USE_SIZEATTENUATION\n gl_PointSize = size * ( scale / - mvPosition.z );\n #else\n gl_PointSize = size;\n #endif\n #include <logdepthbuf_vertex>\n #include <clipping_planes_vertex>\n #include <worldpos_vertex>\n #include <shadowmap_vertex>\n}\n";
  14486. // File:src/renderers/shaders/ShaderLib.js
  14487. /**
  14488. * Webgl Shader Library for three.js
  14489. *
  14490. * @author alteredq / http://alteredqualia.com/
  14491. * @author mrdoob / http://mrdoob.com/
  14492. * @author mikael emtinger / http://gomo.se/
  14493. */
  14494. THREE.ShaderLib = {
  14495. 'basic': {
  14496. uniforms: THREE.UniformsUtils.merge( [
  14497. THREE.UniformsLib[ 'common' ],
  14498. THREE.UniformsLib[ 'aomap' ],
  14499. THREE.UniformsLib[ 'fog' ]
  14500. ] ),
  14501. vertexShader: THREE.ShaderChunk[ 'meshbasic_vert' ],
  14502. fragmentShader: THREE.ShaderChunk[ 'meshbasic_frag' ]
  14503. },
  14504. 'lambert': {
  14505. uniforms: THREE.UniformsUtils.merge( [
  14506. THREE.UniformsLib[ 'common' ],
  14507. THREE.UniformsLib[ 'aomap' ],
  14508. THREE.UniformsLib[ 'lightmap' ],
  14509. THREE.UniformsLib[ 'emissivemap' ],
  14510. THREE.UniformsLib[ 'fog' ],
  14511. THREE.UniformsLib[ 'lights' ],
  14512. {
  14513. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) }
  14514. }
  14515. ] ),
  14516. vertexShader: THREE.ShaderChunk[ 'meshlambert_vert' ],
  14517. fragmentShader: THREE.ShaderChunk[ 'meshlambert_frag' ]
  14518. },
  14519. 'phong': {
  14520. uniforms: THREE.UniformsUtils.merge( [
  14521. THREE.UniformsLib[ 'common' ],
  14522. THREE.UniformsLib[ 'aomap' ],
  14523. THREE.UniformsLib[ 'lightmap' ],
  14524. THREE.UniformsLib[ 'emissivemap' ],
  14525. THREE.UniformsLib[ 'bumpmap' ],
  14526. THREE.UniformsLib[ 'normalmap' ],
  14527. THREE.UniformsLib[ 'displacementmap' ],
  14528. THREE.UniformsLib[ 'fog' ],
  14529. THREE.UniformsLib[ 'lights' ],
  14530. {
  14531. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14532. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  14533. "shininess": { type: "1f", value: 30 }
  14534. }
  14535. ] ),
  14536. vertexShader: THREE.ShaderChunk[ 'meshphong_vert' ],
  14537. fragmentShader: THREE.ShaderChunk[ 'meshphong_frag' ]
  14538. },
  14539. 'standard': {
  14540. uniforms: THREE.UniformsUtils.merge( [
  14541. THREE.UniformsLib[ 'common' ],
  14542. THREE.UniformsLib[ 'aomap' ],
  14543. THREE.UniformsLib[ 'lightmap' ],
  14544. THREE.UniformsLib[ 'emissivemap' ],
  14545. THREE.UniformsLib[ 'bumpmap' ],
  14546. THREE.UniformsLib[ 'normalmap' ],
  14547. THREE.UniformsLib[ 'displacementmap' ],
  14548. THREE.UniformsLib[ 'roughnessmap' ],
  14549. THREE.UniformsLib[ 'metalnessmap' ],
  14550. THREE.UniformsLib[ 'fog' ],
  14551. THREE.UniformsLib[ 'lights' ],
  14552. {
  14553. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  14554. "roughness": { type: "1f", value: 0.5 },
  14555. "metalness": { type: "1f", value: 0 },
  14556. "envMapIntensity" : { type: "1f", value: 1 } // temporary
  14557. }
  14558. ] ),
  14559. vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ],
  14560. fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ]
  14561. },
  14562. 'points': {
  14563. uniforms: THREE.UniformsUtils.merge( [
  14564. THREE.UniformsLib[ 'points' ],
  14565. THREE.UniformsLib[ 'fog' ]
  14566. ] ),
  14567. vertexShader: THREE.ShaderChunk[ 'points_vert' ],
  14568. fragmentShader: THREE.ShaderChunk[ 'points_frag' ]
  14569. },
  14570. 'dashed': {
  14571. uniforms: THREE.UniformsUtils.merge( [
  14572. THREE.UniformsLib[ 'common' ],
  14573. THREE.UniformsLib[ 'fog' ],
  14574. {
  14575. "scale" : { type: "1f", value: 1 },
  14576. "dashSize" : { type: "1f", value: 1 },
  14577. "totalSize": { type: "1f", value: 2 }
  14578. }
  14579. ] ),
  14580. vertexShader: THREE.ShaderChunk[ 'linedashed_vert' ],
  14581. fragmentShader: THREE.ShaderChunk[ 'linedashed_frag' ]
  14582. },
  14583. 'depth': {
  14584. uniforms: THREE.UniformsUtils.merge( [
  14585. THREE.UniformsLib[ 'common' ],
  14586. THREE.UniformsLib[ 'displacementmap' ]
  14587. ] ),
  14588. vertexShader: THREE.ShaderChunk[ 'depth_vert' ],
  14589. fragmentShader: THREE.ShaderChunk[ 'depth_frag' ]
  14590. },
  14591. 'normal': {
  14592. uniforms: {
  14593. "opacity" : { type: "1f", value: 1.0 }
  14594. },
  14595. vertexShader: THREE.ShaderChunk[ 'normal_vert' ],
  14596. fragmentShader: THREE.ShaderChunk[ 'normal_frag' ]
  14597. },
  14598. /* -------------------------------------------------------------------------
  14599. // Cube map shader
  14600. ------------------------------------------------------------------------- */
  14601. 'cube': {
  14602. uniforms: {
  14603. "tCube": { type: "t", value: null },
  14604. "tFlip": { type: "1f", value: - 1 }
  14605. },
  14606. vertexShader: THREE.ShaderChunk[ 'cube_vert' ],
  14607. fragmentShader: THREE.ShaderChunk[ 'cube_frag' ]
  14608. },
  14609. /* -------------------------------------------------------------------------
  14610. // Cube map shader
  14611. ------------------------------------------------------------------------- */
  14612. 'equirect': {
  14613. uniforms: {
  14614. "tEquirect": { type: "t", value: null },
  14615. "tFlip": { type: "1f", value: - 1 }
  14616. },
  14617. vertexShader: THREE.ShaderChunk[ 'equirect_vert' ],
  14618. fragmentShader: THREE.ShaderChunk[ 'equirect_frag' ]
  14619. },
  14620. 'distanceRGBA': {
  14621. uniforms: {
  14622. "lightPos": { type: "v3", value: new THREE.Vector3() }
  14623. },
  14624. vertexShader: THREE.ShaderChunk[ 'distanceRGBA_vert' ],
  14625. fragmentShader: THREE.ShaderChunk[ 'distanceRGBA_frag' ]
  14626. }
  14627. };
  14628. THREE.ShaderLib[ 'physical' ] = {
  14629. uniforms: THREE.UniformsUtils.merge( [
  14630. THREE.ShaderLib[ 'standard' ].uniforms,
  14631. {
  14632. // future
  14633. }
  14634. ] ),
  14635. vertexShader: THREE.ShaderChunk[ 'meshphysical_vert' ],
  14636. fragmentShader: THREE.ShaderChunk[ 'meshphysical_frag' ]
  14637. };
  14638. // File:src/renderers/WebGLRenderer.js
  14639. /**
  14640. * @author supereggbert / http://www.paulbrunt.co.uk/
  14641. * @author mrdoob / http://mrdoob.com/
  14642. * @author alteredq / http://alteredqualia.com/
  14643. * @author szimek / https://github.com/szimek/
  14644. * @author tschw
  14645. */
  14646. THREE.WebGLRenderer = function ( parameters ) {
  14647. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  14648. parameters = parameters || {};
  14649. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  14650. _context = parameters.context !== undefined ? parameters.context : null,
  14651. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  14652. _depth = parameters.depth !== undefined ? parameters.depth : true,
  14653. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  14654. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  14655. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  14656. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  14657. var lights = [];
  14658. var opaqueObjects = [];
  14659. var opaqueObjectsLastIndex = - 1;
  14660. var transparentObjects = [];
  14661. var transparentObjectsLastIndex = - 1;
  14662. var morphInfluences = new Float32Array( 8 );
  14663. var sprites = [];
  14664. var lensFlares = [];
  14665. // public properties
  14666. this.domElement = _canvas;
  14667. this.context = null;
  14668. // clearing
  14669. this.autoClear = true;
  14670. this.autoClearColor = true;
  14671. this.autoClearDepth = true;
  14672. this.autoClearStencil = true;
  14673. // scene graph
  14674. this.sortObjects = true;
  14675. // user-defined clipping
  14676. this.clippingPlanes = [];
  14677. this.localClippingEnabled = false;
  14678. // physically based shading
  14679. this.gammaFactor = 2.0; // for backwards compatibility
  14680. this.gammaInput = false;
  14681. this.gammaOutput = false;
  14682. // physical lights
  14683. this.physicallyCorrectLights = false;
  14684. // tone mapping
  14685. this.toneMapping = THREE.LinearToneMapping;
  14686. this.toneMappingExposure = 1.0;
  14687. this.toneMappingWhitePoint = 1.0;
  14688. // morphs
  14689. this.maxMorphTargets = 8;
  14690. this.maxMorphNormals = 4;
  14691. // flags
  14692. this.autoScaleCubemaps = true;
  14693. // internal properties
  14694. var _this = this,
  14695. // internal state cache
  14696. _currentProgram = null,
  14697. _currentRenderTarget = null,
  14698. _currentFramebuffer = null,
  14699. _currentMaterialId = - 1,
  14700. _currentGeometryProgram = '',
  14701. _currentCamera = null,
  14702. _currentScissor = new THREE.Vector4(),
  14703. _currentScissorTest = null,
  14704. _currentViewport = new THREE.Vector4(),
  14705. //
  14706. _usedTextureUnits = 0,
  14707. //
  14708. _clearColor = new THREE.Color( 0x000000 ),
  14709. _clearAlpha = 0,
  14710. _width = _canvas.width,
  14711. _height = _canvas.height,
  14712. _pixelRatio = 1,
  14713. _scissor = new THREE.Vector4( 0, 0, _width, _height ),
  14714. _scissorTest = false,
  14715. _viewport = new THREE.Vector4( 0, 0, _width, _height ),
  14716. // frustum
  14717. _frustum = new THREE.Frustum(),
  14718. // clipping
  14719. _clippingEnabled = false,
  14720. _localClippingEnabled = false,
  14721. _clipRenderingShadows = false,
  14722. _numClippingPlanes = 0,
  14723. _clippingPlanesUniform = {
  14724. type: '4fv', value: null, needsUpdate: false },
  14725. _globalClippingState = null,
  14726. _numGlobalClippingPlanes = 0,
  14727. _matrix3 = new THREE.Matrix3(),
  14728. _sphere = new THREE.Sphere(),
  14729. _plane = new THREE.Plane(),
  14730. // camera matrices cache
  14731. _projScreenMatrix = new THREE.Matrix4(),
  14732. _vector3 = new THREE.Vector3(),
  14733. // light arrays cache
  14734. _lights = {
  14735. hash: '',
  14736. ambient: [ 0, 0, 0 ],
  14737. directional: [],
  14738. directionalShadowMap: [],
  14739. directionalShadowMatrix: [],
  14740. spot: [],
  14741. spotShadowMap: [],
  14742. spotShadowMatrix: [],
  14743. point: [],
  14744. pointShadowMap: [],
  14745. pointShadowMatrix: [],
  14746. hemi: [],
  14747. shadows: []
  14748. },
  14749. // info
  14750. _infoMemory = {
  14751. geometries: 0,
  14752. textures: 0
  14753. },
  14754. _infoRender = {
  14755. calls: 0,
  14756. vertices: 0,
  14757. faces: 0,
  14758. points: 0
  14759. };
  14760. this.info = {
  14761. render: _infoRender,
  14762. memory: _infoMemory,
  14763. programs: null
  14764. };
  14765. // initialize
  14766. var _gl;
  14767. try {
  14768. var attributes = {
  14769. alpha: _alpha,
  14770. depth: _depth,
  14771. stencil: _stencil,
  14772. antialias: _antialias,
  14773. premultipliedAlpha: _premultipliedAlpha,
  14774. preserveDrawingBuffer: _preserveDrawingBuffer
  14775. };
  14776. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  14777. if ( _gl === null ) {
  14778. if ( _canvas.getContext( 'webgl' ) !== null ) {
  14779. throw 'Error creating WebGL context with your selected attributes.';
  14780. } else {
  14781. throw 'Error creating WebGL context.';
  14782. }
  14783. }
  14784. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  14785. if ( _gl.getShaderPrecisionFormat === undefined ) {
  14786. _gl.getShaderPrecisionFormat = function () {
  14787. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  14788. };
  14789. }
  14790. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  14791. } catch ( error ) {
  14792. console.error( 'THREE.WebGLRenderer: ' + error );
  14793. }
  14794. var _isWebGL2 = (typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext);
  14795. var extensions = new THREE.WebGLExtensions( _gl );
  14796. extensions.get( 'WEBGL_depth_texture' );
  14797. extensions.get( 'OES_texture_float' );
  14798. extensions.get( 'OES_texture_float_linear' );
  14799. extensions.get( 'OES_texture_half_float' );
  14800. extensions.get( 'OES_texture_half_float_linear' );
  14801. extensions.get( 'OES_standard_derivatives' );
  14802. extensions.get( 'ANGLE_instanced_arrays' );
  14803. if ( extensions.get( 'OES_element_index_uint' ) ) {
  14804. THREE.BufferGeometry.MaxIndex = 4294967296;
  14805. }
  14806. var capabilities = new THREE.WebGLCapabilities( _gl, extensions, parameters );
  14807. var state = new THREE.WebGLState( _gl, extensions, paramThreeToGL );
  14808. var properties = new THREE.WebGLProperties();
  14809. var objects = new THREE.WebGLObjects( _gl, properties, this.info );
  14810. var programCache = new THREE.WebGLPrograms( this, capabilities );
  14811. var lightCache = new THREE.WebGLLights();
  14812. this.info.programs = programCache.programs;
  14813. var bufferRenderer = new THREE.WebGLBufferRenderer( _gl, extensions, _infoRender );
  14814. var indexedBufferRenderer = new THREE.WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  14815. //
  14816. function getTargetPixelRatio() {
  14817. return _currentRenderTarget === null ? _pixelRatio : 1;
  14818. }
  14819. function glClearColor( r, g, b, a ) {
  14820. if ( _premultipliedAlpha === true ) {
  14821. r *= a; g *= a; b *= a;
  14822. }
  14823. state.clearColor( r, g, b, a );
  14824. }
  14825. function setDefaultGLState() {
  14826. state.init();
  14827. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  14828. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  14829. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14830. }
  14831. function resetGLState() {
  14832. _currentProgram = null;
  14833. _currentCamera = null;
  14834. _currentGeometryProgram = '';
  14835. _currentMaterialId = - 1;
  14836. state.reset();
  14837. }
  14838. setDefaultGLState();
  14839. this.context = _gl;
  14840. this.capabilities = capabilities;
  14841. this.extensions = extensions;
  14842. this.properties = properties;
  14843. this.state = state;
  14844. // shadow map
  14845. var shadowMap = new THREE.WebGLShadowMap( this, _lights, objects );
  14846. this.shadowMap = shadowMap;
  14847. // Plugins
  14848. var spritePlugin = new THREE.SpritePlugin( this, sprites );
  14849. var lensFlarePlugin = new THREE.LensFlarePlugin( this, lensFlares );
  14850. // API
  14851. this.getContext = function () {
  14852. return _gl;
  14853. };
  14854. this.getContextAttributes = function () {
  14855. return _gl.getContextAttributes();
  14856. };
  14857. this.forceContextLoss = function () {
  14858. extensions.get( 'WEBGL_lose_context' ).loseContext();
  14859. };
  14860. this.getMaxAnisotropy = ( function () {
  14861. var value;
  14862. return function getMaxAnisotropy() {
  14863. if ( value !== undefined ) return value;
  14864. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14865. if ( extension !== null ) {
  14866. value = _gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  14867. } else {
  14868. value = 0;
  14869. }
  14870. return value;
  14871. };
  14872. } )();
  14873. this.getPrecision = function () {
  14874. return capabilities.precision;
  14875. };
  14876. this.getPixelRatio = function () {
  14877. return _pixelRatio;
  14878. };
  14879. this.setPixelRatio = function ( value ) {
  14880. if ( value === undefined ) return;
  14881. _pixelRatio = value;
  14882. this.setSize( _viewport.z, _viewport.w, false );
  14883. };
  14884. this.getSize = function () {
  14885. return {
  14886. width: _width,
  14887. height: _height
  14888. };
  14889. };
  14890. this.setSize = function ( width, height, updateStyle ) {
  14891. _width = width;
  14892. _height = height;
  14893. _canvas.width = width * _pixelRatio;
  14894. _canvas.height = height * _pixelRatio;
  14895. if ( updateStyle !== false ) {
  14896. _canvas.style.width = width + 'px';
  14897. _canvas.style.height = height + 'px';
  14898. }
  14899. this.setViewport( 0, 0, width, height );
  14900. };
  14901. this.setViewport = function ( x, y, width, height ) {
  14902. state.viewport( _viewport.set( x, y, width, height ) );
  14903. };
  14904. this.setScissor = function ( x, y, width, height ) {
  14905. state.scissor( _scissor.set( x, y, width, height ) );
  14906. };
  14907. this.setScissorTest = function ( boolean ) {
  14908. state.setScissorTest( _scissorTest = boolean );
  14909. };
  14910. // Clearing
  14911. this.getClearColor = function () {
  14912. return _clearColor;
  14913. };
  14914. this.setClearColor = function ( color, alpha ) {
  14915. _clearColor.set( color );
  14916. _clearAlpha = alpha !== undefined ? alpha : 1;
  14917. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14918. };
  14919. this.getClearAlpha = function () {
  14920. return _clearAlpha;
  14921. };
  14922. this.setClearAlpha = function ( alpha ) {
  14923. _clearAlpha = alpha;
  14924. glClearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14925. };
  14926. this.clear = function ( color, depth, stencil ) {
  14927. var bits = 0;
  14928. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  14929. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  14930. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  14931. _gl.clear( bits );
  14932. };
  14933. this.clearColor = function () {
  14934. this.clear( true, false, false );
  14935. };
  14936. this.clearDepth = function () {
  14937. this.clear( false, true, false );
  14938. };
  14939. this.clearStencil = function () {
  14940. this.clear( false, false, true );
  14941. };
  14942. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  14943. this.setRenderTarget( renderTarget );
  14944. this.clear( color, depth, stencil );
  14945. };
  14946. // Reset
  14947. this.resetGLState = resetGLState;
  14948. this.dispose = function() {
  14949. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  14950. };
  14951. // Events
  14952. function onContextLost( event ) {
  14953. event.preventDefault();
  14954. resetGLState();
  14955. setDefaultGLState();
  14956. properties.clear();
  14957. }
  14958. function onTextureDispose( event ) {
  14959. var texture = event.target;
  14960. texture.removeEventListener( 'dispose', onTextureDispose );
  14961. deallocateTexture( texture );
  14962. _infoMemory.textures --;
  14963. }
  14964. function onRenderTargetDispose( event ) {
  14965. var renderTarget = event.target;
  14966. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14967. deallocateRenderTarget( renderTarget );
  14968. _infoMemory.textures --;
  14969. }
  14970. function onMaterialDispose( event ) {
  14971. var material = event.target;
  14972. material.removeEventListener( 'dispose', onMaterialDispose );
  14973. deallocateMaterial( material );
  14974. }
  14975. // Buffer deallocation
  14976. function deallocateTexture( texture ) {
  14977. var textureProperties = properties.get( texture );
  14978. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  14979. // cube texture
  14980. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  14981. } else {
  14982. // 2D texture
  14983. if ( textureProperties.__webglInit === undefined ) return;
  14984. _gl.deleteTexture( textureProperties.__webglTexture );
  14985. }
  14986. // remove all webgl properties
  14987. properties.delete( texture );
  14988. }
  14989. function deallocateRenderTarget( renderTarget ) {
  14990. var renderTargetProperties = properties.get( renderTarget );
  14991. var textureProperties = properties.get( renderTarget.texture );
  14992. if ( ! renderTarget ) return;
  14993. if ( textureProperties.__webglTexture !== undefined ) {
  14994. _gl.deleteTexture( textureProperties.__webglTexture );
  14995. }
  14996. if ( renderTarget.depthTexture ) {
  14997. renderTarget.depthTexture.dispose();
  14998. }
  14999. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15000. for ( var i = 0; i < 6; i ++ ) {
  15001. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  15002. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  15003. }
  15004. } else {
  15005. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  15006. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  15007. }
  15008. properties.delete( renderTarget.texture );
  15009. properties.delete( renderTarget );
  15010. }
  15011. function deallocateMaterial( material ) {
  15012. releaseMaterialProgramReference( material );
  15013. properties.delete( material );
  15014. }
  15015. function releaseMaterialProgramReference( material ) {
  15016. var programInfo = properties.get( material ).program;
  15017. material.program = undefined;
  15018. if ( programInfo !== undefined ) {
  15019. programCache.releaseProgram( programInfo );
  15020. }
  15021. }
  15022. // Buffer rendering
  15023. this.renderBufferImmediate = function ( object, program, material ) {
  15024. state.initAttributes();
  15025. var buffers = properties.get( object );
  15026. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  15027. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  15028. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  15029. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  15030. var attributes = program.getAttributes();
  15031. if ( object.hasPositions ) {
  15032. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  15033. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  15034. state.enableAttribute( attributes.position );
  15035. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  15036. }
  15037. if ( object.hasNormals ) {
  15038. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  15039. if ( material.type !== 'MeshPhongMaterial' && material.type !== 'MeshStandardMaterial' && material.type !== 'MeshPhysicalMaterial' && material.shading === THREE.FlatShading ) {
  15040. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  15041. var array = object.normalArray;
  15042. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  15043. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  15044. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  15045. array[ i + 0 ] = nx;
  15046. array[ i + 1 ] = ny;
  15047. array[ i + 2 ] = nz;
  15048. array[ i + 3 ] = nx;
  15049. array[ i + 4 ] = ny;
  15050. array[ i + 5 ] = nz;
  15051. array[ i + 6 ] = nx;
  15052. array[ i + 7 ] = ny;
  15053. array[ i + 8 ] = nz;
  15054. }
  15055. }
  15056. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  15057. state.enableAttribute( attributes.normal );
  15058. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  15059. }
  15060. if ( object.hasUvs && material.map ) {
  15061. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  15062. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  15063. state.enableAttribute( attributes.uv );
  15064. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  15065. }
  15066. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  15067. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  15068. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  15069. state.enableAttribute( attributes.color );
  15070. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  15071. }
  15072. state.disableUnusedAttributes();
  15073. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  15074. object.count = 0;
  15075. };
  15076. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  15077. setMaterial( material );
  15078. var program = setProgram( camera, fog, material, object );
  15079. var updateBuffers = false;
  15080. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  15081. if ( geometryProgram !== _currentGeometryProgram ) {
  15082. _currentGeometryProgram = geometryProgram;
  15083. updateBuffers = true;
  15084. }
  15085. // morph targets
  15086. var morphTargetInfluences = object.morphTargetInfluences;
  15087. if ( morphTargetInfluences !== undefined ) {
  15088. var activeInfluences = [];
  15089. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  15090. var influence = morphTargetInfluences[ i ];
  15091. activeInfluences.push( [ influence, i ] );
  15092. }
  15093. activeInfluences.sort( absNumericalSort );
  15094. if ( activeInfluences.length > 8 ) {
  15095. activeInfluences.length = 8;
  15096. }
  15097. var morphAttributes = geometry.morphAttributes;
  15098. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  15099. var influence = activeInfluences[ i ];
  15100. morphInfluences[ i ] = influence[ 0 ];
  15101. if ( influence[ 0 ] !== 0 ) {
  15102. var index = influence[ 1 ];
  15103. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  15104. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  15105. } else {
  15106. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  15107. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  15108. }
  15109. }
  15110. program.getUniforms().setValue(
  15111. _gl, 'morphTargetInfluences', morphInfluences );
  15112. updateBuffers = true;
  15113. }
  15114. //
  15115. var index = geometry.index;
  15116. var position = geometry.attributes.position;
  15117. if ( material.wireframe === true ) {
  15118. index = objects.getWireframeAttribute( geometry );
  15119. }
  15120. var renderer;
  15121. if ( index !== null ) {
  15122. renderer = indexedBufferRenderer;
  15123. renderer.setIndex( index );
  15124. } else {
  15125. renderer = bufferRenderer;
  15126. }
  15127. if ( updateBuffers ) {
  15128. setupVertexAttributes( material, program, geometry );
  15129. if ( index !== null ) {
  15130. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  15131. }
  15132. }
  15133. //
  15134. var dataStart = 0;
  15135. var dataCount = Infinity;
  15136. if ( index !== null ) {
  15137. dataCount = index.count;
  15138. } else if ( position !== undefined ) {
  15139. dataCount = position.count;
  15140. }
  15141. var rangeStart = geometry.drawRange.start;
  15142. var rangeCount = geometry.drawRange.count;
  15143. var groupStart = group !== null ? group.start : 0;
  15144. var groupCount = group !== null ? group.count : Infinity;
  15145. var drawStart = Math.max( dataStart, rangeStart, groupStart );
  15146. var drawEnd = Math.min( dataStart + dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  15147. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  15148. //
  15149. if ( object instanceof THREE.Mesh ) {
  15150. if ( material.wireframe === true ) {
  15151. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  15152. renderer.setMode( _gl.LINES );
  15153. } else {
  15154. switch ( object.drawMode ) {
  15155. case THREE.TrianglesDrawMode:
  15156. renderer.setMode( _gl.TRIANGLES );
  15157. break;
  15158. case THREE.TriangleStripDrawMode:
  15159. renderer.setMode( _gl.TRIANGLE_STRIP );
  15160. break;
  15161. case THREE.TriangleFanDrawMode:
  15162. renderer.setMode( _gl.TRIANGLE_FAN );
  15163. break;
  15164. }
  15165. }
  15166. } else if ( object instanceof THREE.Line ) {
  15167. var lineWidth = material.linewidth;
  15168. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  15169. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  15170. if ( object instanceof THREE.LineSegments ) {
  15171. renderer.setMode( _gl.LINES );
  15172. } else {
  15173. renderer.setMode( _gl.LINE_STRIP );
  15174. }
  15175. } else if ( object instanceof THREE.Points ) {
  15176. renderer.setMode( _gl.POINTS );
  15177. }
  15178. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  15179. if ( geometry.maxInstancedCount > 0 ) {
  15180. renderer.renderInstances( geometry, drawStart, drawCount );
  15181. }
  15182. } else {
  15183. renderer.render( drawStart, drawCount );
  15184. }
  15185. };
  15186. function setupVertexAttributes( material, program, geometry, startIndex ) {
  15187. var extension;
  15188. if ( geometry instanceof THREE.InstancedBufferGeometry ) {
  15189. extension = extensions.get( 'ANGLE_instanced_arrays' );
  15190. if ( extension === null ) {
  15191. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  15192. return;
  15193. }
  15194. }
  15195. if ( startIndex === undefined ) startIndex = 0;
  15196. state.initAttributes();
  15197. var geometryAttributes = geometry.attributes;
  15198. var programAttributes = program.getAttributes();
  15199. var materialDefaultAttributeValues = material.defaultAttributeValues;
  15200. for ( var name in programAttributes ) {
  15201. var programAttribute = programAttributes[ name ];
  15202. if ( programAttribute >= 0 ) {
  15203. var geometryAttribute = geometryAttributes[ name ];
  15204. if ( geometryAttribute !== undefined ) {
  15205. var type = _gl.FLOAT;
  15206. var array = geometryAttribute.array;
  15207. var normalized = geometryAttribute.normalized;
  15208. if ( array instanceof Float32Array ) {
  15209. type = _gl.FLOAT;
  15210. } else if ( array instanceof Float64Array ) {
  15211. console.warn("Unsupported data buffer format: Float64Array");
  15212. } else if ( array instanceof Uint16Array ) {
  15213. type = _gl.UNSIGNED_SHORT;
  15214. } else if ( array instanceof Int16Array ) {
  15215. type = _gl.SHORT;
  15216. } else if ( array instanceof Uint32Array ) {
  15217. type = _gl.UNSIGNED_INT;
  15218. } else if ( array instanceof Int32Array ) {
  15219. type = _gl.INT;
  15220. } else if ( array instanceof Int8Array ) {
  15221. type = _gl.BYTE;
  15222. } else if ( array instanceof Uint8Array ) {
  15223. type = _gl.UNSIGNED_BYTE;
  15224. }
  15225. var size = geometryAttribute.itemSize;
  15226. var buffer = objects.getAttributeBuffer( geometryAttribute );
  15227. if ( geometryAttribute instanceof THREE.InterleavedBufferAttribute ) {
  15228. var data = geometryAttribute.data;
  15229. var stride = data.stride;
  15230. var offset = geometryAttribute.offset;
  15231. if ( data instanceof THREE.InstancedInterleavedBuffer ) {
  15232. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  15233. if ( geometry.maxInstancedCount === undefined ) {
  15234. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  15235. }
  15236. } else {
  15237. state.enableAttribute( programAttribute );
  15238. }
  15239. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15240. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * data.array.BYTES_PER_ELEMENT, ( startIndex * stride + offset ) * data.array.BYTES_PER_ELEMENT );
  15241. } else {
  15242. if ( geometryAttribute instanceof THREE.InstancedBufferAttribute ) {
  15243. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  15244. if ( geometry.maxInstancedCount === undefined ) {
  15245. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  15246. }
  15247. } else {
  15248. state.enableAttribute( programAttribute );
  15249. }
  15250. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  15251. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * geometryAttribute.array.BYTES_PER_ELEMENT );
  15252. }
  15253. } else if ( materialDefaultAttributeValues !== undefined ) {
  15254. var value = materialDefaultAttributeValues[ name ];
  15255. if ( value !== undefined ) {
  15256. switch ( value.length ) {
  15257. case 2:
  15258. _gl.vertexAttrib2fv( programAttribute, value );
  15259. break;
  15260. case 3:
  15261. _gl.vertexAttrib3fv( programAttribute, value );
  15262. break;
  15263. case 4:
  15264. _gl.vertexAttrib4fv( programAttribute, value );
  15265. break;
  15266. default:
  15267. _gl.vertexAttrib1fv( programAttribute, value );
  15268. }
  15269. }
  15270. }
  15271. }
  15272. }
  15273. state.disableUnusedAttributes();
  15274. }
  15275. // Sorting
  15276. function absNumericalSort( a, b ) {
  15277. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  15278. }
  15279. function painterSortStable ( a, b ) {
  15280. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15281. return a.object.renderOrder - b.object.renderOrder;
  15282. } else if ( a.material.id !== b.material.id ) {
  15283. return a.material.id - b.material.id;
  15284. } else if ( a.z !== b.z ) {
  15285. return a.z - b.z;
  15286. } else {
  15287. return a.id - b.id;
  15288. }
  15289. }
  15290. function reversePainterSortStable ( a, b ) {
  15291. if ( a.object.renderOrder !== b.object.renderOrder ) {
  15292. return a.object.renderOrder - b.object.renderOrder;
  15293. } if ( a.z !== b.z ) {
  15294. return b.z - a.z;
  15295. } else {
  15296. return a.id - b.id;
  15297. }
  15298. }
  15299. // Rendering
  15300. this.render = function ( scene, camera, renderTarget, forceClear ) {
  15301. if ( camera instanceof THREE.Camera === false ) {
  15302. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  15303. return;
  15304. }
  15305. var fog = scene.fog;
  15306. // reset caching for this frame
  15307. _currentGeometryProgram = '';
  15308. _currentMaterialId = - 1;
  15309. _currentCamera = null;
  15310. // update scene graph
  15311. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  15312. // update camera matrices and frustum
  15313. if ( camera.parent === null ) camera.updateMatrixWorld();
  15314. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  15315. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  15316. _frustum.setFromMatrix( _projScreenMatrix );
  15317. lights.length = 0;
  15318. opaqueObjectsLastIndex = - 1;
  15319. transparentObjectsLastIndex = - 1;
  15320. sprites.length = 0;
  15321. lensFlares.length = 0;
  15322. setupGlobalClippingPlanes( this.clippingPlanes, camera );
  15323. projectObject( scene, camera );
  15324. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  15325. transparentObjects.length = transparentObjectsLastIndex + 1;
  15326. if ( _this.sortObjects === true ) {
  15327. opaqueObjects.sort( painterSortStable );
  15328. transparentObjects.sort( reversePainterSortStable );
  15329. }
  15330. //
  15331. if ( _clippingEnabled ) {
  15332. _clipRenderingShadows = true;
  15333. setupClippingPlanes( null );
  15334. }
  15335. setupShadows( lights );
  15336. shadowMap.render( scene, camera );
  15337. setupLights( lights, camera );
  15338. if ( _clippingEnabled ) {
  15339. _clipRenderingShadows = false;
  15340. resetGlobalClippingState();
  15341. }
  15342. //
  15343. _infoRender.calls = 0;
  15344. _infoRender.vertices = 0;
  15345. _infoRender.faces = 0;
  15346. _infoRender.points = 0;
  15347. if ( renderTarget === undefined ) {
  15348. renderTarget = null;
  15349. }
  15350. this.setRenderTarget( renderTarget );
  15351. if ( this.autoClear || forceClear ) {
  15352. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  15353. }
  15354. //
  15355. if ( scene.overrideMaterial ) {
  15356. var overrideMaterial = scene.overrideMaterial;
  15357. renderObjects( opaqueObjects, camera, fog, overrideMaterial );
  15358. renderObjects( transparentObjects, camera, fog, overrideMaterial );
  15359. } else {
  15360. // opaque pass (front-to-back order)
  15361. state.setBlending( THREE.NoBlending );
  15362. renderObjects( opaqueObjects, camera, fog );
  15363. // transparent pass (back-to-front order)
  15364. renderObjects( transparentObjects, camera, fog );
  15365. }
  15366. // custom render plugins (post pass)
  15367. spritePlugin.render( scene, camera );
  15368. lensFlarePlugin.render( scene, camera, _currentViewport );
  15369. // Generate mipmap if we're using any kind of mipmap filtering
  15370. if ( renderTarget ) {
  15371. var texture = renderTarget.texture;
  15372. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  15373. texture.minFilter !== THREE.NearestFilter &&
  15374. texture.minFilter !== THREE.LinearFilter ) {
  15375. updateRenderTargetMipmap( renderTarget );
  15376. }
  15377. }
  15378. // Ensure depth buffer writing is enabled so it can be cleared on next render
  15379. state.setDepthTest( true );
  15380. state.setDepthWrite( true );
  15381. state.setColorWrite( true );
  15382. // _gl.finish();
  15383. };
  15384. function pushRenderItem( object, geometry, material, z, group ) {
  15385. var array, index;
  15386. // allocate the next position in the appropriate array
  15387. if ( material.transparent ) {
  15388. array = transparentObjects;
  15389. index = ++ transparentObjectsLastIndex;
  15390. } else {
  15391. array = opaqueObjects;
  15392. index = ++ opaqueObjectsLastIndex;
  15393. }
  15394. // recycle existing render item or grow the array
  15395. var renderItem = array[ index ];
  15396. if ( renderItem !== undefined ) {
  15397. renderItem.id = object.id;
  15398. renderItem.object = object;
  15399. renderItem.geometry = geometry;
  15400. renderItem.material = material;
  15401. renderItem.z = _vector3.z;
  15402. renderItem.group = group;
  15403. } else {
  15404. renderItem = {
  15405. id: object.id,
  15406. object: object,
  15407. geometry: geometry,
  15408. material: material,
  15409. z: _vector3.z,
  15410. group: group
  15411. };
  15412. // assert( index === array.length );
  15413. array.push( renderItem );
  15414. }
  15415. }
  15416. function isObjectViewable( object ) {
  15417. var geometry = object.geometry;
  15418. if ( geometry.boundingSphere === null )
  15419. geometry.computeBoundingSphere();
  15420. var sphere = _sphere.
  15421. copy( geometry.boundingSphere ).
  15422. applyMatrix4( object.matrixWorld );
  15423. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  15424. if ( _numClippingPlanes === 0 ) return true;
  15425. var planes = _this.clippingPlanes,
  15426. center = sphere.center,
  15427. negRad = - sphere.radius,
  15428. i = 0;
  15429. do {
  15430. // out when deeper than radius in the negative halfspace
  15431. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  15432. } while ( ++ i !== _numClippingPlanes );
  15433. return true;
  15434. }
  15435. function projectObject( object, camera ) {
  15436. if ( object.visible === false ) return;
  15437. if ( object.layers.test( camera.layers ) ) {
  15438. if ( object instanceof THREE.Light ) {
  15439. lights.push( object );
  15440. } else if ( object instanceof THREE.Sprite ) {
  15441. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  15442. sprites.push( object );
  15443. }
  15444. } else if ( object instanceof THREE.LensFlare ) {
  15445. lensFlares.push( object );
  15446. } else if ( object instanceof THREE.ImmediateRenderObject ) {
  15447. if ( _this.sortObjects === true ) {
  15448. _vector3.setFromMatrixPosition( object.matrixWorld );
  15449. _vector3.applyProjection( _projScreenMatrix );
  15450. }
  15451. pushRenderItem( object, null, object.material, _vector3.z, null );
  15452. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) {
  15453. if ( object instanceof THREE.SkinnedMesh ) {
  15454. object.skeleton.update();
  15455. }
  15456. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  15457. var material = object.material;
  15458. if ( material.visible === true ) {
  15459. if ( _this.sortObjects === true ) {
  15460. _vector3.setFromMatrixPosition( object.matrixWorld );
  15461. _vector3.applyProjection( _projScreenMatrix );
  15462. }
  15463. var geometry = objects.update( object );
  15464. if ( material instanceof THREE.MultiMaterial ) {
  15465. var groups = geometry.groups;
  15466. var materials = material.materials;
  15467. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  15468. var group = groups[ i ];
  15469. var groupMaterial = materials[ group.materialIndex ];
  15470. if ( groupMaterial.visible === true ) {
  15471. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  15472. }
  15473. }
  15474. } else {
  15475. pushRenderItem( object, geometry, material, _vector3.z, null );
  15476. }
  15477. }
  15478. }
  15479. }
  15480. }
  15481. var children = object.children;
  15482. for ( var i = 0, l = children.length; i < l; i ++ ) {
  15483. projectObject( children[ i ], camera );
  15484. }
  15485. }
  15486. function renderObjects( renderList, camera, fog, overrideMaterial ) {
  15487. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  15488. var renderItem = renderList[ i ];
  15489. var object = renderItem.object;
  15490. var geometry = renderItem.geometry;
  15491. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  15492. var group = renderItem.group;
  15493. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15494. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  15495. if ( object instanceof THREE.ImmediateRenderObject ) {
  15496. setMaterial( material );
  15497. var program = setProgram( camera, fog, material, object );
  15498. _currentGeometryProgram = '';
  15499. object.render( function ( object ) {
  15500. _this.renderBufferImmediate( object, program, material );
  15501. } );
  15502. } else {
  15503. _this.renderBufferDirect( camera, fog, geometry, material, object, group );
  15504. }
  15505. }
  15506. }
  15507. function initMaterial( material, fog, object ) {
  15508. var materialProperties = properties.get( material );
  15509. var parameters = programCache.getParameters(
  15510. material, _lights, fog, _numClippingPlanes, object );
  15511. var code = programCache.getProgramCode( material, parameters );
  15512. var program = materialProperties.program;
  15513. var programChange = true;
  15514. if ( program === undefined ) {
  15515. // new material
  15516. material.addEventListener( 'dispose', onMaterialDispose );
  15517. } else if ( program.code !== code ) {
  15518. // changed glsl or parameters
  15519. releaseMaterialProgramReference( material );
  15520. } else if ( parameters.shaderID !== undefined ) {
  15521. // same glsl and uniform list
  15522. return;
  15523. } else {
  15524. // only rebuild uniform list
  15525. programChange = false;
  15526. }
  15527. if ( programChange ) {
  15528. if ( parameters.shaderID ) {
  15529. var shader = THREE.ShaderLib[ parameters.shaderID ];
  15530. materialProperties.__webglShader = {
  15531. name: material.type,
  15532. uniforms: THREE.UniformsUtils.clone( shader.uniforms ),
  15533. vertexShader: shader.vertexShader,
  15534. fragmentShader: shader.fragmentShader
  15535. };
  15536. } else {
  15537. materialProperties.__webglShader = {
  15538. name: material.type,
  15539. uniforms: material.uniforms,
  15540. vertexShader: material.vertexShader,
  15541. fragmentShader: material.fragmentShader
  15542. };
  15543. }
  15544. material.__webglShader = materialProperties.__webglShader;
  15545. program = programCache.acquireProgram( material, parameters, code );
  15546. materialProperties.program = program;
  15547. material.program = program;
  15548. }
  15549. var attributes = program.getAttributes();
  15550. if ( material.morphTargets ) {
  15551. material.numSupportedMorphTargets = 0;
  15552. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  15553. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  15554. material.numSupportedMorphTargets ++;
  15555. }
  15556. }
  15557. }
  15558. if ( material.morphNormals ) {
  15559. material.numSupportedMorphNormals = 0;
  15560. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  15561. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  15562. material.numSupportedMorphNormals ++;
  15563. }
  15564. }
  15565. }
  15566. var uniforms = materialProperties.__webglShader.uniforms;
  15567. if ( ! ( material instanceof THREE.ShaderMaterial ) &&
  15568. ! ( material instanceof THREE.RawShaderMaterial ) ||
  15569. material.clipping === true ) {
  15570. materialProperties.numClippingPlanes = _numClippingPlanes;
  15571. uniforms.clippingPlanes = _clippingPlanesUniform;
  15572. }
  15573. if ( material instanceof THREE.MeshPhongMaterial ||
  15574. material instanceof THREE.MeshLambertMaterial ||
  15575. material instanceof THREE.MeshStandardMaterial ||
  15576. material.lights ) {
  15577. // store the light setup it was created for
  15578. materialProperties.lightsHash = _lights.hash;
  15579. // wire up the material to this renderer's lighting state
  15580. uniforms.ambientLightColor.value = _lights.ambient;
  15581. uniforms.directionalLights.value = _lights.directional;
  15582. uniforms.spotLights.value = _lights.spot;
  15583. uniforms.pointLights.value = _lights.point;
  15584. uniforms.hemisphereLights.value = _lights.hemi;
  15585. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  15586. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  15587. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  15588. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  15589. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  15590. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  15591. }
  15592. var progUniforms = materialProperties.program.getUniforms(),
  15593. uniformsList =
  15594. THREE.WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  15595. materialProperties.uniformsList = uniformsList;
  15596. materialProperties.dynamicUniforms =
  15597. THREE.WebGLUniforms.splitDynamic( uniformsList, uniforms );
  15598. }
  15599. function setMaterial( material ) {
  15600. setMaterialFaces( material );
  15601. if ( material.transparent === true ) {
  15602. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  15603. } else {
  15604. state.setBlending( THREE.NoBlending );
  15605. }
  15606. state.setDepthFunc( material.depthFunc );
  15607. state.setDepthTest( material.depthTest );
  15608. state.setDepthWrite( material.depthWrite );
  15609. state.setColorWrite( material.colorWrite );
  15610. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  15611. }
  15612. function setMaterialFaces( material ) {
  15613. material.side !== THREE.DoubleSide ? state.enable( _gl.CULL_FACE ) : state.disable( _gl.CULL_FACE );
  15614. state.setFlipSided( material.side === THREE.BackSide );
  15615. }
  15616. function setProgram( camera, fog, material, object ) {
  15617. _usedTextureUnits = 0;
  15618. var materialProperties = properties.get( material );
  15619. if ( _clippingEnabled ) {
  15620. if ( _localClippingEnabled || camera !== _currentCamera ) {
  15621. var useCache =
  15622. camera === _currentCamera &&
  15623. material.id === _currentMaterialId;
  15624. // we might want to call this function with some ClippingGroup
  15625. // object instead of the material, once it becomes feasible
  15626. // (#8465, #8379)
  15627. setClippingState(
  15628. material.clippingPlanes, material.clipShadows,
  15629. camera, materialProperties, useCache );
  15630. }
  15631. if ( materialProperties.numClippingPlanes !== undefined &&
  15632. materialProperties.numClippingPlanes !== _numClippingPlanes ) {
  15633. material.needsUpdate = true;
  15634. }
  15635. }
  15636. if ( materialProperties.program === undefined ) {
  15637. material.needsUpdate = true;
  15638. }
  15639. if ( materialProperties.lightsHash !== undefined &&
  15640. materialProperties.lightsHash !== _lights.hash ) {
  15641. material.needsUpdate = true;
  15642. }
  15643. if ( material.needsUpdate ) {
  15644. initMaterial( material, fog, object );
  15645. material.needsUpdate = false;
  15646. }
  15647. var refreshProgram = false;
  15648. var refreshMaterial = false;
  15649. var refreshLights = false;
  15650. var program = materialProperties.program,
  15651. p_uniforms = program.getUniforms(),
  15652. m_uniforms = materialProperties.__webglShader.uniforms;
  15653. if ( program.id !== _currentProgram ) {
  15654. _gl.useProgram( program.program );
  15655. _currentProgram = program.id;
  15656. refreshProgram = true;
  15657. refreshMaterial = true;
  15658. refreshLights = true;
  15659. }
  15660. if ( material.id !== _currentMaterialId ) {
  15661. _currentMaterialId = material.id;
  15662. refreshMaterial = true;
  15663. }
  15664. if ( refreshProgram || camera !== _currentCamera ) {
  15665. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  15666. if ( capabilities.logarithmicDepthBuffer ) {
  15667. p_uniforms.setValue( _gl, 'logDepthBufFC',
  15668. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  15669. }
  15670. if ( camera !== _currentCamera ) {
  15671. _currentCamera = camera;
  15672. // lighting uniforms depend on the camera so enforce an update
  15673. // now, in case this material supports lights - or later, when
  15674. // the next material that does gets activated:
  15675. refreshMaterial = true; // set to true on material change
  15676. refreshLights = true; // remains set until update done
  15677. }
  15678. // load material specific uniforms
  15679. // (shader material also gets them for the sake of genericity)
  15680. if ( material instanceof THREE.ShaderMaterial ||
  15681. material instanceof THREE.MeshPhongMaterial ||
  15682. material instanceof THREE.MeshStandardMaterial ||
  15683. material.envMap ) {
  15684. var uCamPos = p_uniforms.map.cameraPosition;
  15685. if ( uCamPos !== undefined ) {
  15686. uCamPos.setValue( _gl,
  15687. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  15688. }
  15689. }
  15690. if ( material instanceof THREE.MeshPhongMaterial ||
  15691. material instanceof THREE.MeshLambertMaterial ||
  15692. material instanceof THREE.MeshBasicMaterial ||
  15693. material instanceof THREE.MeshStandardMaterial ||
  15694. material instanceof THREE.ShaderMaterial ||
  15695. material.skinning ) {
  15696. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  15697. }
  15698. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  15699. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  15700. }
  15701. // skinning uniforms must be set even if material didn't change
  15702. // auto-setting of texture unit for bone texture must go before other textures
  15703. // not sure why, but otherwise weird things happen
  15704. if ( material.skinning ) {
  15705. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  15706. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  15707. var skeleton = object.skeleton;
  15708. if ( skeleton ) {
  15709. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  15710. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  15711. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  15712. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  15713. } else {
  15714. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  15715. }
  15716. }
  15717. }
  15718. if ( refreshMaterial ) {
  15719. if ( material instanceof THREE.MeshPhongMaterial ||
  15720. material instanceof THREE.MeshLambertMaterial ||
  15721. material instanceof THREE.MeshStandardMaterial ||
  15722. material.lights ) {
  15723. // the current material requires lighting info
  15724. // note: all lighting uniforms are always set correctly
  15725. // they simply reference the renderer's state for their
  15726. // values
  15727. //
  15728. // use the current material's .needsUpdate flags to set
  15729. // the GL state when required
  15730. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  15731. }
  15732. // refresh uniforms common to several materials
  15733. if ( fog && material.fog ) {
  15734. refreshUniformsFog( m_uniforms, fog );
  15735. }
  15736. if ( material instanceof THREE.MeshBasicMaterial ||
  15737. material instanceof THREE.MeshLambertMaterial ||
  15738. material instanceof THREE.MeshPhongMaterial ||
  15739. material instanceof THREE.MeshStandardMaterial ||
  15740. material instanceof THREE.MeshDepthMaterial ) {
  15741. refreshUniformsCommon( m_uniforms, material );
  15742. }
  15743. // refresh single material specific uniforms
  15744. if ( material instanceof THREE.LineBasicMaterial ) {
  15745. refreshUniformsLine( m_uniforms, material );
  15746. } else if ( material instanceof THREE.LineDashedMaterial ) {
  15747. refreshUniformsLine( m_uniforms, material );
  15748. refreshUniformsDash( m_uniforms, material );
  15749. } else if ( material instanceof THREE.PointsMaterial ) {
  15750. refreshUniformsPoints( m_uniforms, material );
  15751. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  15752. refreshUniformsLambert( m_uniforms, material );
  15753. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  15754. refreshUniformsPhong( m_uniforms, material );
  15755. } else if ( material instanceof THREE.MeshPhysicalMaterial ) {
  15756. refreshUniformsPhysical( m_uniforms, material );
  15757. } else if ( material instanceof THREE.MeshStandardMaterial ) {
  15758. refreshUniformsStandard( m_uniforms, material );
  15759. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  15760. if ( material.displacementMap ) {
  15761. m_uniforms.displacementMap.value = material.displacementMap;
  15762. m_uniforms.displacementScale.value = material.displacementScale;
  15763. m_uniforms.displacementBias.value = material.displacementBias;
  15764. }
  15765. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  15766. m_uniforms.opacity.value = material.opacity;
  15767. }
  15768. THREE.WebGLUniforms.upload(
  15769. _gl, materialProperties.uniformsList, m_uniforms, _this );
  15770. }
  15771. // common matrices
  15772. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  15773. p_uniforms.set( _gl, object, 'normalMatrix' );
  15774. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  15775. // dynamic uniforms
  15776. var dynUniforms = materialProperties.dynamicUniforms;
  15777. if ( dynUniforms !== null ) {
  15778. THREE.WebGLUniforms.evalDynamic(
  15779. dynUniforms, m_uniforms, object, camera );
  15780. THREE.WebGLUniforms.upload( _gl, dynUniforms, m_uniforms, _this );
  15781. }
  15782. return program;
  15783. }
  15784. // Uniforms (refresh uniforms objects)
  15785. function refreshUniformsCommon ( uniforms, material ) {
  15786. uniforms.opacity.value = material.opacity;
  15787. uniforms.diffuse.value = material.color;
  15788. if ( material.emissive ) {
  15789. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  15790. }
  15791. uniforms.map.value = material.map;
  15792. uniforms.specularMap.value = material.specularMap;
  15793. uniforms.alphaMap.value = material.alphaMap;
  15794. if ( material.aoMap ) {
  15795. uniforms.aoMap.value = material.aoMap;
  15796. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  15797. }
  15798. // uv repeat and offset setting priorities
  15799. // 1. color map
  15800. // 2. specular map
  15801. // 3. normal map
  15802. // 4. bump map
  15803. // 5. alpha map
  15804. // 6. emissive map
  15805. var uvScaleMap;
  15806. if ( material.map ) {
  15807. uvScaleMap = material.map;
  15808. } else if ( material.specularMap ) {
  15809. uvScaleMap = material.specularMap;
  15810. } else if ( material.displacementMap ) {
  15811. uvScaleMap = material.displacementMap;
  15812. } else if ( material.normalMap ) {
  15813. uvScaleMap = material.normalMap;
  15814. } else if ( material.bumpMap ) {
  15815. uvScaleMap = material.bumpMap;
  15816. } else if ( material.roughnessMap ) {
  15817. uvScaleMap = material.roughnessMap;
  15818. } else if ( material.metalnessMap ) {
  15819. uvScaleMap = material.metalnessMap;
  15820. } else if ( material.alphaMap ) {
  15821. uvScaleMap = material.alphaMap;
  15822. } else if ( material.emissiveMap ) {
  15823. uvScaleMap = material.emissiveMap;
  15824. }
  15825. if ( uvScaleMap !== undefined ) {
  15826. if ( uvScaleMap instanceof THREE.WebGLRenderTarget ) {
  15827. uvScaleMap = uvScaleMap.texture;
  15828. }
  15829. var offset = uvScaleMap.offset;
  15830. var repeat = uvScaleMap.repeat;
  15831. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15832. }
  15833. uniforms.envMap.value = material.envMap;
  15834. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : - 1;
  15835. uniforms.reflectivity.value = material.reflectivity;
  15836. uniforms.refractionRatio.value = material.refractionRatio;
  15837. }
  15838. function refreshUniformsLine ( uniforms, material ) {
  15839. uniforms.diffuse.value = material.color;
  15840. uniforms.opacity.value = material.opacity;
  15841. }
  15842. function refreshUniformsDash ( uniforms, material ) {
  15843. uniforms.dashSize.value = material.dashSize;
  15844. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15845. uniforms.scale.value = material.scale;
  15846. }
  15847. function refreshUniformsPoints ( uniforms, material ) {
  15848. uniforms.diffuse.value = material.color;
  15849. uniforms.opacity.value = material.opacity;
  15850. uniforms.size.value = material.size * _pixelRatio;
  15851. uniforms.scale.value = _canvas.clientHeight * 0.5;
  15852. uniforms.map.value = material.map;
  15853. if ( material.map !== null ) {
  15854. var offset = material.map.offset;
  15855. var repeat = material.map.repeat;
  15856. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15857. }
  15858. }
  15859. function refreshUniformsFog ( uniforms, fog ) {
  15860. uniforms.fogColor.value = fog.color;
  15861. if ( fog instanceof THREE.Fog ) {
  15862. uniforms.fogNear.value = fog.near;
  15863. uniforms.fogFar.value = fog.far;
  15864. } else if ( fog instanceof THREE.FogExp2 ) {
  15865. uniforms.fogDensity.value = fog.density;
  15866. }
  15867. }
  15868. function refreshUniformsLambert ( uniforms, material ) {
  15869. if ( material.lightMap ) {
  15870. uniforms.lightMap.value = material.lightMap;
  15871. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15872. }
  15873. if ( material.emissiveMap ) {
  15874. uniforms.emissiveMap.value = material.emissiveMap;
  15875. }
  15876. }
  15877. function refreshUniformsPhong ( uniforms, material ) {
  15878. uniforms.specular.value = material.specular;
  15879. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15880. if ( material.lightMap ) {
  15881. uniforms.lightMap.value = material.lightMap;
  15882. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15883. }
  15884. if ( material.emissiveMap ) {
  15885. uniforms.emissiveMap.value = material.emissiveMap;
  15886. }
  15887. if ( material.bumpMap ) {
  15888. uniforms.bumpMap.value = material.bumpMap;
  15889. uniforms.bumpScale.value = material.bumpScale;
  15890. }
  15891. if ( material.normalMap ) {
  15892. uniforms.normalMap.value = material.normalMap;
  15893. uniforms.normalScale.value.copy( material.normalScale );
  15894. }
  15895. if ( material.displacementMap ) {
  15896. uniforms.displacementMap.value = material.displacementMap;
  15897. uniforms.displacementScale.value = material.displacementScale;
  15898. uniforms.displacementBias.value = material.displacementBias;
  15899. }
  15900. }
  15901. function refreshUniformsStandard ( uniforms, material ) {
  15902. uniforms.roughness.value = material.roughness;
  15903. uniforms.metalness.value = material.metalness;
  15904. if ( material.roughnessMap ) {
  15905. uniforms.roughnessMap.value = material.roughnessMap;
  15906. }
  15907. if ( material.metalnessMap ) {
  15908. uniforms.metalnessMap.value = material.metalnessMap;
  15909. }
  15910. if ( material.lightMap ) {
  15911. uniforms.lightMap.value = material.lightMap;
  15912. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  15913. }
  15914. if ( material.emissiveMap ) {
  15915. uniforms.emissiveMap.value = material.emissiveMap;
  15916. }
  15917. if ( material.bumpMap ) {
  15918. uniforms.bumpMap.value = material.bumpMap;
  15919. uniforms.bumpScale.value = material.bumpScale;
  15920. }
  15921. if ( material.normalMap ) {
  15922. uniforms.normalMap.value = material.normalMap;
  15923. uniforms.normalScale.value.copy( material.normalScale );
  15924. }
  15925. if ( material.displacementMap ) {
  15926. uniforms.displacementMap.value = material.displacementMap;
  15927. uniforms.displacementScale.value = material.displacementScale;
  15928. uniforms.displacementBias.value = material.displacementBias;
  15929. }
  15930. if ( material.envMap ) {
  15931. //uniforms.envMap.value = material.envMap; // part of uniforms common
  15932. uniforms.envMapIntensity.value = material.envMapIntensity;
  15933. }
  15934. }
  15935. function refreshUniformsPhysical ( uniforms, material ) {
  15936. refreshUniformsStandard( uniforms, material );
  15937. }
  15938. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  15939. function markUniformsLightsNeedsUpdate ( uniforms, value ) {
  15940. uniforms.ambientLightColor.needsUpdate = value;
  15941. uniforms.directionalLights.needsUpdate = value;
  15942. uniforms.pointLights.needsUpdate = value;
  15943. uniforms.spotLights.needsUpdate = value;
  15944. uniforms.hemisphereLights.needsUpdate = value;
  15945. }
  15946. // Lighting
  15947. function setupShadows ( lights ) {
  15948. var lightShadowsLength = 0;
  15949. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  15950. var light = lights[ i ];
  15951. if ( light.castShadow ) {
  15952. _lights.shadows[ lightShadowsLength ++ ] = light;
  15953. }
  15954. }
  15955. _lights.shadows.length = lightShadowsLength;
  15956. }
  15957. function setupLights ( lights, camera ) {
  15958. var l, ll, light,
  15959. r = 0, g = 0, b = 0,
  15960. color,
  15961. intensity,
  15962. distance,
  15963. viewMatrix = camera.matrixWorldInverse,
  15964. directionalLength = 0,
  15965. pointLength = 0,
  15966. spotLength = 0,
  15967. hemiLength = 0;
  15968. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15969. light = lights[ l ];
  15970. color = light.color;
  15971. intensity = light.intensity;
  15972. distance = light.distance;
  15973. if ( light instanceof THREE.AmbientLight ) {
  15974. r += color.r * intensity;
  15975. g += color.g * intensity;
  15976. b += color.b * intensity;
  15977. } else if ( light instanceof THREE.DirectionalLight ) {
  15978. var uniforms = lightCache.get( light );
  15979. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  15980. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  15981. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15982. uniforms.direction.sub( _vector3 );
  15983. uniforms.direction.transformDirection( viewMatrix );
  15984. uniforms.shadow = light.castShadow;
  15985. if ( light.castShadow ) {
  15986. uniforms.shadowBias = light.shadow.bias;
  15987. uniforms.shadowRadius = light.shadow.radius;
  15988. uniforms.shadowMapSize = light.shadow.mapSize;
  15989. }
  15990. _lights.directionalShadowMap[ directionalLength ] = light.shadow.map;
  15991. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  15992. _lights.directional[ directionalLength ++ ] = uniforms;
  15993. } else if ( light instanceof THREE.SpotLight ) {
  15994. var uniforms = lightCache.get( light );
  15995. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  15996. uniforms.position.applyMatrix4( viewMatrix );
  15997. uniforms.color.copy( color ).multiplyScalar( intensity );
  15998. uniforms.distance = distance;
  15999. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16000. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  16001. uniforms.direction.sub( _vector3 );
  16002. uniforms.direction.transformDirection( viewMatrix );
  16003. uniforms.coneCos = Math.cos( light.angle );
  16004. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  16005. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16006. uniforms.shadow = light.castShadow;
  16007. if ( light.castShadow ) {
  16008. uniforms.shadowBias = light.shadow.bias;
  16009. uniforms.shadowRadius = light.shadow.radius;
  16010. uniforms.shadowMapSize = light.shadow.mapSize;
  16011. }
  16012. _lights.spotShadowMap[ spotLength ] = light.shadow.map;
  16013. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  16014. _lights.spot[ spotLength ++ ] = uniforms;
  16015. } else if ( light instanceof THREE.PointLight ) {
  16016. var uniforms = lightCache.get( light );
  16017. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  16018. uniforms.position.applyMatrix4( viewMatrix );
  16019. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  16020. uniforms.distance = light.distance;
  16021. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  16022. uniforms.shadow = light.castShadow;
  16023. if ( light.castShadow ) {
  16024. uniforms.shadowBias = light.shadow.bias;
  16025. uniforms.shadowRadius = light.shadow.radius;
  16026. uniforms.shadowMapSize = light.shadow.mapSize;
  16027. }
  16028. _lights.pointShadowMap[ pointLength ] = light.shadow.map;
  16029. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  16030. _lights.pointShadowMatrix[ pointLength ] = new THREE.Matrix4();
  16031. }
  16032. // for point lights we set the shadow matrix to be a translation-only matrix
  16033. // equal to inverse of the light's position
  16034. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  16035. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  16036. _lights.point[ pointLength ++ ] = uniforms;
  16037. } else if ( light instanceof THREE.HemisphereLight ) {
  16038. var uniforms = lightCache.get( light );
  16039. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  16040. uniforms.direction.transformDirection( viewMatrix );
  16041. uniforms.direction.normalize();
  16042. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  16043. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  16044. _lights.hemi[ hemiLength ++ ] = uniforms;
  16045. }
  16046. }
  16047. _lights.ambient[ 0 ] = r;
  16048. _lights.ambient[ 1 ] = g;
  16049. _lights.ambient[ 2 ] = b;
  16050. _lights.directional.length = directionalLength;
  16051. _lights.spot.length = spotLength;
  16052. _lights.point.length = pointLength;
  16053. _lights.hemi.length = hemiLength;
  16054. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + hemiLength + ',' + _lights.shadows.length;
  16055. }
  16056. // Clipping
  16057. function setupGlobalClippingPlanes( planes, camera ) {
  16058. _clippingEnabled =
  16059. _this.clippingPlanes.length !== 0 ||
  16060. _this.localClippingEnabled ||
  16061. // enable state of previous frame - the clipping code has to
  16062. // run another frame in order to reset the state:
  16063. _numGlobalClippingPlanes !== 0 ||
  16064. _localClippingEnabled;
  16065. _localClippingEnabled = _this.localClippingEnabled;
  16066. _globalClippingState = setupClippingPlanes( planes, camera, 0 );
  16067. _numGlobalClippingPlanes = planes !== null ? planes.length : 0;
  16068. }
  16069. function setupClippingPlanes( planes, camera, dstOffset, skipTransform ) {
  16070. var nPlanes = planes !== null ? planes.length : 0,
  16071. dstArray = null;
  16072. if ( nPlanes !== 0 ) {
  16073. dstArray = _clippingPlanesUniform.value;
  16074. if ( skipTransform !== true || dstArray === null ) {
  16075. var flatSize = dstOffset + nPlanes * 4,
  16076. viewMatrix = camera.matrixWorldInverse,
  16077. viewNormalMatrix = _matrix3.getNormalMatrix( viewMatrix );
  16078. if ( dstArray === null || dstArray.length < flatSize ) {
  16079. dstArray = new Float32Array( flatSize );
  16080. }
  16081. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  16082. var plane = _plane.copy( planes[ i ] ).
  16083. applyMatrix4( viewMatrix, viewNormalMatrix );
  16084. plane.normal.toArray( dstArray, i4 );
  16085. dstArray[ i4 + 3 ] = plane.constant;
  16086. }
  16087. }
  16088. _clippingPlanesUniform.value = dstArray;
  16089. _clippingPlanesUniform.needsUpdate = true;
  16090. }
  16091. _numClippingPlanes = nPlanes;
  16092. return dstArray;
  16093. }
  16094. function resetGlobalClippingState() {
  16095. if ( _clippingPlanesUniform.value !== _globalClippingState ) {
  16096. _clippingPlanesUniform.value = _globalClippingState;
  16097. _clippingPlanesUniform.needsUpdate = _numGlobalClippingPlanes > 0;
  16098. }
  16099. _numClippingPlanes = _numGlobalClippingPlanes;
  16100. }
  16101. function setClippingState( planes, clipShadows, camera, cache, fromCache ) {
  16102. if ( ! _localClippingEnabled ||
  16103. planes === null || planes.length === 0 ||
  16104. _clipRenderingShadows && ! clipShadows ) {
  16105. // there's no local clipping
  16106. if ( _clipRenderingShadows ) {
  16107. // there's no global clipping
  16108. setupClippingPlanes( null );
  16109. } else {
  16110. resetGlobalClippingState();
  16111. }
  16112. } else {
  16113. var nGlobal = _clipRenderingShadows ? 0 : _numGlobalClippingPlanes,
  16114. lGlobal = nGlobal * 4,
  16115. dstArray = cache.clippingState || null;
  16116. _clippingPlanesUniform.value = dstArray; // ensure unique state
  16117. dstArray = setupClippingPlanes(
  16118. planes, camera, lGlobal, fromCache );
  16119. for ( var i = 0; i !== lGlobal; ++ i ) {
  16120. dstArray[ i ] = _globalClippingState[ i ];
  16121. }
  16122. cache.clippingState = dstArray;
  16123. _numClippingPlanes += nGlobal;
  16124. }
  16125. }
  16126. // GL state setting
  16127. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  16128. if ( cullFace === THREE.CullFaceNone ) {
  16129. state.disable( _gl.CULL_FACE );
  16130. } else {
  16131. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  16132. _gl.frontFace( _gl.CW );
  16133. } else {
  16134. _gl.frontFace( _gl.CCW );
  16135. }
  16136. if ( cullFace === THREE.CullFaceBack ) {
  16137. _gl.cullFace( _gl.BACK );
  16138. } else if ( cullFace === THREE.CullFaceFront ) {
  16139. _gl.cullFace( _gl.FRONT );
  16140. } else {
  16141. _gl.cullFace( _gl.FRONT_AND_BACK );
  16142. }
  16143. state.enable( _gl.CULL_FACE );
  16144. }
  16145. };
  16146. // Textures
  16147. function allocTextureUnit() {
  16148. var textureUnit = _usedTextureUnits;
  16149. if ( textureUnit >= capabilities.maxTextures ) {
  16150. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  16151. }
  16152. _usedTextureUnits += 1;
  16153. return textureUnit;
  16154. }
  16155. function setTextureParameters ( textureType, texture, isPowerOfTwoImage ) {
  16156. var extension;
  16157. if ( isPowerOfTwoImage ) {
  16158. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  16159. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  16160. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  16161. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  16162. } else {
  16163. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  16164. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  16165. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) {
  16166. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  16167. }
  16168. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  16169. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  16170. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) {
  16171. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  16172. }
  16173. }
  16174. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16175. if ( extension ) {
  16176. if ( texture.type === THREE.FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  16177. if ( texture.type === THREE.HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  16178. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  16179. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _this.getMaxAnisotropy() ) );
  16180. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  16181. }
  16182. }
  16183. }
  16184. function uploadTexture( textureProperties, texture, slot ) {
  16185. if ( textureProperties.__webglInit === undefined ) {
  16186. textureProperties.__webglInit = true;
  16187. texture.addEventListener( 'dispose', onTextureDispose );
  16188. textureProperties.__webglTexture = _gl.createTexture();
  16189. _infoMemory.textures ++;
  16190. }
  16191. state.activeTexture( _gl.TEXTURE0 + slot );
  16192. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16193. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16194. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  16195. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  16196. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  16197. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  16198. image = makePowerOfTwo( image );
  16199. }
  16200. var isPowerOfTwoImage = isPowerOfTwo( image ),
  16201. glFormat = paramThreeToGL( texture.format ),
  16202. glType = paramThreeToGL( texture.type );
  16203. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  16204. var mipmap, mipmaps = texture.mipmaps;
  16205. if ( texture instanceof THREE.DepthTexture ) {
  16206. // populate depth texture with dummy data
  16207. var internalFormat = _gl.DEPTH_COMPONENT;
  16208. if ( texture.type === THREE.FloatType ) {
  16209. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  16210. internalFormat = _gl.DEPTH_COMPONENT32F;
  16211. } else if ( _isWebGL2 ) {
  16212. // WebGL 2.0 requires signed internalformat for glTexImage2D
  16213. internalFormat = _gl.DEPTH_COMPONENT16;
  16214. }
  16215. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  16216. } else if ( texture instanceof THREE.DataTexture ) {
  16217. // use manually created mipmaps if available
  16218. // if there are no manual mipmaps
  16219. // set 0 level mipmap and then use GL to generate other mipmap levels
  16220. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16221. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16222. mipmap = mipmaps[ i ];
  16223. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16224. }
  16225. texture.generateMipmaps = false;
  16226. } else {
  16227. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  16228. }
  16229. } else if ( texture instanceof THREE.CompressedTexture ) {
  16230. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16231. mipmap = mipmaps[ i ];
  16232. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16233. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16234. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16235. } else {
  16236. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  16237. }
  16238. } else {
  16239. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16240. }
  16241. }
  16242. } else {
  16243. // regular Texture (image, video, canvas)
  16244. // use manually created mipmaps if available
  16245. // if there are no manual mipmaps
  16246. // set 0 level mipmap and then use GL to generate other mipmap levels
  16247. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  16248. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  16249. mipmap = mipmaps[ i ];
  16250. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  16251. }
  16252. texture.generateMipmaps = false;
  16253. } else {
  16254. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  16255. }
  16256. }
  16257. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16258. textureProperties.__version = texture.version;
  16259. if ( texture.onUpdate ) texture.onUpdate( texture );
  16260. }
  16261. function setTexture2D( texture, slot ) {
  16262. if ( texture instanceof THREE.WebGLRenderTarget ) texture = texture.texture;
  16263. var textureProperties = properties.get( texture );
  16264. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16265. var image = texture.image;
  16266. if ( image === undefined ) {
  16267. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  16268. return;
  16269. }
  16270. if ( image.complete === false ) {
  16271. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  16272. return;
  16273. }
  16274. uploadTexture( textureProperties, texture, slot );
  16275. return;
  16276. }
  16277. state.activeTexture( _gl.TEXTURE0 + slot );
  16278. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16279. }
  16280. function clampToMaxSize ( image, maxSize ) {
  16281. if ( image.width > maxSize || image.height > maxSize ) {
  16282. // Warning: Scaling through the canvas will only work with images that use
  16283. // premultiplied alpha.
  16284. var scale = maxSize / Math.max( image.width, image.height );
  16285. var canvas = document.createElement( 'canvas' );
  16286. canvas.width = Math.floor( image.width * scale );
  16287. canvas.height = Math.floor( image.height * scale );
  16288. var context = canvas.getContext( '2d' );
  16289. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  16290. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16291. return canvas;
  16292. }
  16293. return image;
  16294. }
  16295. function isPowerOfTwo( image ) {
  16296. return THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height );
  16297. }
  16298. function textureNeedsPowerOfTwo( texture ) {
  16299. if ( texture.wrapS !== THREE.ClampToEdgeWrapping || texture.wrapT !== THREE.ClampToEdgeWrapping ) return true;
  16300. if ( texture.minFilter !== THREE.NearestFilter && texture.minFilter !== THREE.LinearFilter ) return true;
  16301. return false;
  16302. }
  16303. function makePowerOfTwo( image ) {
  16304. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  16305. var canvas = document.createElement( 'canvas' );
  16306. canvas.width = THREE.Math.nearestPowerOfTwo( image.width );
  16307. canvas.height = THREE.Math.nearestPowerOfTwo( image.height );
  16308. var context = canvas.getContext( '2d' );
  16309. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  16310. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  16311. return canvas;
  16312. }
  16313. return image;
  16314. }
  16315. function setCubeTexture ( texture, slot ) {
  16316. var textureProperties = properties.get( texture );
  16317. if ( texture.image.length === 6 ) {
  16318. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  16319. if ( ! textureProperties.__image__webglTextureCube ) {
  16320. texture.addEventListener( 'dispose', onTextureDispose );
  16321. textureProperties.__image__webglTextureCube = _gl.createTexture();
  16322. _infoMemory.textures ++;
  16323. }
  16324. state.activeTexture( _gl.TEXTURE0 + slot );
  16325. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16326. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  16327. var isCompressed = texture instanceof THREE.CompressedTexture;
  16328. var isDataTexture = texture.image[ 0 ] instanceof THREE.DataTexture;
  16329. var cubeImage = [];
  16330. for ( var i = 0; i < 6; i ++ ) {
  16331. if ( _this.autoScaleCubemaps && ! isCompressed && ! isDataTexture ) {
  16332. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  16333. } else {
  16334. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  16335. }
  16336. }
  16337. var image = cubeImage[ 0 ],
  16338. isPowerOfTwoImage = isPowerOfTwo( image ),
  16339. glFormat = paramThreeToGL( texture.format ),
  16340. glType = paramThreeToGL( texture.type );
  16341. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  16342. for ( var i = 0; i < 6; i ++ ) {
  16343. if ( ! isCompressed ) {
  16344. if ( isDataTexture ) {
  16345. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  16346. } else {
  16347. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  16348. }
  16349. } else {
  16350. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  16351. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  16352. mipmap = mipmaps[ j ];
  16353. if ( texture.format !== THREE.RGBAFormat && texture.format !== THREE.RGBFormat ) {
  16354. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  16355. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  16356. } else {
  16357. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setCubeTexture()" );
  16358. }
  16359. } else {
  16360. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  16361. }
  16362. }
  16363. }
  16364. }
  16365. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  16366. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16367. }
  16368. textureProperties.__version = texture.version;
  16369. if ( texture.onUpdate ) texture.onUpdate( texture );
  16370. } else {
  16371. state.activeTexture( _gl.TEXTURE0 + slot );
  16372. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  16373. }
  16374. }
  16375. }
  16376. function setCubeTextureDynamic ( texture, slot ) {
  16377. state.activeTexture( _gl.TEXTURE0 + slot );
  16378. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  16379. }
  16380. var setTextureWarned = false;
  16381. this.setTexture = function( texture, slot ) {
  16382. if ( ! setTextureWarned ) {
  16383. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, " +
  16384. "use setTexture2D instead." );
  16385. setTextureWarned = true;
  16386. }
  16387. setTexture2D( texture, slot );
  16388. };
  16389. this.allocTextureUnit = allocTextureUnit;
  16390. this.setTexture2D = setTexture2D;
  16391. this.setTextureCube = function( texture, slot ) {
  16392. if ( texture instanceof THREE.CubeTexture ||
  16393. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  16394. // CompressedTexture can have Array in image :/
  16395. setCubeTexture( texture, slot );
  16396. } else {
  16397. // assumed: texture instanceof THREE.WebGLRenderTargetCube
  16398. setCubeTextureDynamic( texture.texture, slot );
  16399. }
  16400. };
  16401. // Render targets
  16402. // Setup storage for target texture and bind it to correct framebuffer
  16403. function setupFrameBufferTexture ( framebuffer, renderTarget, attachment, textureTarget ) {
  16404. var glFormat = paramThreeToGL( renderTarget.texture.format );
  16405. var glType = paramThreeToGL( renderTarget.texture.type );
  16406. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  16407. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16408. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  16409. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16410. }
  16411. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  16412. function setupRenderBufferStorage ( renderbuffer, renderTarget ) {
  16413. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  16414. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  16415. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  16416. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16417. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  16418. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  16419. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  16420. } else {
  16421. // FIXME: We don't support !depth !stencil
  16422. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  16423. }
  16424. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  16425. }
  16426. // Setup resources for a Depth Texture for a FBO (needs an extension)
  16427. function setupDepthTexture ( framebuffer, renderTarget ) {
  16428. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16429. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  16430. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16431. if ( !( renderTarget.depthTexture instanceof THREE.DepthTexture ) ) {
  16432. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  16433. }
  16434. // upload an empty depth texture with framebuffer size
  16435. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  16436. renderTarget.depthTexture.image.width !== renderTarget.width ||
  16437. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  16438. renderTarget.depthTexture.image.width = renderTarget.width;
  16439. renderTarget.depthTexture.image.height = renderTarget.height;
  16440. renderTarget.depthTexture.needsUpdate = true;
  16441. }
  16442. _this.setTexture( renderTarget.depthTexture, 0 );
  16443. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  16444. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  16445. }
  16446. // Setup GL resources for a non-texture depth buffer
  16447. function setupDepthRenderbuffer( renderTarget ) {
  16448. var renderTargetProperties = properties.get( renderTarget );
  16449. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16450. if ( renderTarget.depthTexture ) {
  16451. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  16452. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  16453. } else {
  16454. if ( isCube ) {
  16455. renderTargetProperties.__webglDepthbuffer = [];
  16456. for ( var i = 0; i < 6; i ++ ) {
  16457. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  16458. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  16459. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  16460. }
  16461. } else {
  16462. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  16463. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  16464. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  16465. }
  16466. }
  16467. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  16468. }
  16469. // Set up GL resources for the render target
  16470. function setupRenderTarget( renderTarget ) {
  16471. var renderTargetProperties = properties.get( renderTarget );
  16472. var textureProperties = properties.get( renderTarget.texture );
  16473. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  16474. textureProperties.__webglTexture = _gl.createTexture();
  16475. _infoMemory.textures ++;
  16476. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16477. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height );
  16478. // Setup framebuffer
  16479. if ( isCube ) {
  16480. renderTargetProperties.__webglFramebuffer = [];
  16481. for ( var i = 0; i < 6; i ++ ) {
  16482. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  16483. }
  16484. } else {
  16485. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  16486. }
  16487. // Setup color buffer
  16488. if ( isCube ) {
  16489. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  16490. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  16491. for ( var i = 0; i < 6; i ++ ) {
  16492. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  16493. }
  16494. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  16495. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  16496. } else {
  16497. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  16498. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  16499. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  16500. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  16501. state.bindTexture( _gl.TEXTURE_2D, null );
  16502. }
  16503. // Setup depth and stencil buffers
  16504. if ( renderTarget.depthBuffer ) {
  16505. setupDepthRenderbuffer( renderTarget );
  16506. }
  16507. }
  16508. this.getCurrentRenderTarget = function() {
  16509. return _currentRenderTarget;
  16510. };
  16511. this.setRenderTarget = function ( renderTarget ) {
  16512. _currentRenderTarget = renderTarget;
  16513. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  16514. setupRenderTarget( renderTarget );
  16515. }
  16516. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  16517. var framebuffer;
  16518. if ( renderTarget ) {
  16519. var renderTargetProperties = properties.get( renderTarget );
  16520. if ( isCube ) {
  16521. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  16522. } else {
  16523. framebuffer = renderTargetProperties.__webglFramebuffer;
  16524. }
  16525. _currentScissor.copy( renderTarget.scissor );
  16526. _currentScissorTest = renderTarget.scissorTest;
  16527. _currentViewport.copy( renderTarget.viewport );
  16528. } else {
  16529. framebuffer = null;
  16530. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  16531. _currentScissorTest = _scissorTest;
  16532. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  16533. }
  16534. if ( _currentFramebuffer !== framebuffer ) {
  16535. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16536. _currentFramebuffer = framebuffer;
  16537. }
  16538. state.scissor( _currentScissor );
  16539. state.setScissorTest( _currentScissorTest );
  16540. state.viewport( _currentViewport );
  16541. if ( isCube ) {
  16542. var textureProperties = properties.get( renderTarget.texture );
  16543. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  16544. }
  16545. };
  16546. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  16547. if ( renderTarget instanceof THREE.WebGLRenderTarget === false ) {
  16548. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  16549. return;
  16550. }
  16551. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  16552. if ( framebuffer ) {
  16553. var restore = false;
  16554. if ( framebuffer !== _currentFramebuffer ) {
  16555. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  16556. restore = true;
  16557. }
  16558. try {
  16559. var texture = renderTarget.texture;
  16560. if ( texture.format !== THREE.RGBAFormat && paramThreeToGL( texture.format ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  16561. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  16562. return;
  16563. }
  16564. if ( texture.type !== THREE.UnsignedByteType &&
  16565. paramThreeToGL( texture.type ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) &&
  16566. ! ( texture.type === THREE.FloatType && extensions.get( 'WEBGL_color_buffer_float' ) ) &&
  16567. ! ( texture.type === THREE.HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  16568. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  16569. return;
  16570. }
  16571. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  16572. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  16573. if ( ( x > 0 && x <= ( renderTarget.width - width ) ) && ( y > 0 && y <= ( renderTarget.height - height ) ) ) {
  16574. _gl.readPixels( x, y, width, height, paramThreeToGL( texture.format ), paramThreeToGL( texture.type ), buffer );
  16575. }
  16576. } else {
  16577. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  16578. }
  16579. } finally {
  16580. if ( restore ) {
  16581. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  16582. }
  16583. }
  16584. }
  16585. };
  16586. function updateRenderTargetMipmap( renderTarget ) {
  16587. var target = renderTarget instanceof THREE.WebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  16588. var texture = properties.get( renderTarget.texture ).__webglTexture;
  16589. state.bindTexture( target, texture );
  16590. _gl.generateMipmap( target );
  16591. state.bindTexture( target, null );
  16592. }
  16593. // Fallback filters for non-power-of-2 textures
  16594. function filterFallback ( f ) {
  16595. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  16596. return _gl.NEAREST;
  16597. }
  16598. return _gl.LINEAR;
  16599. }
  16600. // Map three.js constants to WebGL constants
  16601. function paramThreeToGL ( p ) {
  16602. var extension;
  16603. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  16604. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  16605. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  16606. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  16607. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  16608. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  16609. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  16610. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  16611. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  16612. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  16613. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  16614. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  16615. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  16616. if ( p === THREE.ByteType ) return _gl.BYTE;
  16617. if ( p === THREE.ShortType ) return _gl.SHORT;
  16618. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  16619. if ( p === THREE.IntType ) return _gl.INT;
  16620. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  16621. if ( p === THREE.FloatType ) return _gl.FLOAT;
  16622. extension = extensions.get( 'OES_texture_half_float' );
  16623. if ( extension !== null ) {
  16624. if ( p === THREE.HalfFloatType ) return extension.HALF_FLOAT_OES;
  16625. }
  16626. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  16627. if ( p === THREE.RGBFormat ) return _gl.RGB;
  16628. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  16629. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  16630. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  16631. if ( p === THREE.DepthFormat ) return _gl.DEPTH_COMPONENT;
  16632. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  16633. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  16634. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  16635. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  16636. if ( p === THREE.OneFactor ) return _gl.ONE;
  16637. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  16638. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  16639. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  16640. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  16641. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  16642. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  16643. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  16644. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  16645. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  16646. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  16647. if ( extension !== null ) {
  16648. if ( p === THREE.RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  16649. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  16650. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  16651. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  16652. }
  16653. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  16654. if ( extension !== null ) {
  16655. if ( p === THREE.RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  16656. if ( p === THREE.RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  16657. if ( p === THREE.RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  16658. if ( p === THREE.RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  16659. }
  16660. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  16661. if ( extension !== null ) {
  16662. if ( p === THREE.RGB_ETC1_Format ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  16663. }
  16664. extension = extensions.get( 'EXT_blend_minmax' );
  16665. if ( extension !== null ) {
  16666. if ( p === THREE.MinEquation ) return extension.MIN_EXT;
  16667. if ( p === THREE.MaxEquation ) return extension.MAX_EXT;
  16668. }
  16669. return 0;
  16670. }
  16671. };
  16672. // File:src/renderers/WebGLRenderTarget.js
  16673. /**
  16674. * @author szimek / https://github.com/szimek/
  16675. * @author alteredq / http://alteredqualia.com/
  16676. * @author Marius Kintel / https://github.com/kintel
  16677. */
  16678. /*
  16679. In options, we can specify:
  16680. * Texture parameters for an auto-generated target texture
  16681. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  16682. */
  16683. THREE.WebGLRenderTarget = function ( width, height, options ) {
  16684. this.uuid = THREE.Math.generateUUID();
  16685. this.width = width;
  16686. this.height = height;
  16687. this.scissor = new THREE.Vector4( 0, 0, width, height );
  16688. this.scissorTest = false;
  16689. this.viewport = new THREE.Vector4( 0, 0, width, height );
  16690. options = options || {};
  16691. if ( options.minFilter === undefined ) options.minFilter = THREE.LinearFilter;
  16692. this.texture = new THREE.Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  16693. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  16694. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  16695. this.depthTexture = null;
  16696. };
  16697. THREE.WebGLRenderTarget.prototype = {
  16698. constructor: THREE.WebGLRenderTarget,
  16699. setSize: function ( width, height ) {
  16700. if ( this.width !== width || this.height !== height ) {
  16701. this.width = width;
  16702. this.height = height;
  16703. this.dispose();
  16704. }
  16705. this.viewport.set( 0, 0, width, height );
  16706. this.scissor.set( 0, 0, width, height );
  16707. },
  16708. clone: function () {
  16709. return new this.constructor().copy( this );
  16710. },
  16711. copy: function ( source ) {
  16712. this.width = source.width;
  16713. this.height = source.height;
  16714. this.viewport.copy( source.viewport );
  16715. this.texture = source.texture.clone();
  16716. this.depthBuffer = source.depthBuffer;
  16717. this.stencilBuffer = source.stencilBuffer;
  16718. this.depthTexture = source.depthTexture;
  16719. return this;
  16720. },
  16721. dispose: function () {
  16722. this.dispatchEvent( { type: 'dispose' } );
  16723. }
  16724. };
  16725. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  16726. // File:src/renderers/WebGLRenderTargetCube.js
  16727. /**
  16728. * @author alteredq / http://alteredqualia.com
  16729. */
  16730. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  16731. THREE.WebGLRenderTarget.call( this, width, height, options );
  16732. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16733. this.activeMipMapLevel = 0;
  16734. };
  16735. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16736. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  16737. // File:src/renderers/webgl/WebGLBufferRenderer.js
  16738. /**
  16739. * @author mrdoob / http://mrdoob.com/
  16740. */
  16741. THREE.WebGLBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16742. var mode;
  16743. function setMode( value ) {
  16744. mode = value;
  16745. }
  16746. function render( start, count ) {
  16747. _gl.drawArrays( mode, start, count );
  16748. _infoRender.calls ++;
  16749. _infoRender.vertices += count;
  16750. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16751. }
  16752. function renderInstances( geometry ) {
  16753. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16754. if ( extension === null ) {
  16755. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16756. return;
  16757. }
  16758. var position = geometry.attributes.position;
  16759. var count = 0;
  16760. if ( position instanceof THREE.InterleavedBufferAttribute ) {
  16761. count = position.data.count;
  16762. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  16763. } else {
  16764. count = position.count;
  16765. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  16766. }
  16767. _infoRender.calls ++;
  16768. _infoRender.vertices += count * geometry.maxInstancedCount;
  16769. if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
  16770. }
  16771. this.setMode = setMode;
  16772. this.render = render;
  16773. this.renderInstances = renderInstances;
  16774. };
  16775. // File:src/renderers/webgl/WebGLIndexedBufferRenderer.js
  16776. /**
  16777. * @author mrdoob / http://mrdoob.com/
  16778. */
  16779. THREE.WebGLIndexedBufferRenderer = function ( _gl, extensions, _infoRender ) {
  16780. var mode;
  16781. function setMode( value ) {
  16782. mode = value;
  16783. }
  16784. var type, size;
  16785. function setIndex( index ) {
  16786. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  16787. type = _gl.UNSIGNED_INT;
  16788. size = 4;
  16789. } else {
  16790. type = _gl.UNSIGNED_SHORT;
  16791. size = 2;
  16792. }
  16793. }
  16794. function render( start, count ) {
  16795. _gl.drawElements( mode, count, type, start * size );
  16796. _infoRender.calls ++;
  16797. _infoRender.vertices += count;
  16798. if ( mode === _gl.TRIANGLES ) _infoRender.faces += count / 3;
  16799. }
  16800. function renderInstances( geometry, start, count ) {
  16801. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16802. if ( extension === null ) {
  16803. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16804. return;
  16805. }
  16806. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  16807. _infoRender.calls ++;
  16808. _infoRender.vertices += count * geometry.maxInstancedCount;
  16809. if ( mode === _gl.TRIANGLES ) _infoRender.faces += geometry.maxInstancedCount * count / 3;
  16810. }
  16811. this.setMode = setMode;
  16812. this.setIndex = setIndex;
  16813. this.render = render;
  16814. this.renderInstances = renderInstances;
  16815. };
  16816. // File:src/renderers/webgl/WebGLExtensions.js
  16817. /**
  16818. * @author mrdoob / http://mrdoob.com/
  16819. */
  16820. THREE.WebGLExtensions = function ( gl ) {
  16821. var extensions = {};
  16822. this.get = function ( name ) {
  16823. if ( extensions[ name ] !== undefined ) {
  16824. return extensions[ name ];
  16825. }
  16826. var extension;
  16827. switch ( name ) {
  16828. case 'WEBGL_depth_texture':
  16829. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  16830. case 'EXT_texture_filter_anisotropic':
  16831. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16832. break;
  16833. case 'WEBGL_compressed_texture_s3tc':
  16834. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16835. break;
  16836. case 'WEBGL_compressed_texture_pvrtc':
  16837. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  16838. break;
  16839. case 'WEBGL_compressed_texture_etc1':
  16840. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  16841. break;
  16842. default:
  16843. extension = gl.getExtension( name );
  16844. }
  16845. if ( extension === null ) {
  16846. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  16847. }
  16848. extensions[ name ] = extension;
  16849. return extension;
  16850. };
  16851. };
  16852. // File:src/renderers/webgl/WebGLCapabilities.js
  16853. THREE.WebGLCapabilities = function ( gl, extensions, parameters ) {
  16854. function getMaxPrecision( precision ) {
  16855. if ( precision === 'highp' ) {
  16856. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  16857. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  16858. return 'highp';
  16859. }
  16860. precision = 'mediump';
  16861. }
  16862. if ( precision === 'mediump' ) {
  16863. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  16864. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  16865. return 'mediump';
  16866. }
  16867. }
  16868. return 'lowp';
  16869. }
  16870. this.getMaxPrecision = getMaxPrecision;
  16871. this.precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  16872. this.logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false;
  16873. this.maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  16874. this.maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  16875. this.maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  16876. this.maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  16877. this.maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16878. this.maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  16879. this.maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  16880. this.maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  16881. this.vertexTextures = this.maxVertexTextures > 0;
  16882. this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  16883. this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
  16884. var _maxPrecision = getMaxPrecision( this.precision );
  16885. if ( _maxPrecision !== this.precision ) {
  16886. console.warn( 'THREE.WebGLRenderer:', this.precision, 'not supported, using', _maxPrecision, 'instead.' );
  16887. this.precision = _maxPrecision;
  16888. }
  16889. if ( this.logarithmicDepthBuffer ) {
  16890. this.logarithmicDepthBuffer = !! extensions.get( 'EXT_frag_depth' );
  16891. }
  16892. };
  16893. // File:src/renderers/webgl/WebGLGeometries.js
  16894. /**
  16895. * @author mrdoob / http://mrdoob.com/
  16896. */
  16897. THREE.WebGLGeometries = function ( gl, properties, info ) {
  16898. var geometries = {};
  16899. function get( object ) {
  16900. var geometry = object.geometry;
  16901. if ( geometries[ geometry.id ] !== undefined ) {
  16902. return geometries[ geometry.id ];
  16903. }
  16904. geometry.addEventListener( 'dispose', onGeometryDispose );
  16905. var buffergeometry;
  16906. if ( geometry instanceof THREE.BufferGeometry ) {
  16907. buffergeometry = geometry;
  16908. } else if ( geometry instanceof THREE.Geometry ) {
  16909. if ( geometry._bufferGeometry === undefined ) {
  16910. geometry._bufferGeometry = new THREE.BufferGeometry().setFromObject( object );
  16911. }
  16912. buffergeometry = geometry._bufferGeometry;
  16913. }
  16914. geometries[ geometry.id ] = buffergeometry;
  16915. info.memory.geometries ++;
  16916. return buffergeometry;
  16917. }
  16918. function onGeometryDispose( event ) {
  16919. var geometry = event.target;
  16920. var buffergeometry = geometries[ geometry.id ];
  16921. if ( buffergeometry.index !== null ) {
  16922. deleteAttribute( buffergeometry.index );
  16923. }
  16924. deleteAttributes( buffergeometry.attributes );
  16925. geometry.removeEventListener( 'dispose', onGeometryDispose );
  16926. delete geometries[ geometry.id ];
  16927. // TODO
  16928. var property = properties.get( geometry );
  16929. if ( property.wireframe ) {
  16930. deleteAttribute( property.wireframe );
  16931. }
  16932. properties.delete( geometry );
  16933. var bufferproperty = properties.get( buffergeometry );
  16934. if ( bufferproperty.wireframe ) {
  16935. deleteAttribute( bufferproperty.wireframe );
  16936. }
  16937. properties.delete( buffergeometry );
  16938. //
  16939. info.memory.geometries --;
  16940. }
  16941. function getAttributeBuffer( attribute ) {
  16942. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16943. return properties.get( attribute.data ).__webglBuffer;
  16944. }
  16945. return properties.get( attribute ).__webglBuffer;
  16946. }
  16947. function deleteAttribute( attribute ) {
  16948. var buffer = getAttributeBuffer( attribute );
  16949. if ( buffer !== undefined ) {
  16950. gl.deleteBuffer( buffer );
  16951. removeAttributeBuffer( attribute );
  16952. }
  16953. }
  16954. function deleteAttributes( attributes ) {
  16955. for ( var name in attributes ) {
  16956. deleteAttribute( attributes[ name ] );
  16957. }
  16958. }
  16959. function removeAttributeBuffer( attribute ) {
  16960. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  16961. properties.delete( attribute.data );
  16962. } else {
  16963. properties.delete( attribute );
  16964. }
  16965. }
  16966. this.get = get;
  16967. };
  16968. // File:src/renderers/webgl/WebGLLights.js
  16969. /**
  16970. * @author mrdoob / http://mrdoob.com/
  16971. */
  16972. THREE.WebGLLights = function () {
  16973. var lights = {};
  16974. this.get = function ( light ) {
  16975. if ( lights[ light.id ] !== undefined ) {
  16976. return lights[ light.id ];
  16977. }
  16978. var uniforms;
  16979. switch ( light.type ) {
  16980. case 'DirectionalLight':
  16981. uniforms = {
  16982. direction: new THREE.Vector3(),
  16983. color: new THREE.Color(),
  16984. shadow: false,
  16985. shadowBias: 0,
  16986. shadowRadius: 1,
  16987. shadowMapSize: new THREE.Vector2()
  16988. };
  16989. break;
  16990. case 'SpotLight':
  16991. uniforms = {
  16992. position: new THREE.Vector3(),
  16993. direction: new THREE.Vector3(),
  16994. color: new THREE.Color(),
  16995. distance: 0,
  16996. coneCos: 0,
  16997. penumbraCos: 0,
  16998. decay: 0,
  16999. shadow: false,
  17000. shadowBias: 0,
  17001. shadowRadius: 1,
  17002. shadowMapSize: new THREE.Vector2()
  17003. };
  17004. break;
  17005. case 'PointLight':
  17006. uniforms = {
  17007. position: new THREE.Vector3(),
  17008. color: new THREE.Color(),
  17009. distance: 0,
  17010. decay: 0,
  17011. shadow: false,
  17012. shadowBias: 0,
  17013. shadowRadius: 1,
  17014. shadowMapSize: new THREE.Vector2()
  17015. };
  17016. break;
  17017. case 'HemisphereLight':
  17018. uniforms = {
  17019. direction: new THREE.Vector3(),
  17020. skyColor: new THREE.Color(),
  17021. groundColor: new THREE.Color()
  17022. };
  17023. break;
  17024. }
  17025. lights[ light.id ] = uniforms;
  17026. return uniforms;
  17027. };
  17028. };
  17029. // File:src/renderers/webgl/WebGLObjects.js
  17030. /**
  17031. * @author mrdoob / http://mrdoob.com/
  17032. */
  17033. THREE.WebGLObjects = function ( gl, properties, info ) {
  17034. var geometries = new THREE.WebGLGeometries( gl, properties, info );
  17035. //
  17036. function update( object ) {
  17037. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  17038. var geometry = geometries.get( object );
  17039. if ( object.geometry instanceof THREE.Geometry ) {
  17040. geometry.updateFromObject( object );
  17041. }
  17042. var index = geometry.index;
  17043. var attributes = geometry.attributes;
  17044. if ( index !== null ) {
  17045. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  17046. }
  17047. for ( var name in attributes ) {
  17048. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  17049. }
  17050. // morph targets
  17051. var morphAttributes = geometry.morphAttributes;
  17052. for ( var name in morphAttributes ) {
  17053. var array = morphAttributes[ name ];
  17054. for ( var i = 0, l = array.length; i < l; i ++ ) {
  17055. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  17056. }
  17057. }
  17058. return geometry;
  17059. }
  17060. function updateAttribute( attribute, bufferType ) {
  17061. var data = ( attribute instanceof THREE.InterleavedBufferAttribute ) ? attribute.data : attribute;
  17062. var attributeProperties = properties.get( data );
  17063. if ( attributeProperties.__webglBuffer === undefined ) {
  17064. createBuffer( attributeProperties, data, bufferType );
  17065. } else if ( attributeProperties.version !== data.version ) {
  17066. updateBuffer( attributeProperties, data, bufferType );
  17067. }
  17068. }
  17069. function createBuffer( attributeProperties, data, bufferType ) {
  17070. attributeProperties.__webglBuffer = gl.createBuffer();
  17071. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  17072. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  17073. gl.bufferData( bufferType, data.array, usage );
  17074. attributeProperties.version = data.version;
  17075. }
  17076. function updateBuffer( attributeProperties, data, bufferType ) {
  17077. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  17078. if ( data.dynamic === false || data.updateRange.count === - 1 ) {
  17079. // Not using update ranges
  17080. gl.bufferSubData( bufferType, 0, data.array );
  17081. } else if ( data.updateRange.count === 0 ) {
  17082. console.error( 'THREE.WebGLObjects.updateBuffer: dynamic THREE.BufferAttribute marked as needsUpdate but updateRange.count is 0, ensure you are using set methods or updating manually.' );
  17083. } else {
  17084. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  17085. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  17086. data.updateRange.count = 0; // reset range
  17087. }
  17088. attributeProperties.version = data.version;
  17089. }
  17090. function getAttributeBuffer( attribute ) {
  17091. if ( attribute instanceof THREE.InterleavedBufferAttribute ) {
  17092. return properties.get( attribute.data ).__webglBuffer;
  17093. }
  17094. return properties.get( attribute ).__webglBuffer;
  17095. }
  17096. function getWireframeAttribute( geometry ) {
  17097. var property = properties.get( geometry );
  17098. if ( property.wireframe !== undefined ) {
  17099. return property.wireframe;
  17100. }
  17101. var indices = [];
  17102. var index = geometry.index;
  17103. var attributes = geometry.attributes;
  17104. var position = attributes.position;
  17105. // console.time( 'wireframe' );
  17106. if ( index !== null ) {
  17107. var edges = {};
  17108. var array = index.array;
  17109. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  17110. var a = array[ i + 0 ];
  17111. var b = array[ i + 1 ];
  17112. var c = array[ i + 2 ];
  17113. if ( checkEdge( edges, a, b ) ) indices.push( a, b );
  17114. if ( checkEdge( edges, b, c ) ) indices.push( b, c );
  17115. if ( checkEdge( edges, c, a ) ) indices.push( c, a );
  17116. }
  17117. } else {
  17118. var array = attributes.position.array;
  17119. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17120. var a = i + 0;
  17121. var b = i + 1;
  17122. var c = i + 2;
  17123. indices.push( a, b, b, c, c, a );
  17124. }
  17125. }
  17126. // console.timeEnd( 'wireframe' );
  17127. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  17128. var attribute = new THREE.BufferAttribute( new TypeArray( indices ), 1 );
  17129. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  17130. property.wireframe = attribute;
  17131. return attribute;
  17132. }
  17133. function checkEdge( edges, a, b ) {
  17134. if ( a > b ) {
  17135. var tmp = a;
  17136. a = b;
  17137. b = tmp;
  17138. }
  17139. var list = edges[ a ];
  17140. if ( list === undefined ) {
  17141. edges[ a ] = [ b ];
  17142. return true;
  17143. } else if ( list.indexOf( b ) === -1 ) {
  17144. list.push( b );
  17145. return true;
  17146. }
  17147. return false;
  17148. }
  17149. this.getAttributeBuffer = getAttributeBuffer;
  17150. this.getWireframeAttribute = getWireframeAttribute;
  17151. this.update = update;
  17152. };
  17153. // File:src/renderers/webgl/WebGLProgram.js
  17154. THREE.WebGLProgram = ( function () {
  17155. var programIdCount = 0;
  17156. function getEncodingComponents( encoding ) {
  17157. switch ( encoding ) {
  17158. case THREE.LinearEncoding:
  17159. return [ 'Linear','( value )' ];
  17160. case THREE.sRGBEncoding:
  17161. return [ 'sRGB','( value )' ];
  17162. case THREE.RGBEEncoding:
  17163. return [ 'RGBE','( value )' ];
  17164. case THREE.RGBM7Encoding:
  17165. return [ 'RGBM','( value, 7.0 )' ];
  17166. case THREE.RGBM16Encoding:
  17167. return [ 'RGBM','( value, 16.0 )' ];
  17168. case THREE.RGBDEncoding:
  17169. return [ 'RGBD','( value, 256.0 )' ];
  17170. case THREE.GammaEncoding:
  17171. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  17172. default:
  17173. throw new Error( 'unsupported encoding: ' + encoding );
  17174. }
  17175. }
  17176. function getTexelDecodingFunction( functionName, encoding ) {
  17177. var components = getEncodingComponents( encoding );
  17178. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  17179. }
  17180. function getTexelEncodingFunction( functionName, encoding ) {
  17181. var components = getEncodingComponents( encoding );
  17182. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  17183. }
  17184. function getToneMappingFunction( functionName, toneMapping ) {
  17185. var toneMappingName;
  17186. switch ( toneMapping ) {
  17187. case THREE.LinearToneMapping:
  17188. toneMappingName = "Linear";
  17189. break;
  17190. case THREE.ReinhardToneMapping:
  17191. toneMappingName = "Reinhard";
  17192. break;
  17193. case THREE.Uncharted2ToneMapping:
  17194. toneMappingName = "Uncharted2";
  17195. break;
  17196. case THREE.CineonToneMapping:
  17197. toneMappingName = "OptimizedCineon";
  17198. break;
  17199. default:
  17200. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  17201. }
  17202. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  17203. }
  17204. function generateExtensions( extensions, parameters, rendererExtensions ) {
  17205. extensions = extensions || {};
  17206. var chunks = [
  17207. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  17208. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  17209. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  17210. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : '',
  17211. ];
  17212. return chunks.filter( filterEmptyLine ).join( '\n' );
  17213. }
  17214. function generateDefines( defines ) {
  17215. var chunks = [];
  17216. for ( var name in defines ) {
  17217. var value = defines[ name ];
  17218. if ( value === false ) continue;
  17219. chunks.push( '#define ' + name + ' ' + value );
  17220. }
  17221. return chunks.join( '\n' );
  17222. }
  17223. function fetchAttributeLocations( gl, program, identifiers ) {
  17224. var attributes = {};
  17225. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  17226. for ( var i = 0; i < n; i ++ ) {
  17227. var info = gl.getActiveAttrib( program, i );
  17228. var name = info.name;
  17229. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  17230. attributes[ name ] = gl.getAttribLocation( program, name );
  17231. }
  17232. return attributes;
  17233. }
  17234. function filterEmptyLine( string ) {
  17235. return string !== '';
  17236. }
  17237. function replaceLightNums( string, parameters ) {
  17238. return string
  17239. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  17240. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  17241. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  17242. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  17243. }
  17244. function parseIncludes( string ) {
  17245. var pattern = /#include +<([\w\d.]+)>/g;
  17246. function replace( match, include ) {
  17247. var replace = THREE.ShaderChunk[ include ];
  17248. if ( replace === undefined ) {
  17249. throw new Error( 'Can not resolve #include <' + include + '>' );
  17250. }
  17251. return parseIncludes( replace );
  17252. }
  17253. return string.replace( pattern, replace );
  17254. }
  17255. function unrollLoops( string ) {
  17256. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  17257. function replace( match, start, end, snippet ) {
  17258. var unroll = '';
  17259. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  17260. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  17261. }
  17262. return unroll;
  17263. }
  17264. return string.replace( pattern, replace );
  17265. }
  17266. return function WebGLProgram( renderer, code, material, parameters ) {
  17267. var gl = renderer.context;
  17268. var extensions = material.extensions;
  17269. var defines = material.defines;
  17270. var vertexShader = material.__webglShader.vertexShader;
  17271. var fragmentShader = material.__webglShader.fragmentShader;
  17272. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  17273. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  17274. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  17275. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  17276. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  17277. }
  17278. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17279. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  17280. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17281. if ( parameters.envMap ) {
  17282. switch ( material.envMap.mapping ) {
  17283. case THREE.CubeReflectionMapping:
  17284. case THREE.CubeRefractionMapping:
  17285. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  17286. break;
  17287. case THREE.CubeUVReflectionMapping:
  17288. case THREE.CubeUVRefractionMapping:
  17289. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  17290. break;
  17291. case THREE.EquirectangularReflectionMapping:
  17292. case THREE.EquirectangularRefractionMapping:
  17293. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  17294. break;
  17295. case THREE.SphericalReflectionMapping:
  17296. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  17297. break;
  17298. }
  17299. switch ( material.envMap.mapping ) {
  17300. case THREE.CubeRefractionMapping:
  17301. case THREE.EquirectangularRefractionMapping:
  17302. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  17303. break;
  17304. }
  17305. switch ( material.combine ) {
  17306. case THREE.MultiplyOperation:
  17307. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  17308. break;
  17309. case THREE.MixOperation:
  17310. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  17311. break;
  17312. case THREE.AddOperation:
  17313. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  17314. break;
  17315. }
  17316. }
  17317. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  17318. // console.log( 'building new program ' );
  17319. //
  17320. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  17321. var customDefines = generateDefines( defines );
  17322. //
  17323. var program = gl.createProgram();
  17324. var prefixVertex, prefixFragment;
  17325. if ( material instanceof THREE.RawShaderMaterial ) {
  17326. prefixVertex = '';
  17327. prefixFragment = '';
  17328. } else {
  17329. prefixVertex = [
  17330. 'precision ' + parameters.precision + ' float;',
  17331. 'precision ' + parameters.precision + ' int;',
  17332. '#define SHADER_NAME ' + material.__webglShader.name,
  17333. customDefines,
  17334. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  17335. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17336. '#define MAX_BONES ' + parameters.maxBones,
  17337. parameters.map ? '#define USE_MAP' : '',
  17338. parameters.envMap ? '#define USE_ENVMAP' : '',
  17339. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17340. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17341. parameters.aoMap ? '#define USE_AOMAP' : '',
  17342. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17343. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17344. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17345. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  17346. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17347. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17348. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17349. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17350. parameters.vertexColors ? '#define USE_COLOR' : '',
  17351. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17352. parameters.skinning ? '#define USE_SKINNING' : '',
  17353. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  17354. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  17355. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  17356. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17357. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17358. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  17359. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17360. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17361. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  17362. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17363. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17364. 'uniform mat4 modelMatrix;',
  17365. 'uniform mat4 modelViewMatrix;',
  17366. 'uniform mat4 projectionMatrix;',
  17367. 'uniform mat4 viewMatrix;',
  17368. 'uniform mat3 normalMatrix;',
  17369. 'uniform vec3 cameraPosition;',
  17370. 'attribute vec3 position;',
  17371. 'attribute vec3 normal;',
  17372. 'attribute vec2 uv;',
  17373. '#ifdef USE_COLOR',
  17374. ' attribute vec3 color;',
  17375. '#endif',
  17376. '#ifdef USE_MORPHTARGETS',
  17377. ' attribute vec3 morphTarget0;',
  17378. ' attribute vec3 morphTarget1;',
  17379. ' attribute vec3 morphTarget2;',
  17380. ' attribute vec3 morphTarget3;',
  17381. ' #ifdef USE_MORPHNORMALS',
  17382. ' attribute vec3 morphNormal0;',
  17383. ' attribute vec3 morphNormal1;',
  17384. ' attribute vec3 morphNormal2;',
  17385. ' attribute vec3 morphNormal3;',
  17386. ' #else',
  17387. ' attribute vec3 morphTarget4;',
  17388. ' attribute vec3 morphTarget5;',
  17389. ' attribute vec3 morphTarget6;',
  17390. ' attribute vec3 morphTarget7;',
  17391. ' #endif',
  17392. '#endif',
  17393. '#ifdef USE_SKINNING',
  17394. ' attribute vec4 skinIndex;',
  17395. ' attribute vec4 skinWeight;',
  17396. '#endif',
  17397. '\n'
  17398. ].filter( filterEmptyLine ).join( '\n' );
  17399. prefixFragment = [
  17400. customExtensions,
  17401. 'precision ' + parameters.precision + ' float;',
  17402. 'precision ' + parameters.precision + ' int;',
  17403. '#define SHADER_NAME ' + material.__webglShader.name,
  17404. customDefines,
  17405. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  17406. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  17407. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  17408. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  17409. parameters.map ? '#define USE_MAP' : '',
  17410. parameters.envMap ? '#define USE_ENVMAP' : '',
  17411. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  17412. parameters.envMap ? '#define ' + envMapModeDefine : '',
  17413. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  17414. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  17415. parameters.aoMap ? '#define USE_AOMAP' : '',
  17416. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  17417. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  17418. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  17419. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  17420. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  17421. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  17422. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  17423. parameters.vertexColors ? '#define USE_COLOR' : '',
  17424. parameters.flatShading ? '#define FLAT_SHADED' : '',
  17425. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  17426. parameters.flipSided ? '#define FLIP_SIDED' : '',
  17427. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  17428. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  17429. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  17430. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  17431. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  17432. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  17433. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  17434. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  17435. 'uniform mat4 viewMatrix;',
  17436. 'uniform vec3 cameraPosition;',
  17437. ( parameters.toneMapping !== THREE.NoToneMapping ) ? "#define TONE_MAPPING" : '',
  17438. ( parameters.toneMapping !== THREE.NoToneMapping ) ? THREE.ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  17439. ( parameters.toneMapping !== THREE.NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  17440. ( parameters.outputEncoding || parameters.mapEncoding || parameters.envMapEncoding || parameters.emissiveMapEncoding ) ? THREE.ShaderChunk[ 'encodings_pars_fragment' ] : '', // this code is required here because it is used by the various encoding/decoding function defined below
  17441. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  17442. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  17443. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  17444. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  17445. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  17446. '\n'
  17447. ].filter( filterEmptyLine ).join( '\n' );
  17448. }
  17449. vertexShader = parseIncludes( vertexShader, parameters );
  17450. vertexShader = replaceLightNums( vertexShader, parameters );
  17451. fragmentShader = parseIncludes( fragmentShader, parameters );
  17452. fragmentShader = replaceLightNums( fragmentShader, parameters );
  17453. if ( material instanceof THREE.ShaderMaterial === false ) {
  17454. vertexShader = unrollLoops( vertexShader );
  17455. fragmentShader = unrollLoops( fragmentShader );
  17456. }
  17457. var vertexGlsl = prefixVertex + vertexShader;
  17458. var fragmentGlsl = prefixFragment + fragmentShader;
  17459. // console.log( '*VERTEX*', vertexGlsl );
  17460. // console.log( '*FRAGMENT*', fragmentGlsl );
  17461. var glVertexShader = THREE.WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  17462. var glFragmentShader = THREE.WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  17463. gl.attachShader( program, glVertexShader );
  17464. gl.attachShader( program, glFragmentShader );
  17465. // Force a particular attribute to index 0.
  17466. if ( material.index0AttributeName !== undefined ) {
  17467. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  17468. } else if ( parameters.morphTargets === true ) {
  17469. // programs with morphTargets displace position out of attribute 0
  17470. gl.bindAttribLocation( program, 0, 'position' );
  17471. }
  17472. gl.linkProgram( program );
  17473. var programLog = gl.getProgramInfoLog( program );
  17474. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  17475. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  17476. var runnable = true;
  17477. var haveDiagnostics = true;
  17478. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  17479. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  17480. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  17481. runnable = false;
  17482. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  17483. } else if ( programLog !== '' ) {
  17484. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  17485. } else if ( vertexLog === '' || fragmentLog === '' ) {
  17486. haveDiagnostics = false;
  17487. }
  17488. if ( haveDiagnostics ) {
  17489. this.diagnostics = {
  17490. runnable: runnable,
  17491. material: material,
  17492. programLog: programLog,
  17493. vertexShader: {
  17494. log: vertexLog,
  17495. prefix: prefixVertex
  17496. },
  17497. fragmentShader: {
  17498. log: fragmentLog,
  17499. prefix: prefixFragment
  17500. }
  17501. };
  17502. }
  17503. // clean up
  17504. gl.deleteShader( glVertexShader );
  17505. gl.deleteShader( glFragmentShader );
  17506. // set up caching for uniform locations
  17507. var cachedUniforms;
  17508. this.getUniforms = function() {
  17509. if ( cachedUniforms === undefined ) {
  17510. cachedUniforms =
  17511. new THREE.WebGLUniforms( gl, program, renderer );
  17512. }
  17513. return cachedUniforms;
  17514. };
  17515. // set up caching for attribute locations
  17516. var cachedAttributes;
  17517. this.getAttributes = function() {
  17518. if ( cachedAttributes === undefined ) {
  17519. cachedAttributes = fetchAttributeLocations( gl, program );
  17520. }
  17521. return cachedAttributes;
  17522. };
  17523. // free resource
  17524. this.destroy = function() {
  17525. gl.deleteProgram( program );
  17526. this.program = undefined;
  17527. };
  17528. // DEPRECATED
  17529. Object.defineProperties( this, {
  17530. uniforms: {
  17531. get: function() {
  17532. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  17533. return this.getUniforms();
  17534. }
  17535. },
  17536. attributes: {
  17537. get: function() {
  17538. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  17539. return this.getAttributes();
  17540. }
  17541. }
  17542. } );
  17543. //
  17544. this.id = programIdCount ++;
  17545. this.code = code;
  17546. this.usedTimes = 1;
  17547. this.program = program;
  17548. this.vertexShader = glVertexShader;
  17549. this.fragmentShader = glFragmentShader;
  17550. return this;
  17551. };
  17552. } )();
  17553. // File:src/renderers/webgl/WebGLPrograms.js
  17554. THREE.WebGLPrograms = function ( renderer, capabilities ) {
  17555. var programs = [];
  17556. var shaderIDs = {
  17557. MeshDepthMaterial: 'depth',
  17558. MeshNormalMaterial: 'normal',
  17559. MeshBasicMaterial: 'basic',
  17560. MeshLambertMaterial: 'lambert',
  17561. MeshPhongMaterial: 'phong',
  17562. MeshStandardMaterial: 'physical',
  17563. MeshPhysicalMaterial: 'physical',
  17564. LineBasicMaterial: 'basic',
  17565. LineDashedMaterial: 'dashed',
  17566. PointsMaterial: 'points'
  17567. };
  17568. var parameterNames = [
  17569. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  17570. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  17571. "roughnessMap", "metalnessMap",
  17572. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  17573. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  17574. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  17575. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  17576. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights",
  17577. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  17578. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "depthPacking"
  17579. ];
  17580. function allocateBones ( object ) {
  17581. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  17582. return 1024;
  17583. } else {
  17584. // default for when object is not specified
  17585. // ( for example when prebuilding shader to be used with multiple objects )
  17586. //
  17587. // - leave some extra space for other uniforms
  17588. // - limit here is ANGLE's 254 max uniform vectors
  17589. // (up to 54 should be safe)
  17590. var nVertexUniforms = capabilities.maxVertexUniforms;
  17591. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  17592. var maxBones = nVertexMatrices;
  17593. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  17594. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  17595. if ( maxBones < object.skeleton.bones.length ) {
  17596. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  17597. }
  17598. }
  17599. return maxBones;
  17600. }
  17601. }
  17602. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  17603. var encoding;
  17604. if ( ! map ) {
  17605. encoding = THREE.LinearEncoding;
  17606. } else if ( map instanceof THREE.Texture ) {
  17607. encoding = map.encoding;
  17608. } else if ( map instanceof THREE.WebGLRenderTarget ) {
  17609. encoding = map.texture.encoding;
  17610. }
  17611. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  17612. if ( encoding === THREE.LinearEncoding && gammaOverrideLinear ) {
  17613. encoding = THREE.GammaEncoding;
  17614. }
  17615. return encoding;
  17616. }
  17617. this.getParameters = function ( material, lights, fog, nClipPlanes, object ) {
  17618. var shaderID = shaderIDs[ material.type ];
  17619. // heuristics to create shader parameters according to lights in the scene
  17620. // (not to blow over maxLights budget)
  17621. var maxBones = allocateBones( object );
  17622. var precision = renderer.getPrecision();
  17623. if ( material.precision !== null ) {
  17624. precision = capabilities.getMaxPrecision( material.precision );
  17625. if ( precision !== material.precision ) {
  17626. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  17627. }
  17628. }
  17629. var parameters = {
  17630. shaderID: shaderID,
  17631. precision: precision,
  17632. supportsVertexTextures: capabilities.vertexTextures,
  17633. outputEncoding: getTextureEncodingFromMap( renderer.getCurrentRenderTarget(), renderer.gammaOutput ),
  17634. map: !! material.map,
  17635. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  17636. envMap: !! material.envMap,
  17637. envMapMode: material.envMap && material.envMap.mapping,
  17638. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  17639. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === THREE.CubeUVReflectionMapping ) || ( material.envMap.mapping === THREE.CubeUVRefractionMapping ) ),
  17640. lightMap: !! material.lightMap,
  17641. aoMap: !! material.aoMap,
  17642. emissiveMap: !! material.emissiveMap,
  17643. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  17644. bumpMap: !! material.bumpMap,
  17645. normalMap: !! material.normalMap,
  17646. displacementMap: !! material.displacementMap,
  17647. roughnessMap: !! material.roughnessMap,
  17648. metalnessMap: !! material.metalnessMap,
  17649. specularMap: !! material.specularMap,
  17650. alphaMap: !! material.alphaMap,
  17651. combine: material.combine,
  17652. vertexColors: material.vertexColors,
  17653. fog: fog,
  17654. useFog: material.fog,
  17655. fogExp: fog instanceof THREE.FogExp2,
  17656. flatShading: material.shading === THREE.FlatShading,
  17657. sizeAttenuation: material.sizeAttenuation,
  17658. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  17659. skinning: material.skinning,
  17660. maxBones: maxBones,
  17661. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  17662. morphTargets: material.morphTargets,
  17663. morphNormals: material.morphNormals,
  17664. maxMorphTargets: renderer.maxMorphTargets,
  17665. maxMorphNormals: renderer.maxMorphNormals,
  17666. numDirLights: lights.directional.length,
  17667. numPointLights: lights.point.length,
  17668. numSpotLights: lights.spot.length,
  17669. numHemiLights: lights.hemi.length,
  17670. numClippingPlanes: nClipPlanes,
  17671. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  17672. shadowMapType: renderer.shadowMap.type,
  17673. toneMapping: renderer.toneMapping,
  17674. physicallyCorrectLights: renderer.physicallyCorrectLights,
  17675. premultipliedAlpha: material.premultipliedAlpha,
  17676. alphaTest: material.alphaTest,
  17677. doubleSided: material.side === THREE.DoubleSide,
  17678. flipSided: material.side === THREE.BackSide,
  17679. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  17680. };
  17681. return parameters;
  17682. };
  17683. this.getProgramCode = function ( material, parameters ) {
  17684. var array = [];
  17685. if ( parameters.shaderID ) {
  17686. array.push( parameters.shaderID );
  17687. } else {
  17688. array.push( material.fragmentShader );
  17689. array.push( material.vertexShader );
  17690. }
  17691. if ( material.defines !== undefined ) {
  17692. for ( var name in material.defines ) {
  17693. array.push( name );
  17694. array.push( material.defines[ name ] );
  17695. }
  17696. }
  17697. for ( var i = 0; i < parameterNames.length; i ++ ) {
  17698. array.push( parameters[ parameterNames[ i ] ] );
  17699. }
  17700. return array.join();
  17701. };
  17702. this.acquireProgram = function ( material, parameters, code ) {
  17703. var program;
  17704. // Check if code has been already compiled
  17705. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  17706. var programInfo = programs[ p ];
  17707. if ( programInfo.code === code ) {
  17708. program = programInfo;
  17709. ++ program.usedTimes;
  17710. break;
  17711. }
  17712. }
  17713. if ( program === undefined ) {
  17714. program = new THREE.WebGLProgram( renderer, code, material, parameters );
  17715. programs.push( program );
  17716. }
  17717. return program;
  17718. };
  17719. this.releaseProgram = function( program ) {
  17720. if ( -- program.usedTimes === 0 ) {
  17721. // Remove from unordered set
  17722. var i = programs.indexOf( program );
  17723. programs[ i ] = programs[ programs.length - 1 ];
  17724. programs.pop();
  17725. // Free WebGL resources
  17726. program.destroy();
  17727. }
  17728. };
  17729. // Exposed for resource monitoring & error feedback via renderer.info:
  17730. this.programs = programs;
  17731. };
  17732. // File:src/renderers/webgl/WebGLProperties.js
  17733. /**
  17734. * @author fordacious / fordacious.github.io
  17735. */
  17736. THREE.WebGLProperties = function () {
  17737. var properties = {};
  17738. this.get = function ( object ) {
  17739. var uuid = object.uuid;
  17740. var map = properties[ uuid ];
  17741. if ( map === undefined ) {
  17742. map = {};
  17743. properties[ uuid ] = map;
  17744. }
  17745. return map;
  17746. };
  17747. this.delete = function ( object ) {
  17748. delete properties[ object.uuid ];
  17749. };
  17750. this.clear = function () {
  17751. properties = {};
  17752. };
  17753. };
  17754. // File:src/renderers/webgl/WebGLShader.js
  17755. THREE.WebGLShader = ( function () {
  17756. function addLineNumbers( string ) {
  17757. var lines = string.split( '\n' );
  17758. for ( var i = 0; i < lines.length; i ++ ) {
  17759. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  17760. }
  17761. return lines.join( '\n' );
  17762. }
  17763. return function WebGLShader( gl, type, string ) {
  17764. var shader = gl.createShader( type );
  17765. gl.shaderSource( shader, string );
  17766. gl.compileShader( shader );
  17767. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  17768. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  17769. }
  17770. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  17771. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  17772. }
  17773. // --enable-privileged-webgl-extension
  17774. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  17775. return shader;
  17776. };
  17777. } )();
  17778. // File:src/renderers/webgl/WebGLShadowMap.js
  17779. /**
  17780. * @author alteredq / http://alteredqualia.com/
  17781. * @author mrdoob / http://mrdoob.com/
  17782. */
  17783. THREE.WebGLShadowMap = function ( _renderer, _lights, _objects ) {
  17784. var _gl = _renderer.context,
  17785. _state = _renderer.state,
  17786. _frustum = new THREE.Frustum(),
  17787. _projScreenMatrix = new THREE.Matrix4(),
  17788. _lightShadows = _lights.shadows,
  17789. _shadowMapSize = new THREE.Vector2(),
  17790. _lookTarget = new THREE.Vector3(),
  17791. _lightPositionWorld = new THREE.Vector3(),
  17792. _renderList = [],
  17793. _MorphingFlag = 1,
  17794. _SkinningFlag = 2,
  17795. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  17796. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  17797. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  17798. _materialCache = {};
  17799. var cubeDirections = [
  17800. new THREE.Vector3( 1, 0, 0 ), new THREE.Vector3( - 1, 0, 0 ), new THREE.Vector3( 0, 0, 1 ),
  17801. new THREE.Vector3( 0, 0, - 1 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, - 1, 0 )
  17802. ];
  17803. var cubeUps = [
  17804. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 1, 0 ),
  17805. new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, 0, 1 ), new THREE.Vector3( 0, 0, - 1 )
  17806. ];
  17807. var cube2DViewPorts = [
  17808. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4(),
  17809. new THREE.Vector4(), new THREE.Vector4(), new THREE.Vector4()
  17810. ];
  17811. // init
  17812. var depthMaterialTemplate = new THREE.MeshDepthMaterial();
  17813. depthMaterialTemplate.depthPacking = THREE.RGBADepthPacking;
  17814. depthMaterialTemplate.clipping = true;
  17815. var distanceShader = THREE.ShaderLib[ "distanceRGBA" ];
  17816. var distanceUniforms = THREE.UniformsUtils.clone( distanceShader.uniforms );
  17817. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  17818. var useMorphing = ( i & _MorphingFlag ) !== 0;
  17819. var useSkinning = ( i & _SkinningFlag ) !== 0;
  17820. var depthMaterial = depthMaterialTemplate.clone();
  17821. depthMaterial.morphTargets = useMorphing;
  17822. depthMaterial.skinning = useSkinning;
  17823. _depthMaterials[ i ] = depthMaterial;
  17824. var distanceMaterial = new THREE.ShaderMaterial( {
  17825. defines: {
  17826. 'USE_SHADOWMAP': ''
  17827. },
  17828. uniforms: distanceUniforms,
  17829. vertexShader: distanceShader.vertexShader,
  17830. fragmentShader: distanceShader.fragmentShader,
  17831. morphTargets: useMorphing,
  17832. skinning: useSkinning,
  17833. clipping: true
  17834. } );
  17835. _distanceMaterials[ i ] = distanceMaterial;
  17836. }
  17837. //
  17838. var scope = this;
  17839. this.enabled = false;
  17840. this.autoUpdate = true;
  17841. this.needsUpdate = false;
  17842. this.type = THREE.PCFShadowMap;
  17843. this.cullFace = THREE.CullFaceFront;
  17844. this.render = function ( scene, camera ) {
  17845. if ( scope.enabled === false ) return;
  17846. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  17847. if ( _lightShadows.length === 0 ) return;
  17848. // Set GL state for depth map.
  17849. _state.clearColor( 1, 1, 1, 1 );
  17850. _state.disable( _gl.BLEND );
  17851. _state.enable( _gl.CULL_FACE );
  17852. _gl.frontFace( _gl.CCW );
  17853. _gl.cullFace( scope.cullFace === THREE.CullFaceFront ? _gl.FRONT : _gl.BACK );
  17854. _state.setDepthTest( true );
  17855. _state.setScissorTest( false );
  17856. // render depth map
  17857. var faceCount, isPointLight;
  17858. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  17859. var light = _lightShadows[ i ];
  17860. var shadow = light.shadow;
  17861. var shadowCamera = shadow.camera;
  17862. _shadowMapSize.copy( shadow.mapSize );
  17863. if ( light instanceof THREE.PointLight ) {
  17864. faceCount = 6;
  17865. isPointLight = true;
  17866. var vpWidth = _shadowMapSize.x;
  17867. var vpHeight = _shadowMapSize.y;
  17868. // These viewports map a cube-map onto a 2D texture with the
  17869. // following orientation:
  17870. //
  17871. // xzXZ
  17872. // y Y
  17873. //
  17874. // X - Positive x direction
  17875. // x - Negative x direction
  17876. // Y - Positive y direction
  17877. // y - Negative y direction
  17878. // Z - Positive z direction
  17879. // z - Negative z direction
  17880. // positive X
  17881. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  17882. // negative X
  17883. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  17884. // positive Z
  17885. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  17886. // negative Z
  17887. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  17888. // positive Y
  17889. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  17890. // negative Y
  17891. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  17892. _shadowMapSize.x *= 4.0;
  17893. _shadowMapSize.y *= 2.0;
  17894. } else {
  17895. faceCount = 1;
  17896. isPointLight = false;
  17897. }
  17898. if ( shadow.map === null ) {
  17899. var pars = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  17900. shadow.map = new THREE.WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  17901. shadowCamera.updateProjectionMatrix();
  17902. }
  17903. if ( shadow instanceof THREE.SpotLightShadow ) {
  17904. shadow.update( light );
  17905. }
  17906. var shadowMap = shadow.map;
  17907. var shadowMatrix = shadow.matrix;
  17908. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  17909. shadowCamera.position.copy( _lightPositionWorld );
  17910. _renderer.setRenderTarget( shadowMap );
  17911. _renderer.clear();
  17912. // render shadow map for each cube face (if omni-directional) or
  17913. // run a single pass if not
  17914. for ( var face = 0; face < faceCount; face ++ ) {
  17915. if ( isPointLight ) {
  17916. _lookTarget.copy( shadowCamera.position );
  17917. _lookTarget.add( cubeDirections[ face ] );
  17918. shadowCamera.up.copy( cubeUps[ face ] );
  17919. shadowCamera.lookAt( _lookTarget );
  17920. var vpDimensions = cube2DViewPorts[ face ];
  17921. _state.viewport( vpDimensions );
  17922. } else {
  17923. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  17924. shadowCamera.lookAt( _lookTarget );
  17925. }
  17926. shadowCamera.updateMatrixWorld();
  17927. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  17928. // compute shadow matrix
  17929. shadowMatrix.set(
  17930. 0.5, 0.0, 0.0, 0.5,
  17931. 0.0, 0.5, 0.0, 0.5,
  17932. 0.0, 0.0, 0.5, 0.5,
  17933. 0.0, 0.0, 0.0, 1.0
  17934. );
  17935. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  17936. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  17937. // update camera matrices and frustum
  17938. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  17939. _frustum.setFromMatrix( _projScreenMatrix );
  17940. // set object matrices & frustum culling
  17941. _renderList.length = 0;
  17942. projectObject( scene, camera, shadowCamera );
  17943. // render shadow map
  17944. // render regular objects
  17945. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  17946. var object = _renderList[ j ];
  17947. var geometry = _objects.update( object );
  17948. var material = object.material;
  17949. if ( material instanceof THREE.MultiMaterial ) {
  17950. var groups = geometry.groups;
  17951. var materials = material.materials;
  17952. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  17953. var group = groups[ k ];
  17954. var groupMaterial = materials[ group.materialIndex ];
  17955. if ( groupMaterial.visible === true ) {
  17956. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  17957. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  17958. }
  17959. }
  17960. } else {
  17961. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  17962. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  17963. }
  17964. }
  17965. }
  17966. }
  17967. // Restore GL state.
  17968. var clearColor = _renderer.getClearColor(),
  17969. clearAlpha = _renderer.getClearAlpha();
  17970. _renderer.setClearColor( clearColor, clearAlpha );
  17971. _state.enable( _gl.BLEND );
  17972. if ( scope.cullFace === THREE.CullFaceFront ) {
  17973. _gl.cullFace( _gl.BACK );
  17974. }
  17975. scope.needsUpdate = false;
  17976. };
  17977. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  17978. var geometry = object.geometry;
  17979. var result = null;
  17980. var materialVariants = _depthMaterials;
  17981. var customMaterial = object.customDepthMaterial;
  17982. if ( isPointLight ) {
  17983. materialVariants = _distanceMaterials;
  17984. customMaterial = object.customDistanceMaterial;
  17985. }
  17986. if ( ! customMaterial ) {
  17987. var useMorphing = geometry.morphTargets !== undefined &&
  17988. geometry.morphTargets.length > 0 && material.morphTargets;
  17989. var useSkinning = object instanceof THREE.SkinnedMesh && material.skinning;
  17990. var variantIndex = 0;
  17991. if ( useMorphing ) variantIndex |= _MorphingFlag;
  17992. if ( useSkinning ) variantIndex |= _SkinningFlag;
  17993. result = materialVariants[ variantIndex ];
  17994. } else {
  17995. result = customMaterial;
  17996. }
  17997. if ( _renderer.localClippingEnabled &&
  17998. material.clipShadows === true &&
  17999. material.clippingPlanes.length !== 0 ) {
  18000. // in this case we need a unique material instance reflecting the
  18001. // appropriate state
  18002. var keyA = result.uuid, keyB = material.uuid;
  18003. var materialsForVariant = _materialCache[ keyA ];
  18004. if ( materialsForVariant === undefined ) {
  18005. materialsForVariant = {};
  18006. _materialCache[ keyA ] = materialsForVariant;
  18007. }
  18008. var cachedMaterial = materialsForVariant[ keyB ];
  18009. if ( cachedMaterial === undefined ) {
  18010. cachedMaterial = result.clone();
  18011. materialsForVariant[ keyB ] = cachedMaterial;
  18012. }
  18013. result = cachedMaterial;
  18014. }
  18015. result.visible = material.visible;
  18016. result.wireframe = material.wireframe;
  18017. result.side = material.side;
  18018. result.clipShadows = material.clipShadows;
  18019. result.clippingPlanes = material.clippingPlanes;
  18020. result.wireframeLinewidth = material.wireframeLinewidth;
  18021. result.linewidth = material.linewidth;
  18022. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  18023. result.uniforms.lightPos.value.copy( lightPositionWorld );
  18024. }
  18025. return result;
  18026. }
  18027. function projectObject( object, camera, shadowCamera ) {
  18028. if ( object.visible === false ) return;
  18029. if ( object.layers.test( camera.layers ) && ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Points ) ) {
  18030. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  18031. var material = object.material;
  18032. if ( material.visible === true ) {
  18033. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  18034. _renderList.push( object );
  18035. }
  18036. }
  18037. }
  18038. var children = object.children;
  18039. for ( var i = 0, l = children.length; i < l; i ++ ) {
  18040. projectObject( children[ i ], camera, shadowCamera );
  18041. }
  18042. }
  18043. };
  18044. // File:src/renderers/webgl/WebGLState.js
  18045. /**
  18046. * @author mrdoob / http://mrdoob.com/
  18047. */
  18048. THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) {
  18049. var _this = this;
  18050. var color = new THREE.Vector4();
  18051. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  18052. var newAttributes = new Uint8Array( maxVertexAttributes );
  18053. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  18054. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  18055. var capabilities = {};
  18056. var compressedTextureFormats = null;
  18057. var currentBlending = null;
  18058. var currentBlendEquation = null;
  18059. var currentBlendSrc = null;
  18060. var currentBlendDst = null;
  18061. var currentBlendEquationAlpha = null;
  18062. var currentBlendSrcAlpha = null;
  18063. var currentBlendDstAlpha = null;
  18064. var currentPremultipledAlpha = false;
  18065. var currentDepthFunc = null;
  18066. var currentDepthWrite = null;
  18067. var currentColorWrite = null;
  18068. var currentStencilWrite = null;
  18069. var currentStencilFunc = null;
  18070. var currentStencilRef = null;
  18071. var currentStencilMask = null;
  18072. var currentStencilFail = null;
  18073. var currentStencilZFail = null;
  18074. var currentStencilZPass = null;
  18075. var currentFlipSided = null;
  18076. var currentLineWidth = null;
  18077. var currentPolygonOffsetFactor = null;
  18078. var currentPolygonOffsetUnits = null;
  18079. var currentScissorTest = null;
  18080. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  18081. var currentTextureSlot = undefined;
  18082. var currentBoundTextures = {};
  18083. var currentClearColor = new THREE.Vector4();
  18084. var currentClearDepth = null;
  18085. var currentClearStencil = null;
  18086. var currentScissor = new THREE.Vector4();
  18087. var currentViewport = new THREE.Vector4();
  18088. this.init = function () {
  18089. this.clearColor( 0, 0, 0, 1 );
  18090. this.clearDepth( 1 );
  18091. this.clearStencil( 0 );
  18092. this.enable( gl.DEPTH_TEST );
  18093. gl.depthFunc( gl.LEQUAL );
  18094. gl.frontFace( gl.CCW );
  18095. gl.cullFace( gl.BACK );
  18096. this.enable( gl.CULL_FACE );
  18097. this.enable( gl.BLEND );
  18098. gl.blendEquation( gl.FUNC_ADD );
  18099. gl.blendFunc( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA );
  18100. };
  18101. this.initAttributes = function () {
  18102. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  18103. newAttributes[ i ] = 0;
  18104. }
  18105. };
  18106. this.enableAttribute = function ( attribute ) {
  18107. newAttributes[ attribute ] = 1;
  18108. if ( enabledAttributes[ attribute ] === 0 ) {
  18109. gl.enableVertexAttribArray( attribute );
  18110. enabledAttributes[ attribute ] = 1;
  18111. }
  18112. if ( attributeDivisors[ attribute ] !== 0 ) {
  18113. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  18114. extension.vertexAttribDivisorANGLE( attribute, 0 );
  18115. attributeDivisors[ attribute ] = 0;
  18116. }
  18117. };
  18118. this.enableAttributeAndDivisor = function ( attribute, meshPerAttribute, extension ) {
  18119. newAttributes[ attribute ] = 1;
  18120. if ( enabledAttributes[ attribute ] === 0 ) {
  18121. gl.enableVertexAttribArray( attribute );
  18122. enabledAttributes[ attribute ] = 1;
  18123. }
  18124. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  18125. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  18126. attributeDivisors[ attribute ] = meshPerAttribute;
  18127. }
  18128. };
  18129. this.disableUnusedAttributes = function () {
  18130. for ( var i = 0, l = enabledAttributes.length; i < l; i ++ ) {
  18131. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  18132. gl.disableVertexAttribArray( i );
  18133. enabledAttributes[ i ] = 0;
  18134. }
  18135. }
  18136. };
  18137. this.enable = function ( id ) {
  18138. if ( capabilities[ id ] !== true ) {
  18139. gl.enable( id );
  18140. capabilities[ id ] = true;
  18141. }
  18142. };
  18143. this.disable = function ( id ) {
  18144. if ( capabilities[ id ] !== false ) {
  18145. gl.disable( id );
  18146. capabilities[ id ] = false;
  18147. }
  18148. };
  18149. this.getCompressedTextureFormats = function () {
  18150. if ( compressedTextureFormats === null ) {
  18151. compressedTextureFormats = [];
  18152. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  18153. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  18154. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  18155. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  18156. for ( var i = 0; i < formats.length; i ++ ) {
  18157. compressedTextureFormats.push( formats[ i ] );
  18158. }
  18159. }
  18160. }
  18161. return compressedTextureFormats;
  18162. };
  18163. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  18164. if ( blending === THREE.NoBlending ) {
  18165. this.disable( gl.BLEND );
  18166. } else {
  18167. this.enable( gl.BLEND );
  18168. }
  18169. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  18170. if ( blending === THREE.AdditiveBlending ) {
  18171. if ( premultipliedAlpha ) {
  18172. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18173. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  18174. } else {
  18175. gl.blendEquation( gl.FUNC_ADD );
  18176. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  18177. }
  18178. } else if ( blending === THREE.SubtractiveBlending ) {
  18179. if ( premultipliedAlpha ) {
  18180. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18181. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  18182. } else {
  18183. gl.blendEquation( gl.FUNC_ADD );
  18184. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  18185. }
  18186. } else if ( blending === THREE.MultiplyBlending ) {
  18187. if ( premultipliedAlpha ) {
  18188. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18189. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.SRC_COLOR, gl.SRC_ALPHA );
  18190. } else {
  18191. gl.blendEquation( gl.FUNC_ADD );
  18192. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  18193. }
  18194. } else {
  18195. if ( premultipliedAlpha ) {
  18196. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18197. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18198. } else {
  18199. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  18200. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  18201. }
  18202. }
  18203. currentBlending = blending;
  18204. currentPremultipledAlpha = premultipliedAlpha;
  18205. }
  18206. if ( blending === THREE.CustomBlending ) {
  18207. blendEquationAlpha = blendEquationAlpha || blendEquation;
  18208. blendSrcAlpha = blendSrcAlpha || blendSrc;
  18209. blendDstAlpha = blendDstAlpha || blendDst;
  18210. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  18211. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  18212. currentBlendEquation = blendEquation;
  18213. currentBlendEquationAlpha = blendEquationAlpha;
  18214. }
  18215. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  18216. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  18217. currentBlendSrc = blendSrc;
  18218. currentBlendDst = blendDst;
  18219. currentBlendSrcAlpha = blendSrcAlpha;
  18220. currentBlendDstAlpha = blendDstAlpha;
  18221. }
  18222. } else {
  18223. currentBlendEquation = null;
  18224. currentBlendSrc = null;
  18225. currentBlendDst = null;
  18226. currentBlendEquationAlpha = null;
  18227. currentBlendSrcAlpha = null;
  18228. currentBlendDstAlpha = null;
  18229. }
  18230. };
  18231. this.setDepthFunc = function ( depthFunc ) {
  18232. if ( currentDepthFunc !== depthFunc ) {
  18233. if ( depthFunc ) {
  18234. switch ( depthFunc ) {
  18235. case THREE.NeverDepth:
  18236. gl.depthFunc( gl.NEVER );
  18237. break;
  18238. case THREE.AlwaysDepth:
  18239. gl.depthFunc( gl.ALWAYS );
  18240. break;
  18241. case THREE.LessDepth:
  18242. gl.depthFunc( gl.LESS );
  18243. break;
  18244. case THREE.LessEqualDepth:
  18245. gl.depthFunc( gl.LEQUAL );
  18246. break;
  18247. case THREE.EqualDepth:
  18248. gl.depthFunc( gl.EQUAL );
  18249. break;
  18250. case THREE.GreaterEqualDepth:
  18251. gl.depthFunc( gl.GEQUAL );
  18252. break;
  18253. case THREE.GreaterDepth:
  18254. gl.depthFunc( gl.GREATER );
  18255. break;
  18256. case THREE.NotEqualDepth:
  18257. gl.depthFunc( gl.NOTEQUAL );
  18258. break;
  18259. default:
  18260. gl.depthFunc( gl.LEQUAL );
  18261. }
  18262. } else {
  18263. gl.depthFunc( gl.LEQUAL );
  18264. }
  18265. currentDepthFunc = depthFunc;
  18266. }
  18267. };
  18268. this.setDepthTest = function ( depthTest ) {
  18269. if ( depthTest ) {
  18270. this.enable( gl.DEPTH_TEST );
  18271. } else {
  18272. this.disable( gl.DEPTH_TEST );
  18273. }
  18274. };
  18275. this.setDepthWrite = function ( depthWrite ) {
  18276. // TODO: Rename to setDepthMask
  18277. if ( currentDepthWrite !== depthWrite ) {
  18278. gl.depthMask( depthWrite );
  18279. currentDepthWrite = depthWrite;
  18280. }
  18281. };
  18282. this.setColorWrite = function ( colorWrite ) {
  18283. // TODO: Rename to setColorMask
  18284. if ( currentColorWrite !== colorWrite ) {
  18285. gl.colorMask( colorWrite, colorWrite, colorWrite, colorWrite );
  18286. currentColorWrite = colorWrite;
  18287. }
  18288. };
  18289. this.setStencilFunc = function ( stencilFunc, stencilRef, stencilMask ) {
  18290. if ( currentStencilFunc !== stencilFunc ||
  18291. currentStencilRef !== stencilRef ||
  18292. currentStencilMask !== stencilMask ) {
  18293. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  18294. currentStencilFunc = stencilFunc;
  18295. currentStencilRef = stencilRef;
  18296. currentStencilMask = stencilMask;
  18297. }
  18298. };
  18299. this.setStencilOp = function ( stencilFail, stencilZFail, stencilZPass ) {
  18300. if ( currentStencilFail !== stencilFail ||
  18301. currentStencilZFail !== stencilZFail ||
  18302. currentStencilZPass !== stencilZPass ) {
  18303. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  18304. currentStencilFail = stencilFail;
  18305. currentStencilZFail = stencilZFail;
  18306. currentStencilZPass = stencilZPass;
  18307. }
  18308. };
  18309. this.setStencilTest = function ( stencilTest ) {
  18310. if ( stencilTest ) {
  18311. this.enable( gl.STENCIL_TEST );
  18312. } else {
  18313. this.disable( gl.STENCIL_TEST );
  18314. }
  18315. };
  18316. this.setStencilWrite = function ( stencilWrite ) {
  18317. // TODO: Rename to setStencilMask
  18318. if ( currentStencilWrite !== stencilWrite ) {
  18319. gl.stencilMask( stencilWrite );
  18320. currentStencilWrite = stencilWrite;
  18321. }
  18322. };
  18323. this.setFlipSided = function ( flipSided ) {
  18324. if ( currentFlipSided !== flipSided ) {
  18325. if ( flipSided ) {
  18326. gl.frontFace( gl.CW );
  18327. } else {
  18328. gl.frontFace( gl.CCW );
  18329. }
  18330. currentFlipSided = flipSided;
  18331. }
  18332. };
  18333. this.setLineWidth = function ( width ) {
  18334. if ( width !== currentLineWidth ) {
  18335. gl.lineWidth( width );
  18336. currentLineWidth = width;
  18337. }
  18338. };
  18339. this.setPolygonOffset = function ( polygonOffset, factor, units ) {
  18340. if ( polygonOffset ) {
  18341. this.enable( gl.POLYGON_OFFSET_FILL );
  18342. } else {
  18343. this.disable( gl.POLYGON_OFFSET_FILL );
  18344. }
  18345. if ( polygonOffset && ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) ) {
  18346. gl.polygonOffset( factor, units );
  18347. currentPolygonOffsetFactor = factor;
  18348. currentPolygonOffsetUnits = units;
  18349. }
  18350. };
  18351. this.getScissorTest = function () {
  18352. return currentScissorTest;
  18353. };
  18354. this.setScissorTest = function ( scissorTest ) {
  18355. currentScissorTest = scissorTest;
  18356. if ( scissorTest ) {
  18357. this.enable( gl.SCISSOR_TEST );
  18358. } else {
  18359. this.disable( gl.SCISSOR_TEST );
  18360. }
  18361. };
  18362. // texture
  18363. this.activeTexture = function ( webglSlot ) {
  18364. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  18365. if ( currentTextureSlot !== webglSlot ) {
  18366. gl.activeTexture( webglSlot );
  18367. currentTextureSlot = webglSlot;
  18368. }
  18369. };
  18370. this.bindTexture = function ( webglType, webglTexture ) {
  18371. if ( currentTextureSlot === undefined ) {
  18372. _this.activeTexture();
  18373. }
  18374. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  18375. if ( boundTexture === undefined ) {
  18376. boundTexture = { type: undefined, texture: undefined };
  18377. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  18378. }
  18379. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  18380. gl.bindTexture( webglType, webglTexture );
  18381. boundTexture.type = webglType;
  18382. boundTexture.texture = webglTexture;
  18383. }
  18384. };
  18385. this.compressedTexImage2D = function () {
  18386. try {
  18387. gl.compressedTexImage2D.apply( gl, arguments );
  18388. } catch ( error ) {
  18389. console.error( error );
  18390. }
  18391. };
  18392. this.texImage2D = function () {
  18393. try {
  18394. gl.texImage2D.apply( gl, arguments );
  18395. } catch ( error ) {
  18396. console.error( error );
  18397. }
  18398. };
  18399. // clear values
  18400. this.clearColor = function ( r, g, b, a ) {
  18401. color.set( r, g, b, a );
  18402. if ( currentClearColor.equals( color ) === false ) {
  18403. gl.clearColor( r, g, b, a );
  18404. currentClearColor.copy( color );
  18405. }
  18406. };
  18407. this.clearDepth = function ( depth ) {
  18408. if ( currentClearDepth !== depth ) {
  18409. gl.clearDepth( depth );
  18410. currentClearDepth = depth;
  18411. }
  18412. };
  18413. this.clearStencil = function ( stencil ) {
  18414. if ( currentClearStencil !== stencil ) {
  18415. gl.clearStencil( stencil );
  18416. currentClearStencil = stencil;
  18417. }
  18418. };
  18419. //
  18420. this.scissor = function ( scissor ) {
  18421. if ( currentScissor.equals( scissor ) === false ) {
  18422. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  18423. currentScissor.copy( scissor );
  18424. }
  18425. };
  18426. this.viewport = function ( viewport ) {
  18427. if ( currentViewport.equals( viewport ) === false ) {
  18428. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  18429. currentViewport.copy( viewport );
  18430. }
  18431. };
  18432. //
  18433. this.reset = function () {
  18434. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  18435. if ( enabledAttributes[ i ] === 1 ) {
  18436. gl.disableVertexAttribArray( i );
  18437. enabledAttributes[ i ] = 0;
  18438. }
  18439. }
  18440. capabilities = {};
  18441. compressedTextureFormats = null;
  18442. currentTextureSlot = undefined;
  18443. currentBoundTextures = {};
  18444. currentBlending = null;
  18445. currentColorWrite = null;
  18446. currentDepthWrite = null;
  18447. currentStencilWrite = null;
  18448. currentFlipSided = null;
  18449. };
  18450. };
  18451. // File:src/renderers/webgl/WebGLUniforms.js
  18452. /**
  18453. *
  18454. * Uniforms of a program.
  18455. * Those form a tree structure with a special top-level container for the root,
  18456. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  18457. *
  18458. *
  18459. * Properties of inner nodes including the top-level container:
  18460. *
  18461. * .seq - array of nested uniforms
  18462. * .map - nested uniforms by name
  18463. *
  18464. *
  18465. * Methods of all nodes except the top-level container:
  18466. *
  18467. * .setValue( gl, value, [renderer] )
  18468. *
  18469. * uploads a uniform value(s)
  18470. * the 'renderer' parameter is needed for sampler uniforms
  18471. *
  18472. *
  18473. * Static methods of the top-level container (renderer factorizations):
  18474. *
  18475. * .upload( gl, seq, values, renderer )
  18476. *
  18477. * sets uniforms in 'seq' to 'values[id].value'
  18478. *
  18479. * .seqWithValue( seq, values ) : filteredSeq
  18480. *
  18481. * filters 'seq' entries with corresponding entry in values
  18482. *
  18483. * .splitDynamic( seq, values ) : filteredSeq
  18484. *
  18485. * filters 'seq' entries with dynamic entry and removes them from 'seq'
  18486. *
  18487. *
  18488. * Methods of the top-level container (renderer factorizations):
  18489. *
  18490. * .setValue( gl, name, value )
  18491. *
  18492. * sets uniform with name 'name' to 'value'
  18493. *
  18494. * .set( gl, obj, prop )
  18495. *
  18496. * sets uniform from object and property with same name than uniform
  18497. *
  18498. * .setOptional( gl, obj, prop )
  18499. *
  18500. * like .set for an optional property of the object
  18501. *
  18502. *
  18503. * @author tschw
  18504. *
  18505. */
  18506. THREE.WebGLUniforms = ( function() { // scope
  18507. // --- Base for inner nodes (including the root) ---
  18508. var UniformContainer = function() {
  18509. this.seq = [];
  18510. this.map = {};
  18511. },
  18512. // --- Utilities ---
  18513. // Array Caches (provide typed arrays for temporary by size)
  18514. arrayCacheF32 = [],
  18515. arrayCacheI32 = [],
  18516. uncacheTemporaryArrays = function() {
  18517. arrayCacheF32.length = 0;
  18518. arrayCacheI32.length = 0;
  18519. },
  18520. // Flattening for arrays of vectors and matrices
  18521. flatten = function( array, nBlocks, blockSize ) {
  18522. var firstElem = array[ 0 ];
  18523. if ( firstElem <= 0 || firstElem > 0 ) return array;
  18524. // unoptimized: ! isNaN( firstElem )
  18525. // see http://jacksondunstan.com/articles/983
  18526. var n = nBlocks * blockSize,
  18527. r = arrayCacheF32[ n ];
  18528. if ( r === undefined ) {
  18529. r = new Float32Array( n );
  18530. arrayCacheF32[ n ] = r;
  18531. }
  18532. if ( nBlocks !== 0 ) {
  18533. firstElem.toArray( r, 0 );
  18534. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  18535. offset += blockSize;
  18536. array[ i ].toArray( r, offset );
  18537. }
  18538. }
  18539. return r;
  18540. },
  18541. // Texture unit allocation
  18542. allocTexUnits = function( renderer, n ) {
  18543. var r = arrayCacheI32[ n ];
  18544. if ( r === undefined ) {
  18545. r = new Int32Array( n );
  18546. arrayCacheI32[ n ] = r;
  18547. }
  18548. for ( var i = 0; i !== n; ++ i )
  18549. r[ i ] = renderer.allocTextureUnit();
  18550. return r;
  18551. },
  18552. // --- Setters ---
  18553. // Note: Defining these methods externally, because they come in a bunch
  18554. // and this way their names minify.
  18555. // Single scalar
  18556. setValue1f = function( gl, v ) { gl.uniform1f( this.addr, v ); },
  18557. setValue1i = function( gl, v ) { gl.uniform1i( this.addr, v ); },
  18558. // Single float vector (from flat array or THREE.VectorN)
  18559. setValue2fv = function( gl, v ) {
  18560. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  18561. else gl.uniform2f( this.addr, v.x, v.y );
  18562. },
  18563. setValue3fv = function( gl, v ) {
  18564. if ( v.x !== undefined )
  18565. gl.uniform3f( this.addr, v.x, v.y, v.z );
  18566. else if ( v.r !== undefined )
  18567. gl.uniform3f( this.addr, v.r, v.g, v.b );
  18568. else
  18569. gl.uniform3fv( this.addr, v );
  18570. },
  18571. setValue4fv = function( gl, v ) {
  18572. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  18573. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  18574. },
  18575. // Single matrix (from flat array or MatrixN)
  18576. setValue2fm = function( gl, v ) {
  18577. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  18578. },
  18579. setValue3fm = function( gl, v ) {
  18580. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  18581. },
  18582. setValue4fm = function( gl, v ) {
  18583. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  18584. },
  18585. // Single texture (2D / Cube)
  18586. setValueT1 = function( gl, v, renderer ) {
  18587. var unit = renderer.allocTextureUnit();
  18588. gl.uniform1i( this.addr, unit );
  18589. if ( v ) renderer.setTexture2D( v, unit );
  18590. },
  18591. setValueT6 = function( gl, v, renderer ) {
  18592. var unit = renderer.allocTextureUnit();
  18593. gl.uniform1i( this.addr, unit );
  18594. if ( v ) renderer.setTextureCube( v, unit );
  18595. },
  18596. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  18597. setValue2iv = function( gl, v ) { gl.uniform2iv( this.addr, v ); },
  18598. setValue3iv = function( gl, v ) { gl.uniform3iv( this.addr, v ); },
  18599. setValue4iv = function( gl, v ) { gl.uniform4iv( this.addr, v ); },
  18600. // Helper to pick the right setter for the singular case
  18601. getSingularSetter = function( type ) {
  18602. switch ( type ) {
  18603. case 0x1406: return setValue1f; // FLOAT
  18604. case 0x8b50: return setValue2fv; // _VEC2
  18605. case 0x8b51: return setValue3fv; // _VEC3
  18606. case 0x8b52: return setValue4fv; // _VEC4
  18607. case 0x8b5a: return setValue2fm; // _MAT2
  18608. case 0x8b5b: return setValue3fm; // _MAT3
  18609. case 0x8b5c: return setValue4fm; // _MAT4
  18610. case 0x8b5e: return setValueT1; // SAMPLER_2D
  18611. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  18612. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  18613. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  18614. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  18615. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  18616. }
  18617. },
  18618. // Array of scalars
  18619. setValue1fv = function( gl, v ) { gl.uniform1fv( this.addr, v ); },
  18620. setValue1iv = function( gl, v ) { gl.uniform1iv( this.addr, v ); },
  18621. // Array of vectors (flat or from THREE classes)
  18622. setValueV2a = function( gl, v ) {
  18623. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  18624. },
  18625. setValueV3a = function( gl, v ) {
  18626. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  18627. },
  18628. setValueV4a = function( gl, v ) {
  18629. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  18630. },
  18631. // Array of matrices (flat or from THREE clases)
  18632. setValueM2a = function( gl, v ) {
  18633. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  18634. },
  18635. setValueM3a = function( gl, v ) {
  18636. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  18637. },
  18638. setValueM4a = function( gl, v ) {
  18639. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  18640. },
  18641. // Array of textures (2D / Cube)
  18642. setValueT1a = function( gl, v, renderer ) {
  18643. var n = v.length,
  18644. units = allocTexUnits( renderer, n );
  18645. gl.uniform1iv( this.addr, units );
  18646. for ( var i = 0; i !== n; ++ i ) {
  18647. var tex = v[ i ];
  18648. if ( tex ) renderer.setTexture2D( tex, units[ i ] );
  18649. }
  18650. },
  18651. setValueT6a = function( gl, v, renderer ) {
  18652. var n = v.length,
  18653. units = allocTexUnits( renderer, n );
  18654. gl.uniform1iv( this.addr, units );
  18655. for ( var i = 0; i !== n; ++ i ) {
  18656. var tex = v[ i ];
  18657. if ( tex ) renderer.setTextureCube( tex, units[ i ] );
  18658. }
  18659. },
  18660. // Helper to pick the right setter for a pure (bottom-level) array
  18661. getPureArraySetter = function( type ) {
  18662. switch ( type ) {
  18663. case 0x1406: return setValue1fv; // FLOAT
  18664. case 0x8b50: return setValueV2a; // _VEC2
  18665. case 0x8b51: return setValueV3a; // _VEC3
  18666. case 0x8b52: return setValueV4a; // _VEC4
  18667. case 0x8b5a: return setValueM2a; // _MAT2
  18668. case 0x8b5b: return setValueM3a; // _MAT3
  18669. case 0x8b5c: return setValueM4a; // _MAT4
  18670. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  18671. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  18672. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  18673. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  18674. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  18675. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  18676. }
  18677. },
  18678. // --- Uniform Classes ---
  18679. SingleUniform = function SingleUniform( id, activeInfo, addr ) {
  18680. this.id = id;
  18681. this.addr = addr;
  18682. this.setValue = getSingularSetter( activeInfo.type );
  18683. // this.path = activeInfo.name; // DEBUG
  18684. },
  18685. PureArrayUniform = function( id, activeInfo, addr ) {
  18686. this.id = id;
  18687. this.addr = addr;
  18688. this.size = activeInfo.size;
  18689. this.setValue = getPureArraySetter( activeInfo.type );
  18690. // this.path = activeInfo.name; // DEBUG
  18691. },
  18692. StructuredUniform = function( id ) {
  18693. this.id = id;
  18694. UniformContainer.call( this ); // mix-in
  18695. };
  18696. StructuredUniform.prototype.setValue = function( gl, value ) {
  18697. // Note: Don't need an extra 'renderer' parameter, since samplers
  18698. // are not allowed in structured uniforms.
  18699. var seq = this.seq;
  18700. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  18701. var u = seq[ i ];
  18702. u.setValue( gl, value[ u.id ] );
  18703. }
  18704. };
  18705. // --- Top-level ---
  18706. // Parser - builds up the property tree from the path strings
  18707. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g,
  18708. // extracts
  18709. // - the identifier (member name or array index)
  18710. // - followed by an optional right bracket (found when array index)
  18711. // - followed by an optional left bracket or dot (type of subscript)
  18712. //
  18713. // Note: These portions can be read in a non-overlapping fashion and
  18714. // allow straightforward parsing of the hierarchy that WebGL encodes
  18715. // in the uniform names.
  18716. addUniform = function( container, uniformObject ) {
  18717. container.seq.push( uniformObject );
  18718. container.map[ uniformObject.id ] = uniformObject;
  18719. },
  18720. parseUniform = function( activeInfo, addr, container ) {
  18721. var path = activeInfo.name,
  18722. pathLength = path.length;
  18723. // reset RegExp object, because of the early exit of a previous run
  18724. RePathPart.lastIndex = 0;
  18725. for (; ;) {
  18726. var match = RePathPart.exec( path ),
  18727. matchEnd = RePathPart.lastIndex,
  18728. id = match[ 1 ],
  18729. idIsIndex = match[ 2 ] === ']',
  18730. subscript = match[ 3 ];
  18731. if ( idIsIndex ) id = id | 0; // convert to integer
  18732. if ( subscript === undefined ||
  18733. subscript === '[' && matchEnd + 2 === pathLength ) {
  18734. // bare name or "pure" bottom-level array "[0]" suffix
  18735. addUniform( container, subscript === undefined ?
  18736. new SingleUniform( id, activeInfo, addr ) :
  18737. new PureArrayUniform( id, activeInfo, addr ) );
  18738. break;
  18739. } else {
  18740. // step into inner node / create it in case it doesn't exist
  18741. var map = container.map,
  18742. next = map[ id ];
  18743. if ( next === undefined ) {
  18744. next = new StructuredUniform( id );
  18745. addUniform( container, next );
  18746. }
  18747. container = next;
  18748. }
  18749. }
  18750. },
  18751. // Root Container
  18752. WebGLUniforms = function WebGLUniforms( gl, program, renderer ) {
  18753. UniformContainer.call( this );
  18754. this.renderer = renderer;
  18755. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  18756. for ( var i = 0; i !== n; ++ i ) {
  18757. var info = gl.getActiveUniform( program, i ),
  18758. path = info.name,
  18759. addr = gl.getUniformLocation( program, path );
  18760. parseUniform( info, addr, this );
  18761. }
  18762. };
  18763. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  18764. var u = this.map[ name ];
  18765. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  18766. };
  18767. WebGLUniforms.prototype.set = function( gl, object, name ) {
  18768. var u = this.map[ name ];
  18769. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  18770. };
  18771. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  18772. var v = object[ name ];
  18773. if ( v !== undefined ) this.setValue( gl, name, v );
  18774. };
  18775. // Static interface
  18776. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  18777. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  18778. var u = seq[ i ],
  18779. v = values[ u.id ];
  18780. if ( v.needsUpdate !== false ) {
  18781. // note: always updating when .needsUpdate is undefined
  18782. u.setValue( gl, v.value, renderer );
  18783. }
  18784. }
  18785. };
  18786. WebGLUniforms.seqWithValue = function( seq, values ) {
  18787. var r = [];
  18788. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  18789. var u = seq[ i ];
  18790. if ( u.id in values ) r.push( u );
  18791. }
  18792. return r;
  18793. };
  18794. WebGLUniforms.splitDynamic = function( seq, values ) {
  18795. var r = null,
  18796. n = seq.length,
  18797. w = 0;
  18798. for ( var i = 0; i !== n; ++ i ) {
  18799. var u = seq[ i ],
  18800. v = values[ u.id ];
  18801. if ( v && v.dynamic === true ) {
  18802. if ( r === null ) r = [];
  18803. r.push( u );
  18804. } else {
  18805. // in-place compact 'seq', removing the matches
  18806. if ( w < i ) seq[ w ] = u;
  18807. ++ w;
  18808. }
  18809. }
  18810. if ( w < n ) seq.length = w;
  18811. return r;
  18812. };
  18813. WebGLUniforms.evalDynamic = function( seq, values, object, camera ) {
  18814. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  18815. var v = values[ seq[ i ].id ],
  18816. f = v.onUpdateCallback;
  18817. if ( f !== undefined ) f.call( v, object, camera );
  18818. }
  18819. };
  18820. return WebGLUniforms;
  18821. } )();
  18822. // File:src/renderers/webgl/plugins/LensFlarePlugin.js
  18823. /**
  18824. * @author mikael emtinger / http://gomo.se/
  18825. * @author alteredq / http://alteredqualia.com/
  18826. */
  18827. THREE.LensFlarePlugin = function ( renderer, flares ) {
  18828. var gl = renderer.context;
  18829. var state = renderer.state;
  18830. var vertexBuffer, elementBuffer;
  18831. var shader, program, attributes, uniforms;
  18832. var tempTexture, occlusionTexture;
  18833. function init() {
  18834. var vertices = new Float32Array( [
  18835. - 1, - 1, 0, 0,
  18836. 1, - 1, 1, 0,
  18837. 1, 1, 1, 1,
  18838. - 1, 1, 0, 1
  18839. ] );
  18840. var faces = new Uint16Array( [
  18841. 0, 1, 2,
  18842. 0, 2, 3
  18843. ] );
  18844. // buffers
  18845. vertexBuffer = gl.createBuffer();
  18846. elementBuffer = gl.createBuffer();
  18847. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18848. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  18849. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18850. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  18851. // textures
  18852. tempTexture = gl.createTexture();
  18853. occlusionTexture = gl.createTexture();
  18854. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18855. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  18856. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18857. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18858. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18859. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18860. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  18861. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  18862. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  18863. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  18864. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  18865. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  18866. shader = {
  18867. vertexShader: [
  18868. "uniform lowp int renderType;",
  18869. "uniform vec3 screenPosition;",
  18870. "uniform vec2 scale;",
  18871. "uniform float rotation;",
  18872. "uniform sampler2D occlusionMap;",
  18873. "attribute vec2 position;",
  18874. "attribute vec2 uv;",
  18875. "varying vec2 vUV;",
  18876. "varying float vVisibility;",
  18877. "void main() {",
  18878. "vUV = uv;",
  18879. "vec2 pos = position;",
  18880. "if ( renderType == 2 ) {",
  18881. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  18882. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  18883. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  18884. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  18885. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  18886. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  18887. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  18888. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  18889. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  18890. "vVisibility = visibility.r / 9.0;",
  18891. "vVisibility *= 1.0 - visibility.g / 9.0;",
  18892. "vVisibility *= visibility.b / 9.0;",
  18893. "vVisibility *= 1.0 - visibility.a / 9.0;",
  18894. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  18895. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  18896. "}",
  18897. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  18898. "}"
  18899. ].join( "\n" ),
  18900. fragmentShader: [
  18901. "uniform lowp int renderType;",
  18902. "uniform sampler2D map;",
  18903. "uniform float opacity;",
  18904. "uniform vec3 color;",
  18905. "varying vec2 vUV;",
  18906. "varying float vVisibility;",
  18907. "void main() {",
  18908. // pink square
  18909. "if ( renderType == 0 ) {",
  18910. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  18911. // restore
  18912. "} else if ( renderType == 1 ) {",
  18913. "gl_FragColor = texture2D( map, vUV );",
  18914. // flare
  18915. "} else {",
  18916. "vec4 texture = texture2D( map, vUV );",
  18917. "texture.a *= opacity * vVisibility;",
  18918. "gl_FragColor = texture;",
  18919. "gl_FragColor.rgb *= color;",
  18920. "}",
  18921. "}"
  18922. ].join( "\n" )
  18923. };
  18924. program = createProgram( shader );
  18925. attributes = {
  18926. vertex: gl.getAttribLocation ( program, "position" ),
  18927. uv: gl.getAttribLocation ( program, "uv" )
  18928. };
  18929. uniforms = {
  18930. renderType: gl.getUniformLocation( program, "renderType" ),
  18931. map: gl.getUniformLocation( program, "map" ),
  18932. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  18933. opacity: gl.getUniformLocation( program, "opacity" ),
  18934. color: gl.getUniformLocation( program, "color" ),
  18935. scale: gl.getUniformLocation( program, "scale" ),
  18936. rotation: gl.getUniformLocation( program, "rotation" ),
  18937. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  18938. };
  18939. }
  18940. /*
  18941. * Render lens flares
  18942. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  18943. * reads these back and calculates occlusion.
  18944. */
  18945. this.render = function ( scene, camera, viewport ) {
  18946. if ( flares.length === 0 ) return;
  18947. var tempPosition = new THREE.Vector3();
  18948. var invAspect = viewport.w / viewport.z,
  18949. halfViewportWidth = viewport.z * 0.5,
  18950. halfViewportHeight = viewport.w * 0.5;
  18951. var size = 16 / viewport.w,
  18952. scale = new THREE.Vector2( size * invAspect, size );
  18953. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  18954. screenPositionPixels = new THREE.Vector2( 1, 1 );
  18955. var validArea = new THREE.Box2();
  18956. validArea.min.set( 0, 0 );
  18957. validArea.max.set( viewport.z - 16, viewport.w - 16 );
  18958. if ( program === undefined ) {
  18959. init();
  18960. }
  18961. gl.useProgram( program );
  18962. state.initAttributes();
  18963. state.enableAttribute( attributes.vertex );
  18964. state.enableAttribute( attributes.uv );
  18965. state.disableUnusedAttributes();
  18966. // loop through all lens flares to update their occlusion and positions
  18967. // setup gl and common used attribs/uniforms
  18968. gl.uniform1i( uniforms.occlusionMap, 0 );
  18969. gl.uniform1i( uniforms.map, 1 );
  18970. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  18971. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  18972. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  18973. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  18974. state.disable( gl.CULL_FACE );
  18975. state.setDepthWrite( false );
  18976. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  18977. size = 16 / viewport.w;
  18978. scale.set( size * invAspect, size );
  18979. // calc object screen position
  18980. var flare = flares[ i ];
  18981. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  18982. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  18983. tempPosition.applyProjection( camera.projectionMatrix );
  18984. // setup arrays for gl programs
  18985. screenPosition.copy( tempPosition );
  18986. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  18987. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  18988. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  18989. // screen cull
  18990. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  18991. // save current RGB to temp texture
  18992. state.activeTexture( gl.TEXTURE0 );
  18993. state.bindTexture( gl.TEXTURE_2D, null );
  18994. state.activeTexture( gl.TEXTURE1 );
  18995. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  18996. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  18997. // render pink quad
  18998. gl.uniform1i( uniforms.renderType, 0 );
  18999. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  19000. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  19001. state.disable( gl.BLEND );
  19002. state.enable( gl.DEPTH_TEST );
  19003. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  19004. // copy result to occlusionMap
  19005. state.activeTexture( gl.TEXTURE0 );
  19006. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  19007. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  19008. // restore graphics
  19009. gl.uniform1i( uniforms.renderType, 1 );
  19010. state.disable( gl.DEPTH_TEST );
  19011. state.activeTexture( gl.TEXTURE1 );
  19012. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  19013. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  19014. // update object positions
  19015. flare.positionScreen.copy( screenPosition );
  19016. if ( flare.customUpdateCallback ) {
  19017. flare.customUpdateCallback( flare );
  19018. } else {
  19019. flare.updateLensFlares();
  19020. }
  19021. // render flares
  19022. gl.uniform1i( uniforms.renderType, 2 );
  19023. state.enable( gl.BLEND );
  19024. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  19025. var sprite = flare.lensFlares[ j ];
  19026. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  19027. screenPosition.x = sprite.x;
  19028. screenPosition.y = sprite.y;
  19029. screenPosition.z = sprite.z;
  19030. size = sprite.size * sprite.scale / viewport.w;
  19031. scale.x = size * invAspect;
  19032. scale.y = size;
  19033. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  19034. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  19035. gl.uniform1f( uniforms.rotation, sprite.rotation );
  19036. gl.uniform1f( uniforms.opacity, sprite.opacity );
  19037. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  19038. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  19039. renderer.setTexture2D( sprite.texture, 1 );
  19040. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  19041. }
  19042. }
  19043. }
  19044. }
  19045. // restore gl
  19046. state.enable( gl.CULL_FACE );
  19047. state.enable( gl.DEPTH_TEST );
  19048. state.setDepthWrite( true );
  19049. renderer.resetGLState();
  19050. };
  19051. function createProgram ( shader ) {
  19052. var program = gl.createProgram();
  19053. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  19054. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  19055. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  19056. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  19057. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  19058. gl.compileShader( fragmentShader );
  19059. gl.compileShader( vertexShader );
  19060. gl.attachShader( program, fragmentShader );
  19061. gl.attachShader( program, vertexShader );
  19062. gl.linkProgram( program );
  19063. return program;
  19064. }
  19065. };
  19066. // File:src/renderers/webgl/plugins/SpritePlugin.js
  19067. /**
  19068. * @author mikael emtinger / http://gomo.se/
  19069. * @author alteredq / http://alteredqualia.com/
  19070. */
  19071. THREE.SpritePlugin = function ( renderer, sprites ) {
  19072. var gl = renderer.context;
  19073. var state = renderer.state;
  19074. var vertexBuffer, elementBuffer;
  19075. var program, attributes, uniforms;
  19076. var texture;
  19077. // decompose matrixWorld
  19078. var spritePosition = new THREE.Vector3();
  19079. var spriteRotation = new THREE.Quaternion();
  19080. var spriteScale = new THREE.Vector3();
  19081. function init() {
  19082. var vertices = new Float32Array( [
  19083. - 0.5, - 0.5, 0, 0,
  19084. 0.5, - 0.5, 1, 0,
  19085. 0.5, 0.5, 1, 1,
  19086. - 0.5, 0.5, 0, 1
  19087. ] );
  19088. var faces = new Uint16Array( [
  19089. 0, 1, 2,
  19090. 0, 2, 3
  19091. ] );
  19092. vertexBuffer = gl.createBuffer();
  19093. elementBuffer = gl.createBuffer();
  19094. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  19095. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  19096. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  19097. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  19098. program = createProgram();
  19099. attributes = {
  19100. position: gl.getAttribLocation ( program, 'position' ),
  19101. uv: gl.getAttribLocation ( program, 'uv' )
  19102. };
  19103. uniforms = {
  19104. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  19105. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  19106. rotation: gl.getUniformLocation( program, 'rotation' ),
  19107. scale: gl.getUniformLocation( program, 'scale' ),
  19108. color: gl.getUniformLocation( program, 'color' ),
  19109. map: gl.getUniformLocation( program, 'map' ),
  19110. opacity: gl.getUniformLocation( program, 'opacity' ),
  19111. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  19112. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  19113. fogType: gl.getUniformLocation( program, 'fogType' ),
  19114. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  19115. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  19116. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  19117. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  19118. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  19119. };
  19120. var canvas = document.createElement( 'canvas' );
  19121. canvas.width = 8;
  19122. canvas.height = 8;
  19123. var context = canvas.getContext( '2d' );
  19124. context.fillStyle = 'white';
  19125. context.fillRect( 0, 0, 8, 8 );
  19126. texture = new THREE.Texture( canvas );
  19127. texture.needsUpdate = true;
  19128. }
  19129. this.render = function ( scene, camera ) {
  19130. if ( sprites.length === 0 ) return;
  19131. // setup gl
  19132. if ( program === undefined ) {
  19133. init();
  19134. }
  19135. gl.useProgram( program );
  19136. state.initAttributes();
  19137. state.enableAttribute( attributes.position );
  19138. state.enableAttribute( attributes.uv );
  19139. state.disableUnusedAttributes();
  19140. state.disable( gl.CULL_FACE );
  19141. state.enable( gl.BLEND );
  19142. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  19143. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  19144. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  19145. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  19146. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  19147. state.activeTexture( gl.TEXTURE0 );
  19148. gl.uniform1i( uniforms.map, 0 );
  19149. var oldFogType = 0;
  19150. var sceneFogType = 0;
  19151. var fog = scene.fog;
  19152. if ( fog ) {
  19153. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  19154. if ( fog instanceof THREE.Fog ) {
  19155. gl.uniform1f( uniforms.fogNear, fog.near );
  19156. gl.uniform1f( uniforms.fogFar, fog.far );
  19157. gl.uniform1i( uniforms.fogType, 1 );
  19158. oldFogType = 1;
  19159. sceneFogType = 1;
  19160. } else if ( fog instanceof THREE.FogExp2 ) {
  19161. gl.uniform1f( uniforms.fogDensity, fog.density );
  19162. gl.uniform1i( uniforms.fogType, 2 );
  19163. oldFogType = 2;
  19164. sceneFogType = 2;
  19165. }
  19166. } else {
  19167. gl.uniform1i( uniforms.fogType, 0 );
  19168. oldFogType = 0;
  19169. sceneFogType = 0;
  19170. }
  19171. // update positions and sort
  19172. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  19173. var sprite = sprites[ i ];
  19174. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  19175. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  19176. }
  19177. sprites.sort( painterSortStable );
  19178. // render all sprites
  19179. var scale = [];
  19180. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  19181. var sprite = sprites[ i ];
  19182. var material = sprite.material;
  19183. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  19184. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  19185. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  19186. scale[ 0 ] = spriteScale.x;
  19187. scale[ 1 ] = spriteScale.y;
  19188. var fogType = 0;
  19189. if ( scene.fog && material.fog ) {
  19190. fogType = sceneFogType;
  19191. }
  19192. if ( oldFogType !== fogType ) {
  19193. gl.uniform1i( uniforms.fogType, fogType );
  19194. oldFogType = fogType;
  19195. }
  19196. if ( material.map !== null ) {
  19197. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  19198. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  19199. } else {
  19200. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  19201. gl.uniform2f( uniforms.uvScale, 1, 1 );
  19202. }
  19203. gl.uniform1f( uniforms.opacity, material.opacity );
  19204. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  19205. gl.uniform1f( uniforms.rotation, material.rotation );
  19206. gl.uniform2fv( uniforms.scale, scale );
  19207. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  19208. state.setDepthTest( material.depthTest );
  19209. state.setDepthWrite( material.depthWrite );
  19210. if ( material.map ) {
  19211. renderer.setTexture2D( material.map, 0 );
  19212. } else {
  19213. renderer.setTexture2D( texture, 0 );
  19214. }
  19215. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  19216. }
  19217. // restore gl
  19218. state.enable( gl.CULL_FACE );
  19219. renderer.resetGLState();
  19220. };
  19221. function createProgram () {
  19222. var program = gl.createProgram();
  19223. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  19224. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  19225. gl.shaderSource( vertexShader, [
  19226. 'precision ' + renderer.getPrecision() + ' float;',
  19227. 'uniform mat4 modelViewMatrix;',
  19228. 'uniform mat4 projectionMatrix;',
  19229. 'uniform float rotation;',
  19230. 'uniform vec2 scale;',
  19231. 'uniform vec2 uvOffset;',
  19232. 'uniform vec2 uvScale;',
  19233. 'attribute vec2 position;',
  19234. 'attribute vec2 uv;',
  19235. 'varying vec2 vUV;',
  19236. 'void main() {',
  19237. 'vUV = uvOffset + uv * uvScale;',
  19238. 'vec2 alignedPosition = position * scale;',
  19239. 'vec2 rotatedPosition;',
  19240. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  19241. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  19242. 'vec4 finalPosition;',
  19243. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  19244. 'finalPosition.xy += rotatedPosition;',
  19245. 'finalPosition = projectionMatrix * finalPosition;',
  19246. 'gl_Position = finalPosition;',
  19247. '}'
  19248. ].join( '\n' ) );
  19249. gl.shaderSource( fragmentShader, [
  19250. 'precision ' + renderer.getPrecision() + ' float;',
  19251. 'uniform vec3 color;',
  19252. 'uniform sampler2D map;',
  19253. 'uniform float opacity;',
  19254. 'uniform int fogType;',
  19255. 'uniform vec3 fogColor;',
  19256. 'uniform float fogDensity;',
  19257. 'uniform float fogNear;',
  19258. 'uniform float fogFar;',
  19259. 'uniform float alphaTest;',
  19260. 'varying vec2 vUV;',
  19261. 'void main() {',
  19262. 'vec4 texture = texture2D( map, vUV );',
  19263. 'if ( texture.a < alphaTest ) discard;',
  19264. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  19265. 'if ( fogType > 0 ) {',
  19266. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  19267. 'float fogFactor = 0.0;',
  19268. 'if ( fogType == 1 ) {',
  19269. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  19270. '} else {',
  19271. 'const float LOG2 = 1.442695;',
  19272. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  19273. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  19274. '}',
  19275. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  19276. '}',
  19277. '}'
  19278. ].join( '\n' ) );
  19279. gl.compileShader( vertexShader );
  19280. gl.compileShader( fragmentShader );
  19281. gl.attachShader( program, vertexShader );
  19282. gl.attachShader( program, fragmentShader );
  19283. gl.linkProgram( program );
  19284. return program;
  19285. }
  19286. function painterSortStable ( a, b ) {
  19287. if ( a.renderOrder !== b.renderOrder ) {
  19288. return a.renderOrder - b.renderOrder;
  19289. } else if ( a.z !== b.z ) {
  19290. return b.z - a.z;
  19291. } else {
  19292. return b.id - a.id;
  19293. }
  19294. }
  19295. };
  19296. // File:src/Three.Legacy.js
  19297. /**
  19298. * @author mrdoob / http://mrdoob.com/
  19299. */
  19300. Object.defineProperties( THREE.Box2.prototype, {
  19301. empty: {
  19302. value: function () {
  19303. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  19304. return this.isEmpty();
  19305. }
  19306. },
  19307. isIntersectionBox: {
  19308. value: function ( box ) {
  19309. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  19310. return this.intersectsBox( box );
  19311. }
  19312. }
  19313. } );
  19314. Object.defineProperties( THREE.Box3.prototype, {
  19315. empty: {
  19316. value: function () {
  19317. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  19318. return this.isEmpty();
  19319. }
  19320. },
  19321. isIntersectionBox: {
  19322. value: function ( box ) {
  19323. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  19324. return this.intersectsBox( box );
  19325. }
  19326. },
  19327. isIntersectionSphere: {
  19328. value: function ( sphere ) {
  19329. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  19330. return this.intersectsSphere( sphere );
  19331. }
  19332. }
  19333. } );
  19334. Object.defineProperties( THREE.Matrix3.prototype, {
  19335. multiplyVector3: {
  19336. value: function ( vector ) {
  19337. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  19338. return vector.applyMatrix3( this );
  19339. }
  19340. },
  19341. multiplyVector3Array: {
  19342. value: function ( a ) {
  19343. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  19344. return this.applyToVector3Array( a );
  19345. }
  19346. }
  19347. } );
  19348. Object.defineProperties( THREE.Matrix4.prototype, {
  19349. extractPosition: {
  19350. value: function ( m ) {
  19351. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  19352. return this.copyPosition( m );
  19353. }
  19354. },
  19355. setRotationFromQuaternion: {
  19356. value: function ( q ) {
  19357. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  19358. return this.makeRotationFromQuaternion( q );
  19359. }
  19360. },
  19361. multiplyVector3: {
  19362. value: function ( vector ) {
  19363. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  19364. return vector.applyProjection( this );
  19365. }
  19366. },
  19367. multiplyVector4: {
  19368. value: function ( vector ) {
  19369. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  19370. return vector.applyMatrix4( this );
  19371. }
  19372. },
  19373. multiplyVector3Array: {
  19374. value: function ( a ) {
  19375. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  19376. return this.applyToVector3Array( a );
  19377. }
  19378. },
  19379. rotateAxis: {
  19380. value: function ( v ) {
  19381. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  19382. v.transformDirection( this );
  19383. }
  19384. },
  19385. crossVector: {
  19386. value: function ( vector ) {
  19387. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  19388. return vector.applyMatrix4( this );
  19389. }
  19390. },
  19391. translate: {
  19392. value: function ( v ) {
  19393. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  19394. }
  19395. },
  19396. rotateX: {
  19397. value: function ( angle ) {
  19398. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  19399. }
  19400. },
  19401. rotateY: {
  19402. value: function ( angle ) {
  19403. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  19404. }
  19405. },
  19406. rotateZ: {
  19407. value: function ( angle ) {
  19408. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  19409. }
  19410. },
  19411. rotateByAxis: {
  19412. value: function ( axis, angle ) {
  19413. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  19414. }
  19415. }
  19416. } );
  19417. Object.defineProperties( THREE.Plane.prototype, {
  19418. isIntersectionLine: {
  19419. value: function ( line ) {
  19420. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  19421. return this.intersectsLine( line );
  19422. }
  19423. }
  19424. } );
  19425. Object.defineProperties( THREE.Quaternion.prototype, {
  19426. multiplyVector3: {
  19427. value: function ( vector ) {
  19428. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  19429. return vector.applyQuaternion( this );
  19430. }
  19431. }
  19432. } );
  19433. Object.defineProperties( THREE.Ray.prototype, {
  19434. isIntersectionBox: {
  19435. value: function ( box ) {
  19436. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  19437. return this.intersectsBox( box );
  19438. }
  19439. },
  19440. isIntersectionPlane: {
  19441. value: function ( plane ) {
  19442. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  19443. return this.intersectsPlane( plane );
  19444. }
  19445. },
  19446. isIntersectionSphere: {
  19447. value: function ( sphere ) {
  19448. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  19449. return this.intersectsSphere( sphere );
  19450. }
  19451. }
  19452. } );
  19453. Object.defineProperties( THREE.Vector3.prototype, {
  19454. setEulerFromRotationMatrix: {
  19455. value: function () {
  19456. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  19457. }
  19458. },
  19459. setEulerFromQuaternion: {
  19460. value: function () {
  19461. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  19462. }
  19463. },
  19464. getPositionFromMatrix: {
  19465. value: function ( m ) {
  19466. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  19467. return this.setFromMatrixPosition( m );
  19468. }
  19469. },
  19470. getScaleFromMatrix: {
  19471. value: function ( m ) {
  19472. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  19473. return this.setFromMatrixScale( m );
  19474. }
  19475. },
  19476. getColumnFromMatrix: {
  19477. value: function ( index, matrix ) {
  19478. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  19479. return this.setFromMatrixColumn( index, matrix );
  19480. }
  19481. }
  19482. } );
  19483. //
  19484. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  19485. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  19486. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  19487. };
  19488. THREE.Vertex = function ( x, y, z ) {
  19489. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  19490. return new THREE.Vector3( x, y, z );
  19491. };
  19492. //
  19493. Object.defineProperties( THREE.Object3D.prototype, {
  19494. eulerOrder: {
  19495. get: function () {
  19496. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  19497. return this.rotation.order;
  19498. },
  19499. set: function ( value ) {
  19500. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  19501. this.rotation.order = value;
  19502. }
  19503. },
  19504. getChildByName: {
  19505. value: function ( name ) {
  19506. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  19507. return this.getObjectByName( name );
  19508. }
  19509. },
  19510. renderDepth: {
  19511. set: function ( value ) {
  19512. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  19513. }
  19514. },
  19515. translate: {
  19516. value: function ( distance, axis ) {
  19517. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  19518. return this.translateOnAxis( axis, distance );
  19519. }
  19520. },
  19521. useQuaternion: {
  19522. get: function () {
  19523. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  19524. },
  19525. set: function ( value ) {
  19526. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  19527. }
  19528. }
  19529. } );
  19530. //
  19531. Object.defineProperties( THREE, {
  19532. PointCloud: {
  19533. value: function ( geometry, material ) {
  19534. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  19535. return new THREE.Points( geometry, material );
  19536. }
  19537. },
  19538. ParticleSystem: {
  19539. value: function ( geometry, material ) {
  19540. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  19541. return new THREE.Points( geometry, material );
  19542. }
  19543. }
  19544. } );
  19545. //
  19546. Object.defineProperties( THREE.Light.prototype, {
  19547. onlyShadow: {
  19548. set: function ( value ) {
  19549. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  19550. }
  19551. },
  19552. shadowCameraFov: {
  19553. set: function ( value ) {
  19554. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  19555. this.shadow.camera.fov = value;
  19556. }
  19557. },
  19558. shadowCameraLeft: {
  19559. set: function ( value ) {
  19560. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  19561. this.shadow.camera.left = value;
  19562. }
  19563. },
  19564. shadowCameraRight: {
  19565. set: function ( value ) {
  19566. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  19567. this.shadow.camera.right = value;
  19568. }
  19569. },
  19570. shadowCameraTop: {
  19571. set: function ( value ) {
  19572. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  19573. this.shadow.camera.top = value;
  19574. }
  19575. },
  19576. shadowCameraBottom: {
  19577. set: function ( value ) {
  19578. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  19579. this.shadow.camera.bottom = value;
  19580. }
  19581. },
  19582. shadowCameraNear: {
  19583. set: function ( value ) {
  19584. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  19585. this.shadow.camera.near = value;
  19586. }
  19587. },
  19588. shadowCameraFar: {
  19589. set: function ( value ) {
  19590. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  19591. this.shadow.camera.far = value;
  19592. }
  19593. },
  19594. shadowCameraVisible: {
  19595. set: function ( value ) {
  19596. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  19597. }
  19598. },
  19599. shadowBias: {
  19600. set: function ( value ) {
  19601. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  19602. this.shadow.bias = value;
  19603. }
  19604. },
  19605. shadowDarkness: {
  19606. set: function ( value ) {
  19607. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  19608. }
  19609. },
  19610. shadowMapWidth: {
  19611. set: function ( value ) {
  19612. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  19613. this.shadow.mapSize.width = value;
  19614. }
  19615. },
  19616. shadowMapHeight: {
  19617. set: function ( value ) {
  19618. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  19619. this.shadow.mapSize.height = value;
  19620. }
  19621. }
  19622. } );
  19623. //
  19624. Object.defineProperties( THREE.BufferAttribute.prototype, {
  19625. length: {
  19626. get: function () {
  19627. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Please use .count.' );
  19628. return this.array.length;
  19629. }
  19630. }
  19631. } );
  19632. Object.defineProperties( THREE.BufferGeometry.prototype, {
  19633. drawcalls: {
  19634. get: function () {
  19635. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  19636. return this.groups;
  19637. }
  19638. },
  19639. offsets: {
  19640. get: function () {
  19641. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  19642. return this.groups;
  19643. }
  19644. },
  19645. addIndex: {
  19646. value: function ( index ) {
  19647. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  19648. this.setIndex( index );
  19649. }
  19650. },
  19651. addDrawCall: {
  19652. value: function ( start, count, indexOffset ) {
  19653. if ( indexOffset !== undefined ) {
  19654. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  19655. }
  19656. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  19657. this.addGroup( start, count );
  19658. }
  19659. },
  19660. clearDrawCalls: {
  19661. value: function () {
  19662. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  19663. this.clearGroups();
  19664. }
  19665. },
  19666. computeTangents: {
  19667. value: function () {
  19668. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  19669. }
  19670. },
  19671. computeOffsets: {
  19672. value: function () {
  19673. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  19674. }
  19675. }
  19676. } );
  19677. //
  19678. Object.defineProperties( THREE.Material.prototype, {
  19679. wrapAround: {
  19680. get: function () {
  19681. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19682. },
  19683. set: function ( value ) {
  19684. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  19685. }
  19686. },
  19687. wrapRGB: {
  19688. get: function () {
  19689. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  19690. return new THREE.Color();
  19691. }
  19692. }
  19693. } );
  19694. Object.defineProperties( THREE, {
  19695. PointCloudMaterial: {
  19696. value: function ( parameters ) {
  19697. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  19698. return new THREE.PointsMaterial( parameters );
  19699. }
  19700. },
  19701. ParticleBasicMaterial: {
  19702. value: function ( parameters ) {
  19703. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  19704. return new THREE.PointsMaterial( parameters );
  19705. }
  19706. },
  19707. ParticleSystemMaterial:{
  19708. value: function ( parameters ) {
  19709. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  19710. return new THREE.PointsMaterial( parameters );
  19711. }
  19712. }
  19713. } );
  19714. Object.defineProperties( THREE.MeshPhongMaterial.prototype, {
  19715. metal: {
  19716. get: function () {
  19717. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  19718. return false;
  19719. },
  19720. set: function ( value ) {
  19721. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  19722. }
  19723. }
  19724. } );
  19725. Object.defineProperties( THREE.ShaderMaterial.prototype, {
  19726. derivatives: {
  19727. get: function () {
  19728. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19729. return this.extensions.derivatives;
  19730. },
  19731. set: function ( value ) {
  19732. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  19733. this.extensions.derivatives = value;
  19734. }
  19735. }
  19736. } );
  19737. //
  19738. Object.defineProperties( THREE.WebGLRenderer.prototype, {
  19739. supportsFloatTextures: {
  19740. value: function () {
  19741. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  19742. return this.extensions.get( 'OES_texture_float' );
  19743. }
  19744. },
  19745. supportsHalfFloatTextures: {
  19746. value: function () {
  19747. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  19748. return this.extensions.get( 'OES_texture_half_float' );
  19749. }
  19750. },
  19751. supportsStandardDerivatives: {
  19752. value: function () {
  19753. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  19754. return this.extensions.get( 'OES_standard_derivatives' );
  19755. }
  19756. },
  19757. supportsCompressedTextureS3TC: {
  19758. value: function () {
  19759. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  19760. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  19761. }
  19762. },
  19763. supportsCompressedTexturePVRTC: {
  19764. value: function () {
  19765. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  19766. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  19767. }
  19768. },
  19769. supportsBlendMinMax: {
  19770. value: function () {
  19771. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  19772. return this.extensions.get( 'EXT_blend_minmax' );
  19773. }
  19774. },
  19775. supportsVertexTextures: {
  19776. value: function () {
  19777. return this.capabilities.vertexTextures;
  19778. }
  19779. },
  19780. supportsInstancedArrays: {
  19781. value: function () {
  19782. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  19783. return this.extensions.get( 'ANGLE_instanced_arrays' );
  19784. }
  19785. },
  19786. enableScissorTest: {
  19787. value: function ( boolean ) {
  19788. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  19789. this.setScissorTest( boolean );
  19790. }
  19791. },
  19792. initMaterial: {
  19793. value: function () {
  19794. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  19795. }
  19796. },
  19797. addPrePlugin: {
  19798. value: function () {
  19799. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  19800. }
  19801. },
  19802. addPostPlugin: {
  19803. value: function () {
  19804. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  19805. }
  19806. },
  19807. updateShadowMap: {
  19808. value: function () {
  19809. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  19810. }
  19811. },
  19812. shadowMapEnabled: {
  19813. get: function () {
  19814. return this.shadowMap.enabled;
  19815. },
  19816. set: function ( value ) {
  19817. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  19818. this.shadowMap.enabled = value;
  19819. }
  19820. },
  19821. shadowMapType: {
  19822. get: function () {
  19823. return this.shadowMap.type;
  19824. },
  19825. set: function ( value ) {
  19826. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  19827. this.shadowMap.type = value;
  19828. }
  19829. },
  19830. shadowMapCullFace: {
  19831. get: function () {
  19832. return this.shadowMap.cullFace;
  19833. },
  19834. set: function ( value ) {
  19835. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  19836. this.shadowMap.cullFace = value;
  19837. }
  19838. }
  19839. } );
  19840. //
  19841. Object.defineProperties( THREE.WebGLRenderTarget.prototype, {
  19842. wrapS: {
  19843. get: function () {
  19844. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19845. return this.texture.wrapS;
  19846. },
  19847. set: function ( value ) {
  19848. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  19849. this.texture.wrapS = value;
  19850. }
  19851. },
  19852. wrapT: {
  19853. get: function () {
  19854. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19855. return this.texture.wrapT;
  19856. },
  19857. set: function ( value ) {
  19858. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  19859. this.texture.wrapT = value;
  19860. }
  19861. },
  19862. magFilter: {
  19863. get: function () {
  19864. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19865. return this.texture.magFilter;
  19866. },
  19867. set: function ( value ) {
  19868. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  19869. this.texture.magFilter = value;
  19870. }
  19871. },
  19872. minFilter: {
  19873. get: function () {
  19874. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19875. return this.texture.minFilter;
  19876. },
  19877. set: function ( value ) {
  19878. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  19879. this.texture.minFilter = value;
  19880. }
  19881. },
  19882. anisotropy: {
  19883. get: function () {
  19884. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19885. return this.texture.anisotropy;
  19886. },
  19887. set: function ( value ) {
  19888. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  19889. this.texture.anisotropy = value;
  19890. }
  19891. },
  19892. offset: {
  19893. get: function () {
  19894. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19895. return this.texture.offset;
  19896. },
  19897. set: function ( value ) {
  19898. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  19899. this.texture.offset = value;
  19900. }
  19901. },
  19902. repeat: {
  19903. get: function () {
  19904. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19905. return this.texture.repeat;
  19906. },
  19907. set: function ( value ) {
  19908. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  19909. this.texture.repeat = value;
  19910. }
  19911. },
  19912. format: {
  19913. get: function () {
  19914. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19915. return this.texture.format;
  19916. },
  19917. set: function ( value ) {
  19918. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  19919. this.texture.format = value;
  19920. }
  19921. },
  19922. type: {
  19923. get: function () {
  19924. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19925. return this.texture.type;
  19926. },
  19927. set: function ( value ) {
  19928. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  19929. this.texture.type = value;
  19930. }
  19931. },
  19932. generateMipmaps: {
  19933. get: function () {
  19934. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19935. return this.texture.generateMipmaps;
  19936. },
  19937. set: function ( value ) {
  19938. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  19939. this.texture.generateMipmaps = value;
  19940. }
  19941. }
  19942. } );
  19943. //
  19944. Object.defineProperties( THREE.Audio.prototype, {
  19945. load: {
  19946. value: function ( file ) {
  19947. console.warn( 'THREE.Audio: .load has been deprecated. Please use THREE.AudioLoader.' );
  19948. var scope = this;
  19949. var audioLoader = new THREE.AudioLoader();
  19950. audioLoader.load( file, function ( buffer ) {
  19951. scope.setBuffer( buffer );
  19952. } );
  19953. return this;
  19954. }
  19955. }
  19956. } );
  19957. //
  19958. THREE.GeometryUtils = {
  19959. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  19960. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  19961. var matrix;
  19962. if ( geometry2 instanceof THREE.Mesh ) {
  19963. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  19964. matrix = geometry2.matrix;
  19965. geometry2 = geometry2.geometry;
  19966. }
  19967. geometry1.merge( geometry2, matrix, materialIndexOffset );
  19968. },
  19969. center: function ( geometry ) {
  19970. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  19971. return geometry.center();
  19972. }
  19973. };
  19974. THREE.ImageUtils = {
  19975. crossOrigin: undefined,
  19976. loadTexture: function ( url, mapping, onLoad, onError ) {
  19977. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  19978. var loader = new THREE.TextureLoader();
  19979. loader.setCrossOrigin( this.crossOrigin );
  19980. var texture = loader.load( url, onLoad, undefined, onError );
  19981. if ( mapping ) texture.mapping = mapping;
  19982. return texture;
  19983. },
  19984. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  19985. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  19986. var loader = new THREE.CubeTextureLoader();
  19987. loader.setCrossOrigin( this.crossOrigin );
  19988. var texture = loader.load( urls, onLoad, undefined, onError );
  19989. if ( mapping ) texture.mapping = mapping;
  19990. return texture;
  19991. },
  19992. loadCompressedTexture: function () {
  19993. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  19994. },
  19995. loadCompressedTextureCube: function () {
  19996. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  19997. }
  19998. };
  19999. //
  20000. THREE.Projector = function () {
  20001. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  20002. this.projectVector = function ( vector, camera ) {
  20003. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  20004. vector.project( camera );
  20005. };
  20006. this.unprojectVector = function ( vector, camera ) {
  20007. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  20008. vector.unproject( camera );
  20009. };
  20010. this.pickingRay = function ( vector, camera ) {
  20011. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  20012. };
  20013. };
  20014. //
  20015. THREE.CanvasRenderer = function () {
  20016. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  20017. this.domElement = document.createElement( 'canvas' );
  20018. this.clear = function () {};
  20019. this.render = function () {};
  20020. this.setClearColor = function () {};
  20021. this.setSize = function () {};
  20022. };
  20023. //
  20024. THREE.MeshFaceMaterial = THREE.MultiMaterial;
  20025. //
  20026. Object.defineProperties( THREE.LOD.prototype, {
  20027. objects: {
  20028. get: function () {
  20029. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  20030. return this.levels;
  20031. }
  20032. }
  20033. } );
  20034. // File:src/extras/CurveUtils.js
  20035. /**
  20036. * @author zz85 / http://www.lab4games.net/zz85/blog
  20037. */
  20038. THREE.CurveUtils = {
  20039. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  20040. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  20041. },
  20042. // Puay Bing, thanks for helping with this derivative!
  20043. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  20044. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  20045. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  20046. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  20047. 3 * t * t * p3;
  20048. },
  20049. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  20050. // To check if my formulas are correct
  20051. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  20052. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  20053. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  20054. var h11 = 3 * t * t - 2 * t; // t3 − t2
  20055. return h00 + h10 + h01 + h11;
  20056. },
  20057. // Catmull-Rom
  20058. interpolate: function( p0, p1, p2, p3, t ) {
  20059. var v0 = ( p2 - p0 ) * 0.5;
  20060. var v1 = ( p3 - p1 ) * 0.5;
  20061. var t2 = t * t;
  20062. var t3 = t * t2;
  20063. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  20064. }
  20065. };
  20066. // File:src/extras/SceneUtils.js
  20067. /**
  20068. * @author alteredq / http://alteredqualia.com/
  20069. */
  20070. THREE.SceneUtils = {
  20071. createMultiMaterialObject: function ( geometry, materials ) {
  20072. var group = new THREE.Group();
  20073. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  20074. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  20075. }
  20076. return group;
  20077. },
  20078. detach: function ( child, parent, scene ) {
  20079. child.applyMatrix( parent.matrixWorld );
  20080. parent.remove( child );
  20081. scene.add( child );
  20082. },
  20083. attach: function ( child, scene, parent ) {
  20084. var matrixWorldInverse = new THREE.Matrix4();
  20085. matrixWorldInverse.getInverse( parent.matrixWorld );
  20086. child.applyMatrix( matrixWorldInverse );
  20087. scene.remove( child );
  20088. parent.add( child );
  20089. }
  20090. };
  20091. // File:src/extras/ShapeUtils.js
  20092. /**
  20093. * @author zz85 / http://www.lab4games.net/zz85/blog
  20094. */
  20095. THREE.ShapeUtils = {
  20096. // calculate area of the contour polygon
  20097. area: function ( contour ) {
  20098. var n = contour.length;
  20099. var a = 0.0;
  20100. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  20101. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20102. }
  20103. return a * 0.5;
  20104. },
  20105. triangulate: ( function () {
  20106. /**
  20107. * This code is a quick port of code written in C++ which was submitted to
  20108. * flipcode.com by John W. Ratcliff // July 22, 2000
  20109. * See original code and more information here:
  20110. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  20111. *
  20112. * ported to actionscript by Zevan Rosser
  20113. * www.actionsnippet.com
  20114. *
  20115. * ported to javascript by Joshua Koo
  20116. * http://www.lab4games.net/zz85/blog
  20117. *
  20118. */
  20119. function snip( contour, u, v, w, n, verts ) {
  20120. var p;
  20121. var ax, ay, bx, by;
  20122. var cx, cy, px, py;
  20123. ax = contour[ verts[ u ] ].x;
  20124. ay = contour[ verts[ u ] ].y;
  20125. bx = contour[ verts[ v ] ].x;
  20126. by = contour[ verts[ v ] ].y;
  20127. cx = contour[ verts[ w ] ].x;
  20128. cy = contour[ verts[ w ] ].y;
  20129. if ( Number.EPSILON > ( ( ( bx - ax ) * ( cy - ay ) ) - ( ( by - ay ) * ( cx - ax ) ) ) ) return false;
  20130. var aX, aY, bX, bY, cX, cY;
  20131. var apx, apy, bpx, bpy, cpx, cpy;
  20132. var cCROSSap, bCROSScp, aCROSSbp;
  20133. aX = cx - bx; aY = cy - by;
  20134. bX = ax - cx; bY = ay - cy;
  20135. cX = bx - ax; cY = by - ay;
  20136. for ( p = 0; p < n; p ++ ) {
  20137. px = contour[ verts[ p ] ].x;
  20138. py = contour[ verts[ p ] ].y;
  20139. if ( ( ( px === ax ) && ( py === ay ) ) ||
  20140. ( ( px === bx ) && ( py === by ) ) ||
  20141. ( ( px === cx ) && ( py === cy ) ) ) continue;
  20142. apx = px - ax; apy = py - ay;
  20143. bpx = px - bx; bpy = py - by;
  20144. cpx = px - cx; cpy = py - cy;
  20145. // see if p is inside triangle abc
  20146. aCROSSbp = aX * bpy - aY * bpx;
  20147. cCROSSap = cX * apy - cY * apx;
  20148. bCROSScp = bX * cpy - bY * cpx;
  20149. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  20150. }
  20151. return true;
  20152. }
  20153. // takes in an contour array and returns
  20154. return function ( contour, indices ) {
  20155. var n = contour.length;
  20156. if ( n < 3 ) return null;
  20157. var result = [],
  20158. verts = [],
  20159. vertIndices = [];
  20160. /* we want a counter-clockwise polygon in verts */
  20161. var u, v, w;
  20162. if ( THREE.ShapeUtils.area( contour ) > 0.0 ) {
  20163. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  20164. } else {
  20165. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  20166. }
  20167. var nv = n;
  20168. /* remove nv - 2 vertices, creating 1 triangle every time */
  20169. var count = 2 * nv; /* error detection */
  20170. for ( v = nv - 1; nv > 2; ) {
  20171. /* if we loop, it is probably a non-simple polygon */
  20172. if ( ( count -- ) <= 0 ) {
  20173. //** Triangulate: ERROR - probable bad polygon!
  20174. //throw ( "Warning, unable to triangulate polygon!" );
  20175. //return null;
  20176. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  20177. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  20178. if ( indices ) return vertIndices;
  20179. return result;
  20180. }
  20181. /* three consecutive vertices in current polygon, <u,v,w> */
  20182. u = v; if ( nv <= u ) u = 0; /* previous */
  20183. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  20184. w = v + 1; if ( nv <= w ) w = 0; /* next */
  20185. if ( snip( contour, u, v, w, nv, verts ) ) {
  20186. var a, b, c, s, t;
  20187. /* true names of the vertices */
  20188. a = verts[ u ];
  20189. b = verts[ v ];
  20190. c = verts[ w ];
  20191. /* output Triangle */
  20192. result.push( [ contour[ a ],
  20193. contour[ b ],
  20194. contour[ c ] ] );
  20195. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  20196. /* remove v from the remaining polygon */
  20197. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  20198. verts[ s ] = verts[ t ];
  20199. }
  20200. nv --;
  20201. /* reset error detection counter */
  20202. count = 2 * nv;
  20203. }
  20204. }
  20205. if ( indices ) return vertIndices;
  20206. return result;
  20207. }
  20208. } )(),
  20209. triangulateShape: function ( contour, holes ) {
  20210. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  20211. // inOtherPt needs to be collinear to the inSegment
  20212. if ( inSegPt1.x !== inSegPt2.x ) {
  20213. if ( inSegPt1.x < inSegPt2.x ) {
  20214. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  20215. } else {
  20216. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  20217. }
  20218. } else {
  20219. if ( inSegPt1.y < inSegPt2.y ) {
  20220. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  20221. } else {
  20222. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  20223. }
  20224. }
  20225. }
  20226. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  20227. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  20228. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  20229. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  20230. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  20231. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  20232. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  20233. if ( Math.abs( limit ) > Number.EPSILON ) {
  20234. // not parallel
  20235. var perpSeg2;
  20236. if ( limit > 0 ) {
  20237. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  20238. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  20239. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  20240. } else {
  20241. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  20242. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  20243. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  20244. }
  20245. // i.e. to reduce rounding errors
  20246. // intersection at endpoint of segment#1?
  20247. if ( perpSeg2 === 0 ) {
  20248. if ( ( inExcludeAdjacentSegs ) &&
  20249. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  20250. return [ inSeg1Pt1 ];
  20251. }
  20252. if ( perpSeg2 === limit ) {
  20253. if ( ( inExcludeAdjacentSegs ) &&
  20254. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  20255. return [ inSeg1Pt2 ];
  20256. }
  20257. // intersection at endpoint of segment#2?
  20258. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  20259. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  20260. // return real intersection point
  20261. var factorSeg1 = perpSeg2 / limit;
  20262. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  20263. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  20264. } else {
  20265. // parallel or collinear
  20266. if ( ( perpSeg1 !== 0 ) ||
  20267. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  20268. // they are collinear or degenerate
  20269. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  20270. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  20271. // both segments are points
  20272. if ( seg1Pt && seg2Pt ) {
  20273. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  20274. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  20275. return [ inSeg1Pt1 ]; // they are the same point
  20276. }
  20277. // segment#1 is a single point
  20278. if ( seg1Pt ) {
  20279. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  20280. return [ inSeg1Pt1 ];
  20281. }
  20282. // segment#2 is a single point
  20283. if ( seg2Pt ) {
  20284. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  20285. return [ inSeg2Pt1 ];
  20286. }
  20287. // they are collinear segments, which might overlap
  20288. var seg1min, seg1max, seg1minVal, seg1maxVal;
  20289. var seg2min, seg2max, seg2minVal, seg2maxVal;
  20290. if ( seg1dx !== 0 ) {
  20291. // the segments are NOT on a vertical line
  20292. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  20293. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  20294. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  20295. } else {
  20296. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  20297. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  20298. }
  20299. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  20300. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  20301. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  20302. } else {
  20303. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  20304. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  20305. }
  20306. } else {
  20307. // the segments are on a vertical line
  20308. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  20309. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  20310. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  20311. } else {
  20312. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  20313. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  20314. }
  20315. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  20316. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  20317. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  20318. } else {
  20319. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  20320. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  20321. }
  20322. }
  20323. if ( seg1minVal <= seg2minVal ) {
  20324. if ( seg1maxVal < seg2minVal ) return [];
  20325. if ( seg1maxVal === seg2minVal ) {
  20326. if ( inExcludeAdjacentSegs ) return [];
  20327. return [ seg2min ];
  20328. }
  20329. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  20330. return [ seg2min, seg2max ];
  20331. } else {
  20332. if ( seg1minVal > seg2maxVal ) return [];
  20333. if ( seg1minVal === seg2maxVal ) {
  20334. if ( inExcludeAdjacentSegs ) return [];
  20335. return [ seg1min ];
  20336. }
  20337. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  20338. return [ seg1min, seg2max ];
  20339. }
  20340. }
  20341. }
  20342. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  20343. // The order of legs is important
  20344. // translation of all points, so that Vertex is at (0,0)
  20345. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  20346. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  20347. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  20348. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  20349. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  20350. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  20351. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  20352. // angle != 180 deg.
  20353. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  20354. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  20355. if ( from2toAngle > 0 ) {
  20356. // main angle < 180 deg.
  20357. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  20358. } else {
  20359. // main angle > 180 deg.
  20360. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  20361. }
  20362. } else {
  20363. // angle == 180 deg.
  20364. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  20365. return ( from2otherAngle > 0 );
  20366. }
  20367. }
  20368. function removeHoles( contour, holes ) {
  20369. var shape = contour.concat(); // work on this shape
  20370. var hole;
  20371. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  20372. // Check if hole point lies within angle around shape point
  20373. var lastShapeIdx = shape.length - 1;
  20374. var prevShapeIdx = inShapeIdx - 1;
  20375. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  20376. var nextShapeIdx = inShapeIdx + 1;
  20377. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  20378. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  20379. if ( ! insideAngle ) {
  20380. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  20381. return false;
  20382. }
  20383. // Check if shape point lies within angle around hole point
  20384. var lastHoleIdx = hole.length - 1;
  20385. var prevHoleIdx = inHoleIdx - 1;
  20386. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  20387. var nextHoleIdx = inHoleIdx + 1;
  20388. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  20389. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  20390. if ( ! insideAngle ) {
  20391. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  20392. return false;
  20393. }
  20394. return true;
  20395. }
  20396. function intersectsShapeEdge( inShapePt, inHolePt ) {
  20397. // checks for intersections with shape edges
  20398. var sIdx, nextIdx, intersection;
  20399. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  20400. nextIdx = sIdx + 1; nextIdx %= shape.length;
  20401. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  20402. if ( intersection.length > 0 ) return true;
  20403. }
  20404. return false;
  20405. }
  20406. var indepHoles = [];
  20407. function intersectsHoleEdge( inShapePt, inHolePt ) {
  20408. // checks for intersections with hole edges
  20409. var ihIdx, chkHole,
  20410. hIdx, nextIdx, intersection;
  20411. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  20412. chkHole = holes[ indepHoles[ ihIdx ]];
  20413. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  20414. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  20415. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  20416. if ( intersection.length > 0 ) return true;
  20417. }
  20418. }
  20419. return false;
  20420. }
  20421. var holeIndex, shapeIndex,
  20422. shapePt, holePt,
  20423. holeIdx, cutKey, failedCuts = [],
  20424. tmpShape1, tmpShape2,
  20425. tmpHole1, tmpHole2;
  20426. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  20427. indepHoles.push( h );
  20428. }
  20429. var minShapeIndex = 0;
  20430. var counter = indepHoles.length * 2;
  20431. while ( indepHoles.length > 0 ) {
  20432. counter --;
  20433. if ( counter < 0 ) {
  20434. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  20435. break;
  20436. }
  20437. // search for shape-vertex and hole-vertex,
  20438. // which can be connected without intersections
  20439. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  20440. shapePt = shape[ shapeIndex ];
  20441. holeIndex = - 1;
  20442. // search for hole which can be reached without intersections
  20443. for ( var h = 0; h < indepHoles.length; h ++ ) {
  20444. holeIdx = indepHoles[ h ];
  20445. // prevent multiple checks
  20446. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  20447. if ( failedCuts[ cutKey ] !== undefined ) continue;
  20448. hole = holes[ holeIdx ];
  20449. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  20450. holePt = hole[ h2 ];
  20451. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  20452. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  20453. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  20454. holeIndex = h2;
  20455. indepHoles.splice( h, 1 );
  20456. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  20457. tmpShape2 = shape.slice( shapeIndex );
  20458. tmpHole1 = hole.slice( holeIndex );
  20459. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  20460. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  20461. minShapeIndex = shapeIndex;
  20462. // Debug only, to show the selected cuts
  20463. // glob_CutLines.push( [ shapePt, holePt ] );
  20464. break;
  20465. }
  20466. if ( holeIndex >= 0 ) break; // hole-vertex found
  20467. failedCuts[ cutKey ] = true; // remember failure
  20468. }
  20469. if ( holeIndex >= 0 ) break; // hole-vertex found
  20470. }
  20471. }
  20472. return shape; /* shape with no holes */
  20473. }
  20474. var i, il, f, face,
  20475. key, index,
  20476. allPointsMap = {};
  20477. // 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.
  20478. var allpoints = contour.concat();
  20479. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  20480. Array.prototype.push.apply( allpoints, holes[ h ] );
  20481. }
  20482. //console.log( "allpoints",allpoints, allpoints.length );
  20483. // prepare all points map
  20484. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  20485. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  20486. if ( allPointsMap[ key ] !== undefined ) {
  20487. console.warn( "THREE.Shape: Duplicate point", key );
  20488. }
  20489. allPointsMap[ key ] = i;
  20490. }
  20491. // remove holes by cutting paths to holes and adding them to the shape
  20492. var shapeWithoutHoles = removeHoles( contour, holes );
  20493. var triangles = THREE.ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  20494. //console.log( "triangles",triangles, triangles.length );
  20495. // check all face vertices against all points map
  20496. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  20497. face = triangles[ i ];
  20498. for ( f = 0; f < 3; f ++ ) {
  20499. key = face[ f ].x + ":" + face[ f ].y;
  20500. index = allPointsMap[ key ];
  20501. if ( index !== undefined ) {
  20502. face[ f ] = index;
  20503. }
  20504. }
  20505. }
  20506. return triangles.concat();
  20507. },
  20508. isClockWise: function ( pts ) {
  20509. return THREE.ShapeUtils.area( pts ) < 0;
  20510. },
  20511. // Bezier Curves formulas obtained from
  20512. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  20513. // Quad Bezier Functions
  20514. b2: ( function () {
  20515. function b2p0( t, p ) {
  20516. var k = 1 - t;
  20517. return k * k * p;
  20518. }
  20519. function b2p1( t, p ) {
  20520. return 2 * ( 1 - t ) * t * p;
  20521. }
  20522. function b2p2( t, p ) {
  20523. return t * t * p;
  20524. }
  20525. return function ( t, p0, p1, p2 ) {
  20526. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  20527. };
  20528. } )(),
  20529. // Cubic Bezier Functions
  20530. b3: ( function () {
  20531. function b3p0( t, p ) {
  20532. var k = 1 - t;
  20533. return k * k * k * p;
  20534. }
  20535. function b3p1( t, p ) {
  20536. var k = 1 - t;
  20537. return 3 * k * k * t * p;
  20538. }
  20539. function b3p2( t, p ) {
  20540. var k = 1 - t;
  20541. return 3 * k * t * t * p;
  20542. }
  20543. function b3p3( t, p ) {
  20544. return t * t * t * p;
  20545. }
  20546. return function ( t, p0, p1, p2, p3 ) {
  20547. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  20548. };
  20549. } )()
  20550. };
  20551. // File:src/extras/core/Curve.js
  20552. /**
  20553. * @author zz85 / http://www.lab4games.net/zz85/blog
  20554. * Extensible curve object
  20555. *
  20556. * Some common of Curve methods
  20557. * .getPoint(t), getTangent(t)
  20558. * .getPointAt(u), getTagentAt(u)
  20559. * .getPoints(), .getSpacedPoints()
  20560. * .getLength()
  20561. * .updateArcLengths()
  20562. *
  20563. * This following classes subclasses THREE.Curve:
  20564. *
  20565. * -- 2d classes --
  20566. * THREE.LineCurve
  20567. * THREE.QuadraticBezierCurve
  20568. * THREE.CubicBezierCurve
  20569. * THREE.SplineCurve
  20570. * THREE.ArcCurve
  20571. * THREE.EllipseCurve
  20572. *
  20573. * -- 3d classes --
  20574. * THREE.LineCurve3
  20575. * THREE.QuadraticBezierCurve3
  20576. * THREE.CubicBezierCurve3
  20577. * THREE.SplineCurve3
  20578. *
  20579. * A series of curves can be represented as a THREE.CurvePath
  20580. *
  20581. **/
  20582. /**************************************************************
  20583. * Abstract Curve base class
  20584. **************************************************************/
  20585. THREE.Curve = function () {
  20586. };
  20587. THREE.Curve.prototype = {
  20588. constructor: THREE.Curve,
  20589. // Virtual base class method to overwrite and implement in subclasses
  20590. // - t [0 .. 1]
  20591. getPoint: function ( t ) {
  20592. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  20593. return null;
  20594. },
  20595. // Get point at relative position in curve according to arc length
  20596. // - u [0 .. 1]
  20597. getPointAt: function ( u ) {
  20598. var t = this.getUtoTmapping( u );
  20599. return this.getPoint( t );
  20600. },
  20601. // Get sequence of points using getPoint( t )
  20602. getPoints: function ( divisions ) {
  20603. if ( ! divisions ) divisions = 5;
  20604. var d, pts = [];
  20605. for ( d = 0; d <= divisions; d ++ ) {
  20606. pts.push( this.getPoint( d / divisions ) );
  20607. }
  20608. return pts;
  20609. },
  20610. // Get sequence of points using getPointAt( u )
  20611. getSpacedPoints: function ( divisions ) {
  20612. if ( ! divisions ) divisions = 5;
  20613. var d, pts = [];
  20614. for ( d = 0; d <= divisions; d ++ ) {
  20615. pts.push( this.getPointAt( d / divisions ) );
  20616. }
  20617. return pts;
  20618. },
  20619. // Get total curve arc length
  20620. getLength: function () {
  20621. var lengths = this.getLengths();
  20622. return lengths[ lengths.length - 1 ];
  20623. },
  20624. // Get list of cumulative segment lengths
  20625. getLengths: function ( divisions ) {
  20626. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  20627. if ( this.cacheArcLengths
  20628. && ( this.cacheArcLengths.length === divisions + 1 )
  20629. && ! this.needsUpdate ) {
  20630. //console.log( "cached", this.cacheArcLengths );
  20631. return this.cacheArcLengths;
  20632. }
  20633. this.needsUpdate = false;
  20634. var cache = [];
  20635. var current, last = this.getPoint( 0 );
  20636. var p, sum = 0;
  20637. cache.push( 0 );
  20638. for ( p = 1; p <= divisions; p ++ ) {
  20639. current = this.getPoint ( p / divisions );
  20640. sum += current.distanceTo( last );
  20641. cache.push( sum );
  20642. last = current;
  20643. }
  20644. this.cacheArcLengths = cache;
  20645. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  20646. },
  20647. updateArcLengths: function() {
  20648. this.needsUpdate = true;
  20649. this.getLengths();
  20650. },
  20651. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  20652. getUtoTmapping: function ( u, distance ) {
  20653. var arcLengths = this.getLengths();
  20654. var i = 0, il = arcLengths.length;
  20655. var targetArcLength; // The targeted u distance value to get
  20656. if ( distance ) {
  20657. targetArcLength = distance;
  20658. } else {
  20659. targetArcLength = u * arcLengths[ il - 1 ];
  20660. }
  20661. //var time = Date.now();
  20662. // binary search for the index with largest value smaller than target u distance
  20663. var low = 0, high = il - 1, comparison;
  20664. while ( low <= high ) {
  20665. 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
  20666. comparison = arcLengths[ i ] - targetArcLength;
  20667. if ( comparison < 0 ) {
  20668. low = i + 1;
  20669. } else if ( comparison > 0 ) {
  20670. high = i - 1;
  20671. } else {
  20672. high = i;
  20673. break;
  20674. // DONE
  20675. }
  20676. }
  20677. i = high;
  20678. //console.log('b' , i, low, high, Date.now()- time);
  20679. if ( arcLengths[ i ] === targetArcLength ) {
  20680. var t = i / ( il - 1 );
  20681. return t;
  20682. }
  20683. // we could get finer grain at lengths, or use simple interpolation between two points
  20684. var lengthBefore = arcLengths[ i ];
  20685. var lengthAfter = arcLengths[ i + 1 ];
  20686. var segmentLength = lengthAfter - lengthBefore;
  20687. // determine where we are between the 'before' and 'after' points
  20688. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  20689. // add that fractional amount to t
  20690. var t = ( i + segmentFraction ) / ( il - 1 );
  20691. return t;
  20692. },
  20693. // Returns a unit vector tangent at t
  20694. // In case any sub curve does not implement its tangent derivation,
  20695. // 2 points a small delta apart will be used to find its gradient
  20696. // which seems to give a reasonable approximation
  20697. getTangent: function( t ) {
  20698. var delta = 0.0001;
  20699. var t1 = t - delta;
  20700. var t2 = t + delta;
  20701. // Capping in case of danger
  20702. if ( t1 < 0 ) t1 = 0;
  20703. if ( t2 > 1 ) t2 = 1;
  20704. var pt1 = this.getPoint( t1 );
  20705. var pt2 = this.getPoint( t2 );
  20706. var vec = pt2.clone().sub( pt1 );
  20707. return vec.normalize();
  20708. },
  20709. getTangentAt: function ( u ) {
  20710. var t = this.getUtoTmapping( u );
  20711. return this.getTangent( t );
  20712. }
  20713. };
  20714. // TODO: Transformation for Curves?
  20715. /**************************************************************
  20716. * 3D Curves
  20717. **************************************************************/
  20718. // A Factory method for creating new curve subclasses
  20719. THREE.Curve.create = function ( constructor, getPointFunc ) {
  20720. constructor.prototype = Object.create( THREE.Curve.prototype );
  20721. constructor.prototype.constructor = constructor;
  20722. constructor.prototype.getPoint = getPointFunc;
  20723. return constructor;
  20724. };
  20725. // File:src/extras/core/CurvePath.js
  20726. /**
  20727. * @author zz85 / http://www.lab4games.net/zz85/blog
  20728. *
  20729. **/
  20730. /**************************************************************
  20731. * Curved Path - a curve path is simply a array of connected
  20732. * curves, but retains the api of a curve
  20733. **************************************************************/
  20734. THREE.CurvePath = function () {
  20735. this.curves = [];
  20736. this.autoClose = false; // Automatically closes the path
  20737. };
  20738. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  20739. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  20740. THREE.CurvePath.prototype.add = function ( curve ) {
  20741. this.curves.push( curve );
  20742. };
  20743. /*
  20744. THREE.CurvePath.prototype.checkConnection = function() {
  20745. // TODO
  20746. // If the ending of curve is not connected to the starting
  20747. // or the next curve, then, this is not a real path
  20748. };
  20749. */
  20750. THREE.CurvePath.prototype.closePath = function() {
  20751. // TODO Test
  20752. // and verify for vector3 (needs to implement equals)
  20753. // Add a line curve if start and end of lines are not connected
  20754. var startPoint = this.curves[ 0 ].getPoint( 0 );
  20755. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  20756. if ( ! startPoint.equals( endPoint ) ) {
  20757. this.curves.push( new THREE.LineCurve( endPoint, startPoint ) );
  20758. }
  20759. };
  20760. // To get accurate point with reference to
  20761. // entire path distance at time t,
  20762. // following has to be done:
  20763. // 1. Length of each sub path have to be known
  20764. // 2. Locate and identify type of curve
  20765. // 3. Get t for the curve
  20766. // 4. Return curve.getPointAt(t')
  20767. THREE.CurvePath.prototype.getPoint = function( t ) {
  20768. var d = t * this.getLength();
  20769. var curveLengths = this.getCurveLengths();
  20770. var i = 0;
  20771. // To think about boundaries points.
  20772. while ( i < curveLengths.length ) {
  20773. if ( curveLengths[ i ] >= d ) {
  20774. var diff = curveLengths[ i ] - d;
  20775. var curve = this.curves[ i ];
  20776. var u = 1 - diff / curve.getLength();
  20777. return curve.getPointAt( u );
  20778. }
  20779. i ++;
  20780. }
  20781. return null;
  20782. // loop where sum != 0, sum > d , sum+1 <d
  20783. };
  20784. /*
  20785. THREE.CurvePath.prototype.getTangent = function( t ) {
  20786. };
  20787. */
  20788. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  20789. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  20790. // getPoint() depends on getLength
  20791. THREE.CurvePath.prototype.getLength = function() {
  20792. var lens = this.getCurveLengths();
  20793. return lens[ lens.length - 1 ];
  20794. };
  20795. // Compute lengths and cache them
  20796. // We cannot overwrite getLengths() because UtoT mapping uses it.
  20797. THREE.CurvePath.prototype.getCurveLengths = function() {
  20798. // We use cache values if curves and cache array are same length
  20799. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  20800. return this.cacheLengths;
  20801. }
  20802. // Get length of sub-curve
  20803. // Push sums into cached array
  20804. var lengths = [], sums = 0;
  20805. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  20806. sums += this.curves[ i ].getLength();
  20807. lengths.push( sums );
  20808. }
  20809. this.cacheLengths = lengths;
  20810. return lengths;
  20811. };
  20812. /**************************************************************
  20813. * Create Geometries Helpers
  20814. **************************************************************/
  20815. /// Generate geometry from path points (for Line or Points objects)
  20816. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  20817. var pts = this.getPoints( divisions );
  20818. return this.createGeometry( pts );
  20819. };
  20820. // Generate geometry from equidistant sampling along the path
  20821. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  20822. var pts = this.getSpacedPoints( divisions );
  20823. return this.createGeometry( pts );
  20824. };
  20825. THREE.CurvePath.prototype.createGeometry = function( points ) {
  20826. var geometry = new THREE.Geometry();
  20827. for ( var i = 0, l = points.length; i < l; i ++ ) {
  20828. var point = points[ i ];
  20829. geometry.vertices.push( new THREE.Vector3( point.x, point.y, point.z || 0 ) );
  20830. }
  20831. return geometry;
  20832. };
  20833. // File:src/extras/core/Font.js
  20834. /**
  20835. * @author zz85 / http://www.lab4games.net/zz85/blog
  20836. * @author mrdoob / http://mrdoob.com/
  20837. */
  20838. THREE.Font = function ( data ) {
  20839. this.data = data;
  20840. };
  20841. THREE.Font.prototype = {
  20842. constructor: THREE.Font,
  20843. generateShapes: function ( text, size, divisions ) {
  20844. function createPaths( text ) {
  20845. var chars = String( text ).split( '' );
  20846. var scale = size / data.resolution;
  20847. var offset = 0;
  20848. var paths = [];
  20849. for ( var i = 0; i < chars.length; i ++ ) {
  20850. var ret = createPath( chars[ i ], scale, offset );
  20851. offset += ret.offset;
  20852. paths.push( ret.path );
  20853. }
  20854. return paths;
  20855. }
  20856. function createPath( c, scale, offset ) {
  20857. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  20858. if ( ! glyph ) return;
  20859. var path = new THREE.Path();
  20860. var pts = [], b2 = THREE.ShapeUtils.b2, b3 = THREE.ShapeUtils.b3;
  20861. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  20862. if ( glyph.o ) {
  20863. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  20864. for ( var i = 0, l = outline.length; i < l; ) {
  20865. var action = outline[ i ++ ];
  20866. switch ( action ) {
  20867. case 'm': // moveTo
  20868. x = outline[ i ++ ] * scale + offset;
  20869. y = outline[ i ++ ] * scale;
  20870. path.moveTo( x, y );
  20871. break;
  20872. case 'l': // lineTo
  20873. x = outline[ i ++ ] * scale + offset;
  20874. y = outline[ i ++ ] * scale;
  20875. path.lineTo( x, y );
  20876. break;
  20877. case 'q': // quadraticCurveTo
  20878. cpx = outline[ i ++ ] * scale + offset;
  20879. cpy = outline[ i ++ ] * scale;
  20880. cpx1 = outline[ i ++ ] * scale + offset;
  20881. cpy1 = outline[ i ++ ] * scale;
  20882. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  20883. laste = pts[ pts.length - 1 ];
  20884. if ( laste ) {
  20885. cpx0 = laste.x;
  20886. cpy0 = laste.y;
  20887. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  20888. var t = i2 / divisions;
  20889. b2( t, cpx0, cpx1, cpx );
  20890. b2( t, cpy0, cpy1, cpy );
  20891. }
  20892. }
  20893. break;
  20894. case 'b': // bezierCurveTo
  20895. cpx = outline[ i ++ ] * scale + offset;
  20896. cpy = outline[ i ++ ] * scale;
  20897. cpx1 = outline[ i ++ ] * scale + offset;
  20898. cpy1 = outline[ i ++ ] * scale;
  20899. cpx2 = outline[ i ++ ] * scale + offset;
  20900. cpy2 = outline[ i ++ ] * scale;
  20901. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  20902. laste = pts[ pts.length - 1 ];
  20903. if ( laste ) {
  20904. cpx0 = laste.x;
  20905. cpy0 = laste.y;
  20906. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  20907. var t = i2 / divisions;
  20908. b3( t, cpx0, cpx1, cpx2, cpx );
  20909. b3( t, cpy0, cpy1, cpy2, cpy );
  20910. }
  20911. }
  20912. break;
  20913. }
  20914. }
  20915. }
  20916. return { offset: glyph.ha * scale, path: path };
  20917. }
  20918. //
  20919. if ( size === undefined ) size = 100;
  20920. if ( divisions === undefined ) divisions = 4;
  20921. var data = this.data;
  20922. var paths = createPaths( text );
  20923. var shapes = [];
  20924. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  20925. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  20926. }
  20927. return shapes;
  20928. }
  20929. };
  20930. // File:src/extras/core/Path.js
  20931. /**
  20932. * @author zz85 / http://www.lab4games.net/zz85/blog
  20933. * Creates free form 2d path using series of points, lines or curves.
  20934. *
  20935. **/
  20936. THREE.Path = function ( points ) {
  20937. THREE.CurvePath.call( this );
  20938. this.actions = [];
  20939. if ( points ) {
  20940. this.fromPoints( points );
  20941. }
  20942. };
  20943. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  20944. THREE.Path.prototype.constructor = THREE.Path;
  20945. // TODO Clean up PATH API
  20946. // Create path using straight lines to connect all points
  20947. // - vectors: array of Vector2
  20948. THREE.Path.prototype.fromPoints = function ( vectors ) {
  20949. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  20950. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  20951. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  20952. }
  20953. };
  20954. // startPath() endPath()?
  20955. THREE.Path.prototype.moveTo = function ( x, y ) {
  20956. this.actions.push( { action: 'moveTo', args: [ x, y ] } );
  20957. };
  20958. THREE.Path.prototype.lineTo = function ( x, y ) {
  20959. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20960. var x0 = lastargs[ lastargs.length - 2 ];
  20961. var y0 = lastargs[ lastargs.length - 1 ];
  20962. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  20963. this.curves.push( curve );
  20964. this.actions.push( { action: 'lineTo', args: [ x, y ] } );
  20965. };
  20966. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  20967. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20968. var x0 = lastargs[ lastargs.length - 2 ];
  20969. var y0 = lastargs[ lastargs.length - 1 ];
  20970. var curve = new THREE.QuadraticBezierCurve(
  20971. new THREE.Vector2( x0, y0 ),
  20972. new THREE.Vector2( aCPx, aCPy ),
  20973. new THREE.Vector2( aX, aY )
  20974. );
  20975. this.curves.push( curve );
  20976. this.actions.push( { action: 'quadraticCurveTo', args: [ aCPx, aCPy, aX, aY ] } );
  20977. };
  20978. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  20979. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20980. var x0 = lastargs[ lastargs.length - 2 ];
  20981. var y0 = lastargs[ lastargs.length - 1 ];
  20982. var curve = new THREE.CubicBezierCurve(
  20983. new THREE.Vector2( x0, y0 ),
  20984. new THREE.Vector2( aCP1x, aCP1y ),
  20985. new THREE.Vector2( aCP2x, aCP2y ),
  20986. new THREE.Vector2( aX, aY )
  20987. );
  20988. this.curves.push( curve );
  20989. this.actions.push( { action: 'bezierCurveTo', args: [ aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ] } );
  20990. };
  20991. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  20992. var args = Array.prototype.slice.call( arguments );
  20993. var lastargs = this.actions[ this.actions.length - 1 ].args;
  20994. var x0 = lastargs[ lastargs.length - 2 ];
  20995. var y0 = lastargs[ lastargs.length - 1 ];
  20996. var npts = [ new THREE.Vector2( x0, y0 ) ];
  20997. Array.prototype.push.apply( npts, pts );
  20998. var curve = new THREE.SplineCurve( npts );
  20999. this.curves.push( curve );
  21000. this.actions.push( { action: 'splineThru', args: args } );
  21001. };
  21002. // FUTURE: Change the API or follow canvas API?
  21003. THREE.Path.prototype.arc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21004. var lastargs = this.actions[ this.actions.length - 1 ].args;
  21005. var x0 = lastargs[ lastargs.length - 2 ];
  21006. var y0 = lastargs[ lastargs.length - 1 ];
  21007. this.absarc( aX + x0, aY + y0, aRadius,
  21008. aStartAngle, aEndAngle, aClockwise );
  21009. };
  21010. THREE.Path.prototype.absarc = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21011. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21012. };
  21013. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21014. var lastargs = this.actions[ this.actions.length - 1 ].args;
  21015. var x0 = lastargs[ lastargs.length - 2 ];
  21016. var y0 = lastargs[ lastargs.length - 1 ];
  21017. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21018. };
  21019. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21020. var args = [
  21021. aX, aY,
  21022. xRadius, yRadius,
  21023. aStartAngle, aEndAngle,
  21024. aClockwise,
  21025. aRotation || 0 // aRotation is optional.
  21026. ];
  21027. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  21028. this.curves.push( curve );
  21029. var lastPoint = curve.getPoint( 1 );
  21030. args.push( lastPoint.x );
  21031. args.push( lastPoint.y );
  21032. this.actions.push( { action: 'ellipse', args: args } );
  21033. };
  21034. THREE.Path.prototype.getSpacedPoints = function ( divisions ) {
  21035. if ( ! divisions ) divisions = 40;
  21036. var points = [];
  21037. for ( var i = 0; i < divisions; i ++ ) {
  21038. points.push( this.getPoint( i / divisions ) );
  21039. //if ( !this.getPoint( i / divisions ) ) throw "DIE";
  21040. }
  21041. if ( this.autoClose ) {
  21042. points.push( points[ 0 ] );
  21043. }
  21044. return points;
  21045. };
  21046. /* Return an array of vectors based on contour of the path */
  21047. THREE.Path.prototype.getPoints = function( divisions ) {
  21048. divisions = divisions || 12;
  21049. var b2 = THREE.ShapeUtils.b2;
  21050. var b3 = THREE.ShapeUtils.b3;
  21051. var points = [];
  21052. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  21053. laste, tx, ty;
  21054. for ( var i = 0, l = this.actions.length; i < l; i ++ ) {
  21055. var item = this.actions[ i ];
  21056. var action = item.action;
  21057. var args = item.args;
  21058. switch ( action ) {
  21059. case 'moveTo':
  21060. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  21061. break;
  21062. case 'lineTo':
  21063. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  21064. break;
  21065. case 'quadraticCurveTo':
  21066. cpx = args[ 2 ];
  21067. cpy = args[ 3 ];
  21068. cpx1 = args[ 0 ];
  21069. cpy1 = args[ 1 ];
  21070. if ( points.length > 0 ) {
  21071. laste = points[ points.length - 1 ];
  21072. cpx0 = laste.x;
  21073. cpy0 = laste.y;
  21074. } else {
  21075. laste = this.actions[ i - 1 ].args;
  21076. cpx0 = laste[ laste.length - 2 ];
  21077. cpy0 = laste[ laste.length - 1 ];
  21078. }
  21079. for ( var j = 1; j <= divisions; j ++ ) {
  21080. var t = j / divisions;
  21081. tx = b2( t, cpx0, cpx1, cpx );
  21082. ty = b2( t, cpy0, cpy1, cpy );
  21083. points.push( new THREE.Vector2( tx, ty ) );
  21084. }
  21085. break;
  21086. case 'bezierCurveTo':
  21087. cpx = args[ 4 ];
  21088. cpy = args[ 5 ];
  21089. cpx1 = args[ 0 ];
  21090. cpy1 = args[ 1 ];
  21091. cpx2 = args[ 2 ];
  21092. cpy2 = args[ 3 ];
  21093. if ( points.length > 0 ) {
  21094. laste = points[ points.length - 1 ];
  21095. cpx0 = laste.x;
  21096. cpy0 = laste.y;
  21097. } else {
  21098. laste = this.actions[ i - 1 ].args;
  21099. cpx0 = laste[ laste.length - 2 ];
  21100. cpy0 = laste[ laste.length - 1 ];
  21101. }
  21102. for ( var j = 1; j <= divisions; j ++ ) {
  21103. var t = j / divisions;
  21104. tx = b3( t, cpx0, cpx1, cpx2, cpx );
  21105. ty = b3( t, cpy0, cpy1, cpy2, cpy );
  21106. points.push( new THREE.Vector2( tx, ty ) );
  21107. }
  21108. break;
  21109. case 'splineThru':
  21110. laste = this.actions[ i - 1 ].args;
  21111. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  21112. var spts = [ last ];
  21113. var n = divisions * args[ 0 ].length;
  21114. spts = spts.concat( args[ 0 ] );
  21115. var spline = new THREE.SplineCurve( spts );
  21116. for ( var j = 1; j <= n; j ++ ) {
  21117. points.push( spline.getPointAt( j / n ) );
  21118. }
  21119. break;
  21120. case 'arc':
  21121. var aX = args[ 0 ], aY = args[ 1 ],
  21122. aRadius = args[ 2 ],
  21123. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  21124. aClockwise = !! args[ 5 ];
  21125. var deltaAngle = aEndAngle - aStartAngle;
  21126. var angle;
  21127. var tdivisions = divisions * 2;
  21128. for ( var j = 1; j <= tdivisions; j ++ ) {
  21129. var t = j / tdivisions;
  21130. if ( ! aClockwise ) {
  21131. t = 1 - t;
  21132. }
  21133. angle = aStartAngle + t * deltaAngle;
  21134. tx = aX + aRadius * Math.cos( angle );
  21135. ty = aY + aRadius * Math.sin( angle );
  21136. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  21137. points.push( new THREE.Vector2( tx, ty ) );
  21138. }
  21139. //console.log(points);
  21140. break;
  21141. case 'ellipse':
  21142. var aX = args[ 0 ], aY = args[ 1 ],
  21143. xRadius = args[ 2 ],
  21144. yRadius = args[ 3 ],
  21145. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  21146. aClockwise = !! args[ 6 ],
  21147. aRotation = args[ 7 ];
  21148. var deltaAngle = aEndAngle - aStartAngle;
  21149. var angle;
  21150. var tdivisions = divisions * 2;
  21151. var cos, sin;
  21152. if ( aRotation !== 0 ) {
  21153. cos = Math.cos( aRotation );
  21154. sin = Math.sin( aRotation );
  21155. }
  21156. for ( var j = 1; j <= tdivisions; j ++ ) {
  21157. var t = j / tdivisions;
  21158. if ( ! aClockwise ) {
  21159. t = 1 - t;
  21160. }
  21161. angle = aStartAngle + t * deltaAngle;
  21162. tx = aX + xRadius * Math.cos( angle );
  21163. ty = aY + yRadius * Math.sin( angle );
  21164. if ( aRotation !== 0 ) {
  21165. var x = tx, y = ty;
  21166. // Rotate the point about the center of the ellipse.
  21167. tx = ( x - aX ) * cos - ( y - aY ) * sin + aX;
  21168. ty = ( x - aX ) * sin + ( y - aY ) * cos + aY;
  21169. }
  21170. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  21171. points.push( new THREE.Vector2( tx, ty ) );
  21172. }
  21173. //console.log(points);
  21174. break;
  21175. } // end switch
  21176. }
  21177. // Normalize to remove the closing point by default.
  21178. var lastPoint = points[ points.length - 1 ];
  21179. if ( Math.abs( lastPoint.x - points[ 0 ].x ) < Number.EPSILON &&
  21180. Math.abs( lastPoint.y - points[ 0 ].y ) < Number.EPSILON )
  21181. points.splice( points.length - 1, 1 );
  21182. if ( this.autoClose ) {
  21183. points.push( points[ 0 ] );
  21184. }
  21185. return points;
  21186. };
  21187. //
  21188. // Breaks path into shapes
  21189. //
  21190. // Assumptions (if parameter isCCW==true the opposite holds):
  21191. // - solid shapes are defined clockwise (CW)
  21192. // - holes are defined counterclockwise (CCW)
  21193. //
  21194. // If parameter noHoles==true:
  21195. // - all subPaths are regarded as solid shapes
  21196. // - definition order CW/CCW has no relevance
  21197. //
  21198. THREE.Path.prototype.toShapes = function( isCCW, noHoles ) {
  21199. function extractSubpaths( inActions ) {
  21200. var subPaths = [], lastPath = new THREE.Path();
  21201. for ( var i = 0, l = inActions.length; i < l; i ++ ) {
  21202. var item = inActions[ i ];
  21203. var args = item.args;
  21204. var action = item.action;
  21205. if ( action === 'moveTo' ) {
  21206. if ( lastPath.actions.length !== 0 ) {
  21207. subPaths.push( lastPath );
  21208. lastPath = new THREE.Path();
  21209. }
  21210. }
  21211. lastPath[ action ].apply( lastPath, args );
  21212. }
  21213. if ( lastPath.actions.length !== 0 ) {
  21214. subPaths.push( lastPath );
  21215. }
  21216. // console.log(subPaths);
  21217. return subPaths;
  21218. }
  21219. function toShapesNoHoles( inSubpaths ) {
  21220. var shapes = [];
  21221. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  21222. var tmpPath = inSubpaths[ i ];
  21223. var tmpShape = new THREE.Shape();
  21224. tmpShape.actions = tmpPath.actions;
  21225. tmpShape.curves = tmpPath.curves;
  21226. shapes.push( tmpShape );
  21227. }
  21228. //console.log("shape", shapes);
  21229. return shapes;
  21230. }
  21231. function isPointInsidePolygon( inPt, inPolygon ) {
  21232. var polyLen = inPolygon.length;
  21233. // inPt on polygon contour => immediate success or
  21234. // toggling of inside/outside at every single! intersection point of an edge
  21235. // with the horizontal line through inPt, left of inPt
  21236. // not counting lowerY endpoints of edges and whole edges on that line
  21237. var inside = false;
  21238. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  21239. var edgeLowPt = inPolygon[ p ];
  21240. var edgeHighPt = inPolygon[ q ];
  21241. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  21242. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  21243. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  21244. // not parallel
  21245. if ( edgeDy < 0 ) {
  21246. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  21247. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  21248. }
  21249. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  21250. if ( inPt.y === edgeLowPt.y ) {
  21251. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  21252. // continue; // no intersection or edgeLowPt => doesn't count !!!
  21253. } else {
  21254. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  21255. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  21256. if ( perpEdge < 0 ) continue;
  21257. inside = ! inside; // true intersection left of inPt
  21258. }
  21259. } else {
  21260. // parallel or collinear
  21261. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  21262. // edge lies on the same horizontal line as inPt
  21263. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  21264. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  21265. // continue;
  21266. }
  21267. }
  21268. return inside;
  21269. }
  21270. var isClockWise = THREE.ShapeUtils.isClockWise;
  21271. var subPaths = extractSubpaths( this.actions );
  21272. if ( subPaths.length === 0 ) return [];
  21273. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  21274. var solid, tmpPath, tmpShape, shapes = [];
  21275. if ( subPaths.length === 1 ) {
  21276. tmpPath = subPaths[ 0 ];
  21277. tmpShape = new THREE.Shape();
  21278. tmpShape.actions = tmpPath.actions;
  21279. tmpShape.curves = tmpPath.curves;
  21280. shapes.push( tmpShape );
  21281. return shapes;
  21282. }
  21283. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  21284. holesFirst = isCCW ? ! holesFirst : holesFirst;
  21285. // console.log("Holes first", holesFirst);
  21286. var betterShapeHoles = [];
  21287. var newShapes = [];
  21288. var newShapeHoles = [];
  21289. var mainIdx = 0;
  21290. var tmpPoints;
  21291. newShapes[ mainIdx ] = undefined;
  21292. newShapeHoles[ mainIdx ] = [];
  21293. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  21294. tmpPath = subPaths[ i ];
  21295. tmpPoints = tmpPath.getPoints();
  21296. solid = isClockWise( tmpPoints );
  21297. solid = isCCW ? ! solid : solid;
  21298. if ( solid ) {
  21299. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  21300. newShapes[ mainIdx ] = { s: new THREE.Shape(), p: tmpPoints };
  21301. newShapes[ mainIdx ].s.actions = tmpPath.actions;
  21302. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  21303. if ( holesFirst ) mainIdx ++;
  21304. newShapeHoles[ mainIdx ] = [];
  21305. //console.log('cw', i);
  21306. } else {
  21307. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  21308. //console.log('ccw', i);
  21309. }
  21310. }
  21311. // only Holes? -> probably all Shapes with wrong orientation
  21312. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  21313. if ( newShapes.length > 1 ) {
  21314. var ambiguous = false;
  21315. var toChange = [];
  21316. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21317. betterShapeHoles[ sIdx ] = [];
  21318. }
  21319. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  21320. var sho = newShapeHoles[ sIdx ];
  21321. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  21322. var ho = sho[ hIdx ];
  21323. var hole_unassigned = true;
  21324. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  21325. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  21326. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  21327. if ( hole_unassigned ) {
  21328. hole_unassigned = false;
  21329. betterShapeHoles[ s2Idx ].push( ho );
  21330. } else {
  21331. ambiguous = true;
  21332. }
  21333. }
  21334. }
  21335. if ( hole_unassigned ) {
  21336. betterShapeHoles[ sIdx ].push( ho );
  21337. }
  21338. }
  21339. }
  21340. // console.log("ambiguous: ", ambiguous);
  21341. if ( toChange.length > 0 ) {
  21342. // console.log("to change: ", toChange);
  21343. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  21344. }
  21345. }
  21346. var tmpHoles;
  21347. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  21348. tmpShape = newShapes[ i ].s;
  21349. shapes.push( tmpShape );
  21350. tmpHoles = newShapeHoles[ i ];
  21351. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  21352. tmpShape.holes.push( tmpHoles[ j ].h );
  21353. }
  21354. }
  21355. //console.log("shape", shapes);
  21356. return shapes;
  21357. };
  21358. // File:src/extras/core/Shape.js
  21359. /**
  21360. * @author zz85 / http://www.lab4games.net/zz85/blog
  21361. * Defines a 2d shape plane using paths.
  21362. **/
  21363. // STEP 1 Create a path.
  21364. // STEP 2 Turn path into shape.
  21365. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  21366. // STEP 3a - Extract points from each shape, turn to vertices
  21367. // STEP 3b - Triangulate each shape, add faces.
  21368. THREE.Shape = function () {
  21369. THREE.Path.apply( this, arguments );
  21370. this.holes = [];
  21371. };
  21372. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  21373. THREE.Shape.prototype.constructor = THREE.Shape;
  21374. // Convenience method to return ExtrudeGeometry
  21375. THREE.Shape.prototype.extrude = function ( options ) {
  21376. return new THREE.ExtrudeGeometry( this, options );
  21377. };
  21378. // Convenience method to return ShapeGeometry
  21379. THREE.Shape.prototype.makeGeometry = function ( options ) {
  21380. return new THREE.ShapeGeometry( this, options );
  21381. };
  21382. // Get points of holes
  21383. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  21384. var holesPts = [];
  21385. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  21386. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  21387. }
  21388. return holesPts;
  21389. };
  21390. // Get points of shape and holes (keypoints based on segments parameter)
  21391. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  21392. return {
  21393. shape: this.getPoints( divisions ),
  21394. holes: this.getPointsHoles( divisions )
  21395. };
  21396. };
  21397. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  21398. return this.extractAllPoints( divisions );
  21399. };
  21400. // File:src/extras/curves/LineCurve.js
  21401. /**************************************************************
  21402. * Line
  21403. **************************************************************/
  21404. THREE.LineCurve = function ( v1, v2 ) {
  21405. this.v1 = v1;
  21406. this.v2 = v2;
  21407. };
  21408. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  21409. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  21410. THREE.LineCurve.prototype.getPoint = function ( t ) {
  21411. var point = this.v2.clone().sub( this.v1 );
  21412. point.multiplyScalar( t ).add( this.v1 );
  21413. return point;
  21414. };
  21415. // Line curve is linear, so we can overwrite default getPointAt
  21416. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  21417. return this.getPoint( u );
  21418. };
  21419. THREE.LineCurve.prototype.getTangent = function( t ) {
  21420. var tangent = this.v2.clone().sub( this.v1 );
  21421. return tangent.normalize();
  21422. };
  21423. // File:src/extras/curves/QuadraticBezierCurve.js
  21424. /**************************************************************
  21425. * Quadratic Bezier curve
  21426. **************************************************************/
  21427. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  21428. this.v0 = v0;
  21429. this.v1 = v1;
  21430. this.v2 = v2;
  21431. };
  21432. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  21433. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  21434. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  21435. var b2 = THREE.ShapeUtils.b2;
  21436. return new THREE.Vector2(
  21437. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  21438. b2( t, this.v0.y, this.v1.y, this.v2.y )
  21439. );
  21440. };
  21441. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  21442. var tangentQuadraticBezier = THREE.CurveUtils.tangentQuadraticBezier;
  21443. return new THREE.Vector2(
  21444. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  21445. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  21446. ).normalize();
  21447. };
  21448. // File:src/extras/curves/CubicBezierCurve.js
  21449. /**************************************************************
  21450. * Cubic Bezier curve
  21451. **************************************************************/
  21452. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  21453. this.v0 = v0;
  21454. this.v1 = v1;
  21455. this.v2 = v2;
  21456. this.v3 = v3;
  21457. };
  21458. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  21459. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  21460. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  21461. var b3 = THREE.ShapeUtils.b3;
  21462. return new THREE.Vector2(
  21463. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  21464. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  21465. );
  21466. };
  21467. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  21468. var tangentCubicBezier = THREE.CurveUtils.tangentCubicBezier;
  21469. return new THREE.Vector2(
  21470. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  21471. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  21472. ).normalize();
  21473. };
  21474. // File:src/extras/curves/SplineCurve.js
  21475. /**************************************************************
  21476. * Spline curve
  21477. **************************************************************/
  21478. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  21479. this.points = ( points == undefined ) ? [] : points;
  21480. };
  21481. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  21482. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  21483. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  21484. var points = this.points;
  21485. var point = ( points.length - 1 ) * t;
  21486. var intPoint = Math.floor( point );
  21487. var weight = point - intPoint;
  21488. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  21489. var point1 = points[ intPoint ];
  21490. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21491. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21492. var interpolate = THREE.CurveUtils.interpolate;
  21493. return new THREE.Vector2(
  21494. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  21495. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  21496. );
  21497. };
  21498. // File:src/extras/curves/EllipseCurve.js
  21499. /**************************************************************
  21500. * Ellipse curve
  21501. **************************************************************/
  21502. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  21503. this.aX = aX;
  21504. this.aY = aY;
  21505. this.xRadius = xRadius;
  21506. this.yRadius = yRadius;
  21507. this.aStartAngle = aStartAngle;
  21508. this.aEndAngle = aEndAngle;
  21509. this.aClockwise = aClockwise;
  21510. this.aRotation = aRotation || 0;
  21511. };
  21512. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  21513. THREE.EllipseCurve.prototype.constructor = THREE.EllipseCurve;
  21514. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  21515. var deltaAngle = this.aEndAngle - this.aStartAngle;
  21516. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  21517. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  21518. var angle;
  21519. if ( this.aClockwise === true ) {
  21520. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  21521. } else {
  21522. angle = this.aStartAngle + t * deltaAngle;
  21523. }
  21524. var x = this.aX + this.xRadius * Math.cos( angle );
  21525. var y = this.aY + this.yRadius * Math.sin( angle );
  21526. if ( this.aRotation !== 0 ) {
  21527. var cos = Math.cos( this.aRotation );
  21528. var sin = Math.sin( this.aRotation );
  21529. var tx = x, ty = y;
  21530. // Rotate the point about the center of the ellipse.
  21531. x = ( tx - this.aX ) * cos - ( ty - this.aY ) * sin + this.aX;
  21532. y = ( tx - this.aX ) * sin + ( ty - this.aY ) * cos + this.aY;
  21533. }
  21534. return new THREE.Vector2( x, y );
  21535. };
  21536. // File:src/extras/curves/ArcCurve.js
  21537. /**************************************************************
  21538. * Arc curve
  21539. **************************************************************/
  21540. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  21541. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  21542. };
  21543. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  21544. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  21545. // File:src/extras/curves/LineCurve3.js
  21546. /**************************************************************
  21547. * Line3D
  21548. **************************************************************/
  21549. THREE.LineCurve3 = THREE.Curve.create(
  21550. function ( v1, v2 ) {
  21551. this.v1 = v1;
  21552. this.v2 = v2;
  21553. },
  21554. function ( t ) {
  21555. var vector = new THREE.Vector3();
  21556. vector.subVectors( this.v2, this.v1 ); // diff
  21557. vector.multiplyScalar( t );
  21558. vector.add( this.v1 );
  21559. return vector;
  21560. }
  21561. );
  21562. // File:src/extras/curves/QuadraticBezierCurve3.js
  21563. /**************************************************************
  21564. * Quadratic Bezier 3D curve
  21565. **************************************************************/
  21566. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  21567. function ( v0, v1, v2 ) {
  21568. this.v0 = v0;
  21569. this.v1 = v1;
  21570. this.v2 = v2;
  21571. },
  21572. function ( t ) {
  21573. var b2 = THREE.ShapeUtils.b2;
  21574. return new THREE.Vector3(
  21575. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  21576. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  21577. b2( t, this.v0.z, this.v1.z, this.v2.z )
  21578. );
  21579. }
  21580. );
  21581. // File:src/extras/curves/CubicBezierCurve3.js
  21582. /**************************************************************
  21583. * Cubic Bezier 3D curve
  21584. **************************************************************/
  21585. THREE.CubicBezierCurve3 = THREE.Curve.create(
  21586. function ( v0, v1, v2, v3 ) {
  21587. this.v0 = v0;
  21588. this.v1 = v1;
  21589. this.v2 = v2;
  21590. this.v3 = v3;
  21591. },
  21592. function ( t ) {
  21593. var b3 = THREE.ShapeUtils.b3;
  21594. return new THREE.Vector3(
  21595. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  21596. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  21597. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  21598. );
  21599. }
  21600. );
  21601. // File:src/extras/curves/SplineCurve3.js
  21602. /**************************************************************
  21603. * Spline 3D curve
  21604. **************************************************************/
  21605. THREE.SplineCurve3 = THREE.Curve.create(
  21606. function ( points /* array of Vector3 */ ) {
  21607. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  21608. this.points = ( points == undefined ) ? [] : points;
  21609. },
  21610. function ( t ) {
  21611. var points = this.points;
  21612. var point = ( points.length - 1 ) * t;
  21613. var intPoint = Math.floor( point );
  21614. var weight = point - intPoint;
  21615. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  21616. var point1 = points[ intPoint ];
  21617. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  21618. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  21619. var interpolate = THREE.CurveUtils.interpolate;
  21620. return new THREE.Vector3(
  21621. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  21622. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  21623. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  21624. );
  21625. }
  21626. );
  21627. // File:src/extras/curves/CatmullRomCurve3.js
  21628. /**
  21629. * @author zz85 https://github.com/zz85
  21630. *
  21631. * Centripetal CatmullRom Curve - which is useful for avoiding
  21632. * cusps and self-intersections in non-uniform catmull rom curves.
  21633. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  21634. *
  21635. * curve.type accepts centripetal(default), chordal and catmullrom
  21636. * curve.tension is used for catmullrom which defaults to 0.5
  21637. */
  21638. THREE.CatmullRomCurve3 = ( function() {
  21639. var
  21640. tmp = new THREE.Vector3(),
  21641. px = new CubicPoly(),
  21642. py = new CubicPoly(),
  21643. pz = new CubicPoly();
  21644. /*
  21645. Based on an optimized c++ solution in
  21646. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  21647. - http://ideone.com/NoEbVM
  21648. This CubicPoly class could be used for reusing some variables and calculations,
  21649. but for three.js curve use, it could be possible inlined and flatten into a single function call
  21650. which can be placed in CurveUtils.
  21651. */
  21652. function CubicPoly() {
  21653. }
  21654. /*
  21655. * Compute coefficients for a cubic polynomial
  21656. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  21657. * such that
  21658. * p(0) = x0, p(1) = x1
  21659. * and
  21660. * p'(0) = t0, p'(1) = t1.
  21661. */
  21662. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  21663. this.c0 = x0;
  21664. this.c1 = t0;
  21665. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  21666. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  21667. };
  21668. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  21669. // compute tangents when parameterized in [t1,t2]
  21670. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  21671. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  21672. // rescale tangents for parametrization in [0,1]
  21673. t1 *= dt1;
  21674. t2 *= dt1;
  21675. // initCubicPoly
  21676. this.init( x1, x2, t1, t2 );
  21677. };
  21678. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  21679. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  21680. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  21681. };
  21682. CubicPoly.prototype.calc = function( t ) {
  21683. var t2 = t * t;
  21684. var t3 = t2 * t;
  21685. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  21686. };
  21687. // Subclass Three.js curve
  21688. return THREE.Curve.create(
  21689. function ( p /* array of Vector3 */ ) {
  21690. this.points = p || [];
  21691. this.closed = false;
  21692. },
  21693. function ( t ) {
  21694. var points = this.points,
  21695. point, intPoint, weight, l;
  21696. l = points.length;
  21697. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  21698. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  21699. intPoint = Math.floor( point );
  21700. weight = point - intPoint;
  21701. if ( this.closed ) {
  21702. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  21703. } else if ( weight === 0 && intPoint === l - 1 ) {
  21704. intPoint = l - 2;
  21705. weight = 1;
  21706. }
  21707. var p0, p1, p2, p3; // 4 points
  21708. if ( this.closed || intPoint > 0 ) {
  21709. p0 = points[ ( intPoint - 1 ) % l ];
  21710. } else {
  21711. // extrapolate first point
  21712. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  21713. p0 = tmp;
  21714. }
  21715. p1 = points[ intPoint % l ];
  21716. p2 = points[ ( intPoint + 1 ) % l ];
  21717. if ( this.closed || intPoint + 2 < l ) {
  21718. p3 = points[ ( intPoint + 2 ) % l ];
  21719. } else {
  21720. // extrapolate last point
  21721. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  21722. p3 = tmp;
  21723. }
  21724. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  21725. // init Centripetal / Chordal Catmull-Rom
  21726. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  21727. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  21728. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  21729. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  21730. // safety check for repeated points
  21731. if ( dt1 < 1e-4 ) dt1 = 1.0;
  21732. if ( dt0 < 1e-4 ) dt0 = dt1;
  21733. if ( dt2 < 1e-4 ) dt2 = dt1;
  21734. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  21735. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  21736. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  21737. } else if ( this.type === 'catmullrom' ) {
  21738. var tension = this.tension !== undefined ? this.tension : 0.5;
  21739. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  21740. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  21741. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  21742. }
  21743. var v = new THREE.Vector3(
  21744. px.calc( weight ),
  21745. py.calc( weight ),
  21746. pz.calc( weight )
  21747. );
  21748. return v;
  21749. }
  21750. );
  21751. } )();
  21752. // File:src/extras/curves/ClosedSplineCurve3.js
  21753. /**************************************************************
  21754. * Closed Spline 3D curve
  21755. **************************************************************/
  21756. THREE.ClosedSplineCurve3 = function ( points ) {
  21757. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Please use THREE.CatmullRomCurve3.' );
  21758. THREE.CatmullRomCurve3.call( this, points );
  21759. this.type = 'catmullrom';
  21760. this.closed = true;
  21761. };
  21762. THREE.ClosedSplineCurve3.prototype = Object.create( THREE.CatmullRomCurve3.prototype );
  21763. // File:src/extras/geometries/BoxGeometry.js
  21764. /**
  21765. * @author mrdoob / http://mrdoob.com/
  21766. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  21767. */
  21768. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  21769. THREE.Geometry.call( this );
  21770. this.type = 'BoxGeometry';
  21771. this.parameters = {
  21772. width: width,
  21773. height: height,
  21774. depth: depth,
  21775. widthSegments: widthSegments,
  21776. heightSegments: heightSegments,
  21777. depthSegments: depthSegments
  21778. };
  21779. this.fromBufferGeometry( new THREE.BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  21780. this.mergeVertices();
  21781. };
  21782. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21783. THREE.BoxGeometry.prototype.constructor = THREE.BoxGeometry;
  21784. THREE.CubeGeometry = THREE.BoxGeometry;
  21785. // File:src/extras/geometries/BoxBufferGeometry.js
  21786. /**
  21787. * @author Mugen87 / https://github.com/Mugen87
  21788. */
  21789. THREE.BoxBufferGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  21790. THREE.BufferGeometry.call( this );
  21791. this.type = 'BoxBufferGeometry';
  21792. this.parameters = {
  21793. width: width,
  21794. height: height,
  21795. depth: depth,
  21796. widthSegments: widthSegments,
  21797. heightSegments: heightSegments,
  21798. depthSegments: depthSegments
  21799. };
  21800. var scope = this;
  21801. // segments
  21802. widthSegments = Math.floor( widthSegments ) || 1;
  21803. heightSegments = Math.floor( heightSegments ) || 1;
  21804. depthSegments = Math.floor( depthSegments ) || 1;
  21805. // these are used to calculate buffer length
  21806. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  21807. var indexCount = ( vertexCount / 4 ) * 6;
  21808. // buffers
  21809. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  21810. var vertices = new Float32Array( vertexCount * 3 );
  21811. var normals = new Float32Array( vertexCount * 3 );
  21812. var uvs = new Float32Array( vertexCount * 2 );
  21813. // offset variables
  21814. var vertexBufferOffset = 0;
  21815. var uvBufferOffset = 0;
  21816. var indexBufferOffset = 0;
  21817. var numberOfVertices = 0;
  21818. // group variables
  21819. var groupStart = 0;
  21820. // build each side of the box geometry
  21821. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  21822. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  21823. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  21824. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  21825. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  21826. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  21827. // build geometry
  21828. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  21829. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  21830. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21831. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21832. // helper functions
  21833. function calculateVertexCount ( w, h, d ) {
  21834. var segments = 0;
  21835. // calculate the amount of segments for each side
  21836. segments += w * h * 2; // xy
  21837. segments += w * d * 2; // xz
  21838. segments += d * h * 2; // zy
  21839. return segments * 4; // four vertices per segments
  21840. }
  21841. function buildPlane ( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  21842. var segmentWidth = width / gridX;
  21843. var segmentHeight = height / gridY;
  21844. var widthHalf = width / 2;
  21845. var heightHalf = height / 2;
  21846. var depthHalf = depth / 2;
  21847. var gridX1 = gridX + 1;
  21848. var gridY1 = gridY + 1;
  21849. var vertexCounter = 0;
  21850. var groupCount = 0;
  21851. var vector = new THREE.Vector3();
  21852. // generate vertices, normals and uvs
  21853. for ( var iy = 0; iy < gridY1; iy ++ ) {
  21854. var y = iy * segmentHeight - heightHalf;
  21855. for ( var ix = 0; ix < gridX1; ix ++ ) {
  21856. var x = ix * segmentWidth - widthHalf;
  21857. // set values to correct vector component
  21858. vector[ u ] = x * udir;
  21859. vector[ v ] = y * vdir;
  21860. vector[ w ] = depthHalf;
  21861. // now apply vector to vertex buffer
  21862. vertices[ vertexBufferOffset ] = vector.x;
  21863. vertices[ vertexBufferOffset + 1 ] = vector.y;
  21864. vertices[ vertexBufferOffset + 2 ] = vector.z;
  21865. // set values to correct vector component
  21866. vector[ u ] = 0;
  21867. vector[ v ] = 0;
  21868. vector[ w ] = depth > 0 ? 1 : - 1;
  21869. // now apply vector to normal buffer
  21870. normals[ vertexBufferOffset ] = vector.x;
  21871. normals[ vertexBufferOffset + 1 ] = vector.y;
  21872. normals[ vertexBufferOffset + 2 ] = vector.z;
  21873. // uvs
  21874. uvs[ uvBufferOffset ] = ix / gridX;
  21875. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  21876. // update offsets and counters
  21877. vertexBufferOffset += 3;
  21878. uvBufferOffset += 2;
  21879. vertexCounter += 1;
  21880. }
  21881. }
  21882. // 1. you need three indices to draw a single face
  21883. // 2. a single segment consists of two faces
  21884. // 3. so we need to generate six (2*3) indices per segment
  21885. for ( iy = 0; iy < gridY; iy ++ ) {
  21886. for ( ix = 0; ix < gridX; ix ++ ) {
  21887. // indices
  21888. var a = numberOfVertices + ix + gridX1 * iy;
  21889. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  21890. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  21891. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  21892. // face one
  21893. indices[ indexBufferOffset ] = a;
  21894. indices[ indexBufferOffset + 1 ] = b;
  21895. indices[ indexBufferOffset + 2 ] = d;
  21896. // face two
  21897. indices[ indexBufferOffset + 3 ] = b;
  21898. indices[ indexBufferOffset + 4 ] = c;
  21899. indices[ indexBufferOffset + 5 ] = d;
  21900. // update offsets and counters
  21901. indexBufferOffset += 6;
  21902. groupCount += 6;
  21903. }
  21904. }
  21905. // add a group to the geometry. this will ensure multi material support
  21906. scope.addGroup( groupStart, groupCount, materialIndex );
  21907. // calculate new start value for groups
  21908. groupStart += groupCount;
  21909. // update total number of vertices
  21910. numberOfVertices += vertexCounter;
  21911. }
  21912. };
  21913. THREE.BoxBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21914. THREE.BoxBufferGeometry.prototype.constructor = THREE.BoxBufferGeometry;
  21915. // File:src/extras/geometries/CircleGeometry.js
  21916. /**
  21917. * @author hughes
  21918. */
  21919. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21920. THREE.Geometry.call( this );
  21921. this.type = 'CircleGeometry';
  21922. this.parameters = {
  21923. radius: radius,
  21924. segments: segments,
  21925. thetaStart: thetaStart,
  21926. thetaLength: thetaLength
  21927. };
  21928. this.fromBufferGeometry( new THREE.CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  21929. };
  21930. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21931. THREE.CircleGeometry.prototype.constructor = THREE.CircleGeometry;
  21932. // File:src/extras/geometries/CircleBufferGeometry.js
  21933. /**
  21934. * @author benaadams / https://twitter.com/ben_a_adams
  21935. */
  21936. THREE.CircleBufferGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  21937. THREE.BufferGeometry.call( this );
  21938. this.type = 'CircleBufferGeometry';
  21939. this.parameters = {
  21940. radius: radius,
  21941. segments: segments,
  21942. thetaStart: thetaStart,
  21943. thetaLength: thetaLength
  21944. };
  21945. radius = radius || 50;
  21946. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  21947. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21948. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21949. var vertices = segments + 2;
  21950. var positions = new Float32Array( vertices * 3 );
  21951. var normals = new Float32Array( vertices * 3 );
  21952. var uvs = new Float32Array( vertices * 2 );
  21953. // center data is already zero, but need to set a few extras
  21954. normals[ 2 ] = 1.0;
  21955. uvs[ 0 ] = 0.5;
  21956. uvs[ 1 ] = 0.5;
  21957. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  21958. var segment = thetaStart + s / segments * thetaLength;
  21959. positions[ i ] = radius * Math.cos( segment );
  21960. positions[ i + 1 ] = radius * Math.sin( segment );
  21961. normals[ i + 2 ] = 1; // normal z
  21962. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  21963. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  21964. }
  21965. var indices = [];
  21966. for ( var i = 1; i <= segments; i ++ ) {
  21967. indices.push( i, i + 1, 0 );
  21968. }
  21969. this.setIndex( new THREE.BufferAttribute( new Uint16Array( indices ), 1 ) );
  21970. this.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  21971. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  21972. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  21973. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  21974. };
  21975. THREE.CircleBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  21976. THREE.CircleBufferGeometry.prototype.constructor = THREE.CircleBufferGeometry;
  21977. // File:src/extras/geometries/CylinderBufferGeometry.js
  21978. /**
  21979. * @author Mugen87 / https://github.com/Mugen87
  21980. */
  21981. THREE.CylinderBufferGeometry = function( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21982. THREE.BufferGeometry.call( this );
  21983. this.type = 'CylinderBufferGeometry';
  21984. this.parameters = {
  21985. radiusTop: radiusTop,
  21986. radiusBottom: radiusBottom,
  21987. height: height,
  21988. radialSegments: radialSegments,
  21989. heightSegments: heightSegments,
  21990. openEnded: openEnded,
  21991. thetaStart: thetaStart,
  21992. thetaLength: thetaLength
  21993. };
  21994. var scope = this;
  21995. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  21996. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  21997. height = height !== undefined ? height : 100;
  21998. radialSegments = Math.floor( radialSegments ) || 8;
  21999. heightSegments = Math.floor( heightSegments ) || 1;
  22000. openEnded = openEnded !== undefined ? openEnded : false;
  22001. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22002. thetaLength = thetaLength !== undefined ? thetaLength : 2 * Math.PI;
  22003. // used to calculate buffer length
  22004. var vertexCount = calculateVertexCount();
  22005. var indexCount = calculateIndexCount();
  22006. // buffers
  22007. var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  22008. var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22009. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22010. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22011. // helper variables
  22012. var index = 0, indexOffset = 0, indexArray = [], halfHeight = height / 2;
  22013. // group variables
  22014. var groupStart = 0;
  22015. // generate geometry
  22016. generateTorso();
  22017. if ( openEnded === false ) {
  22018. if ( radiusTop > 0 ) generateCap( true );
  22019. if ( radiusBottom > 0 ) generateCap( false );
  22020. }
  22021. // build geometry
  22022. this.setIndex( indices );
  22023. this.addAttribute( 'position', vertices );
  22024. this.addAttribute( 'normal', normals );
  22025. this.addAttribute( 'uv', uvs );
  22026. // helper functions
  22027. function calculateVertexCount() {
  22028. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  22029. if ( openEnded === false ) {
  22030. count += ( ( radialSegments + 1 ) * 2 ) + ( radialSegments * 2 );
  22031. }
  22032. return count;
  22033. }
  22034. function calculateIndexCount() {
  22035. var count = radialSegments * heightSegments * 2 * 3;
  22036. if ( openEnded === false ) {
  22037. count += radialSegments * 2 * 3;
  22038. }
  22039. return count;
  22040. }
  22041. function generateTorso() {
  22042. var x, y;
  22043. var normal = new THREE.Vector3();
  22044. var vertex = new THREE.Vector3();
  22045. var groupCount = 0;
  22046. // this will be used to calculate the normal
  22047. var tanTheta = ( radiusBottom - radiusTop ) / height;
  22048. // generate vertices, normals and uvs
  22049. for ( y = 0; y <= heightSegments; y ++ ) {
  22050. var indexRow = [];
  22051. var v = y / heightSegments;
  22052. // calculate the radius of the current row
  22053. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22054. for ( x = 0; x <= radialSegments; x ++ ) {
  22055. var u = x / radialSegments;
  22056. // vertex
  22057. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  22058. vertex.y = - v * height + halfHeight;
  22059. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  22060. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22061. // normal
  22062. normal.copy( vertex );
  22063. // handle special case if radiusTop/radiusBottom is zero
  22064. if ( ( radiusTop === 0 && y === 0 ) || ( radiusBottom === 0 && y === heightSegments ) ) {
  22065. normal.x = Math.sin( u * thetaLength + thetaStart );
  22066. normal.z = Math.cos( u * thetaLength + thetaStart );
  22067. }
  22068. normal.setY( Math.sqrt( normal.x * normal.x + normal.z * normal.z ) * tanTheta ).normalize();
  22069. normals.setXYZ( index, normal.x, normal.y, normal.z );
  22070. // uv
  22071. uvs.setXY( index, u, 1 - v );
  22072. // save index of vertex in respective row
  22073. indexRow.push( index );
  22074. // increase index
  22075. index ++;
  22076. }
  22077. // now save vertices of the row in our index array
  22078. indexArray.push( indexRow );
  22079. }
  22080. // generate indices
  22081. for ( x = 0; x < radialSegments; x ++ ) {
  22082. for ( y = 0; y < heightSegments; y ++ ) {
  22083. // we use the index array to access the correct indices
  22084. var i1 = indexArray[ y ][ x ];
  22085. var i2 = indexArray[ y + 1 ][ x ];
  22086. var i3 = indexArray[ y + 1 ][ x + 1 ];
  22087. var i4 = indexArray[ y ][ x + 1 ];
  22088. // face one
  22089. indices.setX( indexOffset, i1 ); indexOffset ++;
  22090. indices.setX( indexOffset, i2 ); indexOffset ++;
  22091. indices.setX( indexOffset, i4 ); indexOffset ++;
  22092. // face two
  22093. indices.setX( indexOffset, i2 ); indexOffset ++;
  22094. indices.setX( indexOffset, i3 ); indexOffset ++;
  22095. indices.setX( indexOffset, i4 ); indexOffset ++;
  22096. // update counters
  22097. groupCount += 6;
  22098. }
  22099. }
  22100. // add a group to the geometry. this will ensure multi material support
  22101. scope.addGroup( groupStart, groupCount, 0 );
  22102. // calculate new start value for groups
  22103. groupStart += groupCount;
  22104. }
  22105. function generateCap( top ) {
  22106. var x, centerIndexStart, centerIndexEnd;
  22107. var uv = new THREE.Vector2();
  22108. var vertex = new THREE.Vector3();
  22109. var groupCount = 0;
  22110. var radius = ( top === true ) ? radiusTop : radiusBottom;
  22111. var sign = ( top === true ) ? 1 : - 1;
  22112. // save the index of the first center vertex
  22113. centerIndexStart = index;
  22114. // first we generate the center vertex data of the cap.
  22115. // because the geometry needs one set of uvs per face,
  22116. // we must generate a center vertex per face/segment
  22117. for ( x = 1; x <= radialSegments; x ++ ) {
  22118. // vertex
  22119. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  22120. // normal
  22121. normals.setXYZ( index, 0, sign, 0 );
  22122. // uv
  22123. if ( top === true ) {
  22124. uv.x = x / radialSegments;
  22125. uv.y = 0;
  22126. } else {
  22127. uv.x = ( x - 1 ) / radialSegments;
  22128. uv.y = 1;
  22129. }
  22130. uvs.setXY( index, uv.x, uv.y );
  22131. // increase index
  22132. index ++;
  22133. }
  22134. // save the index of the last center vertex
  22135. centerIndexEnd = index;
  22136. // now we generate the surrounding vertices, normals and uvs
  22137. for ( x = 0; x <= radialSegments; x ++ ) {
  22138. var u = x / radialSegments;
  22139. // vertex
  22140. vertex.x = radius * Math.sin( u * thetaLength + thetaStart );
  22141. vertex.y = halfHeight * sign;
  22142. vertex.z = radius * Math.cos( u * thetaLength + thetaStart );
  22143. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22144. // normal
  22145. normals.setXYZ( index, 0, sign, 0 );
  22146. // uv
  22147. uvs.setXY( index, u, ( top === true ) ? 1 : 0 );
  22148. // increase index
  22149. index ++;
  22150. }
  22151. // generate indices
  22152. for ( x = 0; x < radialSegments; x ++ ) {
  22153. var c = centerIndexStart + x;
  22154. var i = centerIndexEnd + x;
  22155. if ( top === true ) {
  22156. // face top
  22157. indices.setX( indexOffset, i ); indexOffset ++;
  22158. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  22159. indices.setX( indexOffset, c ); indexOffset ++;
  22160. } else {
  22161. // face bottom
  22162. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  22163. indices.setX( indexOffset, i ); indexOffset ++;
  22164. indices.setX( indexOffset, c ); indexOffset ++;
  22165. }
  22166. // update counters
  22167. groupCount += 3;
  22168. }
  22169. // add a group to the geometry. this will ensure multi material support
  22170. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22171. // calculate new start value for groups
  22172. groupStart += groupCount;
  22173. }
  22174. };
  22175. THREE.CylinderBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22176. THREE.CylinderBufferGeometry.prototype.constructor = THREE.CylinderBufferGeometry;
  22177. // File:src/extras/geometries/CylinderGeometry.js
  22178. /**
  22179. * @author mrdoob / http://mrdoob.com/
  22180. */
  22181. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  22182. THREE.Geometry.call( this );
  22183. this.type = 'CylinderGeometry';
  22184. this.parameters = {
  22185. radiusTop: radiusTop,
  22186. radiusBottom: radiusBottom,
  22187. height: height,
  22188. radialSegments: radialSegments,
  22189. heightSegments: heightSegments,
  22190. openEnded: openEnded,
  22191. thetaStart: thetaStart,
  22192. thetaLength: thetaLength
  22193. };
  22194. this.fromBufferGeometry( new THREE.CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  22195. this.mergeVertices();
  22196. };
  22197. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22198. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  22199. // File:src/extras/geometries/EdgesGeometry.js
  22200. /**
  22201. * @author WestLangley / http://github.com/WestLangley
  22202. */
  22203. THREE.EdgesGeometry = function ( geometry, thresholdAngle ) {
  22204. THREE.BufferGeometry.call( this );
  22205. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  22206. var thresholdDot = Math.cos( THREE.Math.DEG2RAD * thresholdAngle );
  22207. var edge = [ 0, 0 ], hash = {};
  22208. function sortFunction( a, b ) {
  22209. return a - b;
  22210. }
  22211. var keys = [ 'a', 'b', 'c' ];
  22212. var geometry2;
  22213. if ( geometry instanceof THREE.BufferGeometry ) {
  22214. geometry2 = new THREE.Geometry();
  22215. geometry2.fromBufferGeometry( geometry );
  22216. } else {
  22217. geometry2 = geometry.clone();
  22218. }
  22219. geometry2.mergeVertices();
  22220. geometry2.computeFaceNormals();
  22221. var vertices = geometry2.vertices;
  22222. var faces = geometry2.faces;
  22223. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  22224. var face = faces[ i ];
  22225. for ( var j = 0; j < 3; j ++ ) {
  22226. edge[ 0 ] = face[ keys[ j ] ];
  22227. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  22228. edge.sort( sortFunction );
  22229. var key = edge.toString();
  22230. if ( hash[ key ] === undefined ) {
  22231. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  22232. } else {
  22233. hash[ key ].face2 = i;
  22234. }
  22235. }
  22236. }
  22237. var coords = [];
  22238. for ( var key in hash ) {
  22239. var h = hash[ key ];
  22240. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  22241. var vertex = vertices[ h.vert1 ];
  22242. coords.push( vertex.x );
  22243. coords.push( vertex.y );
  22244. coords.push( vertex.z );
  22245. vertex = vertices[ h.vert2 ];
  22246. coords.push( vertex.x );
  22247. coords.push( vertex.y );
  22248. coords.push( vertex.z );
  22249. }
  22250. }
  22251. this.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( coords ), 3 ) );
  22252. };
  22253. THREE.EdgesGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22254. THREE.EdgesGeometry.prototype.constructor = THREE.EdgesGeometry;
  22255. // File:src/extras/geometries/ExtrudeGeometry.js
  22256. /**
  22257. * @author zz85 / http://www.lab4games.net/zz85/blog
  22258. *
  22259. * Creates extruded geometry from a path shape.
  22260. *
  22261. * parameters = {
  22262. *
  22263. * curveSegments: <int>, // number of points on the curves
  22264. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  22265. * amount: <int>, // Depth to extrude the shape
  22266. *
  22267. * bevelEnabled: <bool>, // turn on bevel
  22268. * bevelThickness: <float>, // how deep into the original shape bevel goes
  22269. * bevelSize: <float>, // how far from shape outline is bevel
  22270. * bevelSegments: <int>, // number of bevel layers
  22271. *
  22272. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  22273. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  22274. *
  22275. * uvGenerator: <Object> // object that provides UV generator functions
  22276. *
  22277. * }
  22278. **/
  22279. THREE.ExtrudeGeometry = function ( shapes, options ) {
  22280. if ( typeof( shapes ) === "undefined" ) {
  22281. shapes = [];
  22282. return;
  22283. }
  22284. THREE.Geometry.call( this );
  22285. this.type = 'ExtrudeGeometry';
  22286. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  22287. this.addShapeList( shapes, options );
  22288. this.computeFaceNormals();
  22289. // can't really use automatic vertex normals
  22290. // as then front and back sides get smoothed too
  22291. // should do separate smoothing just for sides
  22292. //this.computeVertexNormals();
  22293. //console.log( "took", ( Date.now() - startTime ) );
  22294. };
  22295. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22296. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  22297. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  22298. var sl = shapes.length;
  22299. for ( var s = 0; s < sl; s ++ ) {
  22300. var shape = shapes[ s ];
  22301. this.addShape( shape, options );
  22302. }
  22303. };
  22304. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  22305. var amount = options.amount !== undefined ? options.amount : 100;
  22306. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  22307. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  22308. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  22309. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  22310. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  22311. var steps = options.steps !== undefined ? options.steps : 1;
  22312. var extrudePath = options.extrudePath;
  22313. var extrudePts, extrudeByPath = false;
  22314. // Use default WorldUVGenerator if no UV generators are specified.
  22315. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  22316. var splineTube, binormal, normal, position2;
  22317. if ( extrudePath ) {
  22318. extrudePts = extrudePath.getSpacedPoints( steps );
  22319. extrudeByPath = true;
  22320. bevelEnabled = false; // bevels not supported for path extrusion
  22321. // SETUP TNB variables
  22322. // Reuse TNB from TubeGeomtry for now.
  22323. // TODO1 - have a .isClosed in spline?
  22324. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames( extrudePath, steps, false );
  22325. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  22326. binormal = new THREE.Vector3();
  22327. normal = new THREE.Vector3();
  22328. position2 = new THREE.Vector3();
  22329. }
  22330. // Safeguards if bevels are not enabled
  22331. if ( ! bevelEnabled ) {
  22332. bevelSegments = 0;
  22333. bevelThickness = 0;
  22334. bevelSize = 0;
  22335. }
  22336. // Variables initialization
  22337. var ahole, h, hl; // looping of holes
  22338. var scope = this;
  22339. var shapesOffset = this.vertices.length;
  22340. var shapePoints = shape.extractPoints( curveSegments );
  22341. var vertices = shapePoints.shape;
  22342. var holes = shapePoints.holes;
  22343. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  22344. if ( reverse ) {
  22345. vertices = vertices.reverse();
  22346. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  22347. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22348. ahole = holes[ h ];
  22349. if ( THREE.ShapeUtils.isClockWise( ahole ) ) {
  22350. holes[ h ] = ahole.reverse();
  22351. }
  22352. }
  22353. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  22354. }
  22355. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  22356. /* Vertices */
  22357. var contour = vertices; // vertices has all points but contour has only points of circumference
  22358. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22359. ahole = holes[ h ];
  22360. vertices = vertices.concat( ahole );
  22361. }
  22362. function scalePt2 ( pt, vec, size ) {
  22363. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  22364. return vec.clone().multiplyScalar( size ).add( pt );
  22365. }
  22366. var b, bs, t, z,
  22367. vert, vlen = vertices.length,
  22368. face, flen = faces.length;
  22369. // Find directions for point movement
  22370. function getBevelVec( inPt, inPrev, inNext ) {
  22371. // computes for inPt the corresponding point inPt' on a new contour
  22372. // shifted by 1 unit (length of normalized vector) to the left
  22373. // if we walk along contour clockwise, this new contour is outside the old one
  22374. //
  22375. // inPt' is the intersection of the two lines parallel to the two
  22376. // adjacent edges of inPt at a distance of 1 unit on the left side.
  22377. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  22378. // good reading for geometry algorithms (here: line-line intersection)
  22379. // http://geomalgorithms.com/a05-_intersect-1.html
  22380. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  22381. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  22382. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  22383. // check for collinear edges
  22384. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22385. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  22386. // not collinear
  22387. // length of vectors for normalizing
  22388. var v_prev_len = Math.sqrt( v_prev_lensq );
  22389. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  22390. // shift adjacent points by unit vectors to the left
  22391. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  22392. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  22393. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  22394. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  22395. // scaling factor for v_prev to intersection point
  22396. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  22397. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  22398. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  22399. // vector from inPt to intersection point
  22400. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  22401. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  22402. // Don't normalize!, otherwise sharp corners become ugly
  22403. // but prevent crazy spikes
  22404. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  22405. if ( v_trans_lensq <= 2 ) {
  22406. return new THREE.Vector2( v_trans_x, v_trans_y );
  22407. } else {
  22408. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  22409. }
  22410. } else {
  22411. // handle special case of collinear edges
  22412. var direction_eq = false; // assumes: opposite
  22413. if ( v_prev_x > Number.EPSILON ) {
  22414. if ( v_next_x > Number.EPSILON ) {
  22415. direction_eq = true;
  22416. }
  22417. } else {
  22418. if ( v_prev_x < - Number.EPSILON ) {
  22419. if ( v_next_x < - Number.EPSILON ) {
  22420. direction_eq = true;
  22421. }
  22422. } else {
  22423. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  22424. direction_eq = true;
  22425. }
  22426. }
  22427. }
  22428. if ( direction_eq ) {
  22429. // console.log("Warning: lines are a straight sequence");
  22430. v_trans_x = - v_prev_y;
  22431. v_trans_y = v_prev_x;
  22432. shrink_by = Math.sqrt( v_prev_lensq );
  22433. } else {
  22434. // console.log("Warning: lines are a straight spike");
  22435. v_trans_x = v_prev_x;
  22436. v_trans_y = v_prev_y;
  22437. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  22438. }
  22439. }
  22440. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  22441. }
  22442. var contourMovements = [];
  22443. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22444. if ( j === il ) j = 0;
  22445. if ( k === il ) k = 0;
  22446. // (j)---(i)---(k)
  22447. // console.log('i,j,k', i, j , k)
  22448. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  22449. }
  22450. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  22451. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22452. ahole = holes[ h ];
  22453. oneHoleMovements = [];
  22454. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  22455. if ( j === il ) j = 0;
  22456. if ( k === il ) k = 0;
  22457. // (j)---(i)---(k)
  22458. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  22459. }
  22460. holesMovements.push( oneHoleMovements );
  22461. verticesMovements = verticesMovements.concat( oneHoleMovements );
  22462. }
  22463. // Loop bevelSegments, 1 for the front, 1 for the back
  22464. for ( b = 0; b < bevelSegments; b ++ ) {
  22465. //for ( b = bevelSegments; b > 0; b -- ) {
  22466. t = b / bevelSegments;
  22467. z = bevelThickness * ( 1 - t );
  22468. //z = bevelThickness * t;
  22469. bs = bevelSize * ( Math.sin ( t * Math.PI / 2 ) ); // curved
  22470. //bs = bevelSize * t; // linear
  22471. // contract shape
  22472. for ( i = 0, il = contour.length; i < il; i ++ ) {
  22473. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22474. v( vert.x, vert.y, - z );
  22475. }
  22476. // expand holes
  22477. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22478. ahole = holes[ h ];
  22479. oneHoleMovements = holesMovements[ h ];
  22480. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  22481. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22482. v( vert.x, vert.y, - z );
  22483. }
  22484. }
  22485. }
  22486. bs = bevelSize;
  22487. // Back facing vertices
  22488. for ( i = 0; i < vlen; i ++ ) {
  22489. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22490. if ( ! extrudeByPath ) {
  22491. v( vert.x, vert.y, 0 );
  22492. } else {
  22493. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  22494. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  22495. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  22496. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  22497. v( position2.x, position2.y, position2.z );
  22498. }
  22499. }
  22500. // Add stepped vertices...
  22501. // Including front facing vertices
  22502. var s;
  22503. for ( s = 1; s <= steps; s ++ ) {
  22504. for ( i = 0; i < vlen; i ++ ) {
  22505. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  22506. if ( ! extrudeByPath ) {
  22507. v( vert.x, vert.y, amount / steps * s );
  22508. } else {
  22509. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  22510. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  22511. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  22512. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  22513. v( position2.x, position2.y, position2.z );
  22514. }
  22515. }
  22516. }
  22517. // Add bevel segments planes
  22518. //for ( b = 1; b <= bevelSegments; b ++ ) {
  22519. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  22520. t = b / bevelSegments;
  22521. z = bevelThickness * ( 1 - t );
  22522. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  22523. bs = bevelSize * Math.sin ( t * Math.PI / 2 );
  22524. // contract shape
  22525. for ( i = 0, il = contour.length; i < il; i ++ ) {
  22526. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  22527. v( vert.x, vert.y, amount + z );
  22528. }
  22529. // expand holes
  22530. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22531. ahole = holes[ h ];
  22532. oneHoleMovements = holesMovements[ h ];
  22533. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  22534. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  22535. if ( ! extrudeByPath ) {
  22536. v( vert.x, vert.y, amount + z );
  22537. } else {
  22538. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  22539. }
  22540. }
  22541. }
  22542. }
  22543. /* Faces */
  22544. // Top and bottom faces
  22545. buildLidFaces();
  22546. // Sides faces
  22547. buildSideFaces();
  22548. ///// Internal functions
  22549. function buildLidFaces() {
  22550. if ( bevelEnabled ) {
  22551. var layer = 0; // steps + 1
  22552. var offset = vlen * layer;
  22553. // Bottom faces
  22554. for ( i = 0; i < flen; i ++ ) {
  22555. face = faces[ i ];
  22556. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  22557. }
  22558. layer = steps + bevelSegments * 2;
  22559. offset = vlen * layer;
  22560. // Top faces
  22561. for ( i = 0; i < flen; i ++ ) {
  22562. face = faces[ i ];
  22563. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  22564. }
  22565. } else {
  22566. // Bottom faces
  22567. for ( i = 0; i < flen; i ++ ) {
  22568. face = faces[ i ];
  22569. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  22570. }
  22571. // Top faces
  22572. for ( i = 0; i < flen; i ++ ) {
  22573. face = faces[ i ];
  22574. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  22575. }
  22576. }
  22577. }
  22578. // Create faces for the z-sides of the shape
  22579. function buildSideFaces() {
  22580. var layeroffset = 0;
  22581. sidewalls( contour, layeroffset );
  22582. layeroffset += contour.length;
  22583. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  22584. ahole = holes[ h ];
  22585. sidewalls( ahole, layeroffset );
  22586. //, true
  22587. layeroffset += ahole.length;
  22588. }
  22589. }
  22590. function sidewalls( contour, layeroffset ) {
  22591. var j, k;
  22592. i = contour.length;
  22593. while ( -- i >= 0 ) {
  22594. j = i;
  22595. k = i - 1;
  22596. if ( k < 0 ) k = contour.length - 1;
  22597. //console.log('b', i,j, i-1, k,vertices.length);
  22598. var s = 0, sl = steps + bevelSegments * 2;
  22599. for ( s = 0; s < sl; s ++ ) {
  22600. var slen1 = vlen * s;
  22601. var slen2 = vlen * ( s + 1 );
  22602. var a = layeroffset + j + slen1,
  22603. b = layeroffset + k + slen1,
  22604. c = layeroffset + k + slen2,
  22605. d = layeroffset + j + slen2;
  22606. f4( a, b, c, d, contour, s, sl, j, k );
  22607. }
  22608. }
  22609. }
  22610. function v( x, y, z ) {
  22611. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  22612. }
  22613. function f3( a, b, c ) {
  22614. a += shapesOffset;
  22615. b += shapesOffset;
  22616. c += shapesOffset;
  22617. scope.faces.push( new THREE.Face3( a, b, c, null, null, 0 ) );
  22618. var uvs = uvgen.generateTopUV( scope, a, b, c );
  22619. scope.faceVertexUvs[ 0 ].push( uvs );
  22620. }
  22621. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  22622. a += shapesOffset;
  22623. b += shapesOffset;
  22624. c += shapesOffset;
  22625. d += shapesOffset;
  22626. scope.faces.push( new THREE.Face3( a, b, d, null, null, 1 ) );
  22627. scope.faces.push( new THREE.Face3( b, c, d, null, null, 1 ) );
  22628. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  22629. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  22630. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  22631. }
  22632. };
  22633. THREE.ExtrudeGeometry.WorldUVGenerator = {
  22634. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  22635. var vertices = geometry.vertices;
  22636. var a = vertices[ indexA ];
  22637. var b = vertices[ indexB ];
  22638. var c = vertices[ indexC ];
  22639. return [
  22640. new THREE.Vector2( a.x, a.y ),
  22641. new THREE.Vector2( b.x, b.y ),
  22642. new THREE.Vector2( c.x, c.y )
  22643. ];
  22644. },
  22645. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  22646. var vertices = geometry.vertices;
  22647. var a = vertices[ indexA ];
  22648. var b = vertices[ indexB ];
  22649. var c = vertices[ indexC ];
  22650. var d = vertices[ indexD ];
  22651. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  22652. return [
  22653. new THREE.Vector2( a.x, 1 - a.z ),
  22654. new THREE.Vector2( b.x, 1 - b.z ),
  22655. new THREE.Vector2( c.x, 1 - c.z ),
  22656. new THREE.Vector2( d.x, 1 - d.z )
  22657. ];
  22658. } else {
  22659. return [
  22660. new THREE.Vector2( a.y, 1 - a.z ),
  22661. new THREE.Vector2( b.y, 1 - b.z ),
  22662. new THREE.Vector2( c.y, 1 - c.z ),
  22663. new THREE.Vector2( d.y, 1 - d.z )
  22664. ];
  22665. }
  22666. }
  22667. };
  22668. // File:src/extras/geometries/ShapeGeometry.js
  22669. /**
  22670. * @author jonobr1 / http://jonobr1.com
  22671. *
  22672. * Creates a one-sided polygonal geometry from a path shape. Similar to
  22673. * ExtrudeGeometry.
  22674. *
  22675. * parameters = {
  22676. *
  22677. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  22678. *
  22679. * material: <int> // material index for front and back faces
  22680. * uvGenerator: <Object> // object that provides UV generator functions
  22681. *
  22682. * }
  22683. **/
  22684. THREE.ShapeGeometry = function ( shapes, options ) {
  22685. THREE.Geometry.call( this );
  22686. this.type = 'ShapeGeometry';
  22687. if ( Array.isArray( shapes ) === false ) shapes = [ shapes ];
  22688. this.addShapeList( shapes, options );
  22689. this.computeFaceNormals();
  22690. };
  22691. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22692. THREE.ShapeGeometry.prototype.constructor = THREE.ShapeGeometry;
  22693. /**
  22694. * Add an array of shapes to THREE.ShapeGeometry.
  22695. */
  22696. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  22697. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  22698. this.addShape( shapes[ i ], options );
  22699. }
  22700. return this;
  22701. };
  22702. /**
  22703. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  22704. */
  22705. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  22706. if ( options === undefined ) options = {};
  22707. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  22708. var material = options.material;
  22709. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  22710. //
  22711. var i, l, hole;
  22712. var shapesOffset = this.vertices.length;
  22713. var shapePoints = shape.extractPoints( curveSegments );
  22714. var vertices = shapePoints.shape;
  22715. var holes = shapePoints.holes;
  22716. var reverse = ! THREE.ShapeUtils.isClockWise( vertices );
  22717. if ( reverse ) {
  22718. vertices = vertices.reverse();
  22719. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  22720. for ( i = 0, l = holes.length; i < l; i ++ ) {
  22721. hole = holes[ i ];
  22722. if ( THREE.ShapeUtils.isClockWise( hole ) ) {
  22723. holes[ i ] = hole.reverse();
  22724. }
  22725. }
  22726. reverse = false;
  22727. }
  22728. var faces = THREE.ShapeUtils.triangulateShape( vertices, holes );
  22729. // Vertices
  22730. for ( i = 0, l = holes.length; i < l; i ++ ) {
  22731. hole = holes[ i ];
  22732. vertices = vertices.concat( hole );
  22733. }
  22734. //
  22735. var vert, vlen = vertices.length;
  22736. var face, flen = faces.length;
  22737. for ( i = 0; i < vlen; i ++ ) {
  22738. vert = vertices[ i ];
  22739. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  22740. }
  22741. for ( i = 0; i < flen; i ++ ) {
  22742. face = faces[ i ];
  22743. var a = face[ 0 ] + shapesOffset;
  22744. var b = face[ 1 ] + shapesOffset;
  22745. var c = face[ 2 ] + shapesOffset;
  22746. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  22747. this.faceVertexUvs[ 0 ].push( uvgen.generateTopUV( this, a, b, c ) );
  22748. }
  22749. };
  22750. // File:src/extras/geometries/LatheBufferGeometry.js
  22751. /**
  22752. * @author Mugen87 / https://github.com/Mugen87
  22753. */
  22754. // points - to create a closed torus, one must use a set of points
  22755. // like so: [ a, b, c, d, a ], see first is the same as last.
  22756. // segments - the number of circumference segments to create
  22757. // phiStart - the starting radian
  22758. // phiLength - the radian (0 to 2PI) range of the lathed section
  22759. // 2PI is a closed lathe, less than 2PI is a portion.
  22760. THREE.LatheBufferGeometry = function ( points, segments, phiStart, phiLength ) {
  22761. THREE.BufferGeometry.call( this );
  22762. this.type = 'LatheBufferGeometry';
  22763. this.parameters = {
  22764. points: points,
  22765. segments: segments,
  22766. phiStart: phiStart,
  22767. phiLength: phiLength
  22768. };
  22769. segments = Math.floor( segments ) || 12;
  22770. phiStart = phiStart || 0;
  22771. phiLength = phiLength || Math.PI * 2;
  22772. // clamp phiLength so it's in range of [ 0, 2PI ]
  22773. phiLength = THREE.Math.clamp( phiLength, 0, Math.PI * 2 );
  22774. // these are used to calculate buffer length
  22775. var vertexCount = ( segments + 1 ) * points.length;
  22776. var indexCount = segments * points.length * 2 * 3;
  22777. // buffers
  22778. var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  22779. var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22780. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22781. // helper variables
  22782. var index = 0, indexOffset = 0, base;
  22783. var inversePointLength = 1.0 / ( points.length - 1 );
  22784. var inverseSegments = 1.0 / segments;
  22785. var vertex = new THREE.Vector3();
  22786. var uv = new THREE.Vector2();
  22787. var i, j;
  22788. // generate vertices and uvs
  22789. for ( i = 0; i <= segments; i ++ ) {
  22790. var phi = phiStart + i * inverseSegments * phiLength;
  22791. var sin = Math.sin( phi );
  22792. var cos = Math.cos( phi );
  22793. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  22794. // vertex
  22795. vertex.x = points[ j ].x * sin;
  22796. vertex.y = points[ j ].y;
  22797. vertex.z = points[ j ].x * cos;
  22798. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  22799. // uv
  22800. uv.x = i / segments;
  22801. uv.y = j / ( points.length - 1 );
  22802. uvs.setXY( index, uv.x, uv.y );
  22803. // increase index
  22804. index ++;
  22805. }
  22806. }
  22807. // generate indices
  22808. for ( i = 0; i < segments; i ++ ) {
  22809. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  22810. base = j + i * points.length;
  22811. // indices
  22812. var a = base;
  22813. var b = base + points.length;
  22814. var c = base + points.length + 1;
  22815. var d = base + 1;
  22816. // face one
  22817. indices.setX( indexOffset, a ); indexOffset++;
  22818. indices.setX( indexOffset, b ); indexOffset++;
  22819. indices.setX( indexOffset, d ); indexOffset++;
  22820. // face two
  22821. indices.setX( indexOffset, b ); indexOffset++;
  22822. indices.setX( indexOffset, c ); indexOffset++;
  22823. indices.setX( indexOffset, d ); indexOffset++;
  22824. }
  22825. }
  22826. // build geometry
  22827. this.setIndex( indices );
  22828. this.addAttribute( 'position', vertices );
  22829. this.addAttribute( 'uv', uvs );
  22830. // generate normals
  22831. this.computeVertexNormals();
  22832. // if the geometry is closed, we need to average the normals along the seam.
  22833. // because the corresponding vertices are identical (but still have different UVs).
  22834. if( phiLength === Math.PI * 2 ) {
  22835. var normals = this.attributes.normal.array;
  22836. var n1 = new THREE.Vector3();
  22837. var n2 = new THREE.Vector3();
  22838. var n = new THREE.Vector3();
  22839. // this is the buffer offset for the last line of vertices
  22840. base = segments * points.length * 3;
  22841. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  22842. // select the normal of the vertex in the first line
  22843. n1.x = normals[ j + 0 ];
  22844. n1.y = normals[ j + 1 ];
  22845. n1.z = normals[ j + 2 ];
  22846. // select the normal of the vertex in the last line
  22847. n2.x = normals[ base + j + 0 ];
  22848. n2.y = normals[ base + j + 1 ];
  22849. n2.z = normals[ base + j + 2 ];
  22850. // average normals
  22851. n.addVectors( n1, n2 ).normalize();
  22852. // assign the new values to both normals
  22853. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  22854. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  22855. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  22856. } // next row
  22857. }
  22858. };
  22859. THREE.LatheBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22860. THREE.LatheBufferGeometry.prototype.constructor = THREE.LatheBufferGeometry;
  22861. // File:src/extras/geometries/LatheGeometry.js
  22862. /**
  22863. * @author astrodud / http://astrodud.isgreat.org/
  22864. * @author zz85 / https://github.com/zz85
  22865. * @author bhouston / http://clara.io
  22866. */
  22867. // points - to create a closed torus, one must use a set of points
  22868. // like so: [ a, b, c, d, a ], see first is the same as last.
  22869. // segments - the number of circumference segments to create
  22870. // phiStart - the starting radian
  22871. // phiLength - the radian (0 to 2PI) range of the lathed section
  22872. // 2PI is a closed lathe, less than 2PI is a portion.
  22873. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  22874. THREE.Geometry.call( this );
  22875. this.type = 'LatheGeometry';
  22876. this.parameters = {
  22877. points: points,
  22878. segments: segments,
  22879. phiStart: phiStart,
  22880. phiLength: phiLength
  22881. };
  22882. this.fromBufferGeometry( new THREE.LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  22883. this.mergeVertices();
  22884. };
  22885. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22886. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  22887. // File:src/extras/geometries/PlaneGeometry.js
  22888. /**
  22889. * @author mrdoob / http://mrdoob.com/
  22890. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  22891. */
  22892. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  22893. THREE.Geometry.call( this );
  22894. this.type = 'PlaneGeometry';
  22895. this.parameters = {
  22896. width: width,
  22897. height: height,
  22898. widthSegments: widthSegments,
  22899. heightSegments: heightSegments
  22900. };
  22901. this.fromBufferGeometry( new THREE.PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  22902. };
  22903. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  22904. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  22905. // File:src/extras/geometries/PlaneBufferGeometry.js
  22906. /**
  22907. * @author mrdoob / http://mrdoob.com/
  22908. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  22909. */
  22910. THREE.PlaneBufferGeometry = function ( width, height, widthSegments, heightSegments ) {
  22911. THREE.BufferGeometry.call( this );
  22912. this.type = 'PlaneBufferGeometry';
  22913. this.parameters = {
  22914. width: width,
  22915. height: height,
  22916. widthSegments: widthSegments,
  22917. heightSegments: heightSegments
  22918. };
  22919. var width_half = width / 2;
  22920. var height_half = height / 2;
  22921. var gridX = Math.floor( widthSegments ) || 1;
  22922. var gridY = Math.floor( heightSegments ) || 1;
  22923. var gridX1 = gridX + 1;
  22924. var gridY1 = gridY + 1;
  22925. var segment_width = width / gridX;
  22926. var segment_height = height / gridY;
  22927. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  22928. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  22929. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  22930. var offset = 0;
  22931. var offset2 = 0;
  22932. for ( var iy = 0; iy < gridY1; iy ++ ) {
  22933. var y = iy * segment_height - height_half;
  22934. for ( var ix = 0; ix < gridX1; ix ++ ) {
  22935. var x = ix * segment_width - width_half;
  22936. vertices[ offset ] = x;
  22937. vertices[ offset + 1 ] = - y;
  22938. normals[ offset + 2 ] = 1;
  22939. uvs[ offset2 ] = ix / gridX;
  22940. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  22941. offset += 3;
  22942. offset2 += 2;
  22943. }
  22944. }
  22945. offset = 0;
  22946. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  22947. for ( var iy = 0; iy < gridY; iy ++ ) {
  22948. for ( var ix = 0; ix < gridX; ix ++ ) {
  22949. var a = ix + gridX1 * iy;
  22950. var b = ix + gridX1 * ( iy + 1 );
  22951. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  22952. var d = ( ix + 1 ) + gridX1 * iy;
  22953. indices[ offset ] = a;
  22954. indices[ offset + 1 ] = b;
  22955. indices[ offset + 2 ] = d;
  22956. indices[ offset + 3 ] = b;
  22957. indices[ offset + 4 ] = c;
  22958. indices[ offset + 5 ] = d;
  22959. offset += 6;
  22960. }
  22961. }
  22962. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  22963. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  22964. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  22965. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  22966. };
  22967. THREE.PlaneBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  22968. THREE.PlaneBufferGeometry.prototype.constructor = THREE.PlaneBufferGeometry;
  22969. // File:src/extras/geometries/RingBufferGeometry.js
  22970. /**
  22971. * @author Mugen87 / https://github.com/Mugen87
  22972. */
  22973. THREE.RingBufferGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  22974. THREE.BufferGeometry.call( this );
  22975. this.type = 'RingBufferGeometry';
  22976. this.parameters = {
  22977. innerRadius: innerRadius,
  22978. outerRadius: outerRadius,
  22979. thetaSegments: thetaSegments,
  22980. phiSegments: phiSegments,
  22981. thetaStart: thetaStart,
  22982. thetaLength: thetaLength
  22983. };
  22984. innerRadius = innerRadius || 20;
  22985. outerRadius = outerRadius || 50;
  22986. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22987. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22988. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  22989. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  22990. // these are used to calculate buffer length
  22991. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  22992. var indexCount = thetaSegments * phiSegments * 2 * 3;
  22993. // buffers
  22994. var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  22995. var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22996. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  22997. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  22998. // some helper variables
  22999. var index = 0, indexOffset = 0, segment;
  23000. var radius = innerRadius;
  23001. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  23002. var vertex = new THREE.Vector3();
  23003. var uv = new THREE.Vector2();
  23004. var j, i;
  23005. // generate vertices, normals and uvs
  23006. // values are generate from the inside of the ring to the outside
  23007. for ( j = 0; j <= phiSegments; j ++ ) {
  23008. for ( i = 0; i <= thetaSegments; i ++ ) {
  23009. segment = thetaStart + i / thetaSegments * thetaLength;
  23010. // vertex
  23011. vertex.x = radius * Math.cos( segment );
  23012. vertex.y = radius * Math.sin( segment );
  23013. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23014. // normal
  23015. normals.setXYZ( index, 0, 0, 1 );
  23016. // uv
  23017. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  23018. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  23019. uvs.setXY( index, uv.x, uv.y );
  23020. // increase index
  23021. index++;
  23022. }
  23023. // increase the radius for next row of vertices
  23024. radius += radiusStep;
  23025. }
  23026. // generate indices
  23027. for ( j = 0; j < phiSegments; j ++ ) {
  23028. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  23029. for ( i = 0; i < thetaSegments; i ++ ) {
  23030. segment = i + thetaSegmentLevel;
  23031. // indices
  23032. var a = segment;
  23033. var b = segment + thetaSegments + 1;
  23034. var c = segment + thetaSegments + 2;
  23035. var d = segment + 1;
  23036. // face one
  23037. indices.setX( indexOffset, a ); indexOffset++;
  23038. indices.setX( indexOffset, b ); indexOffset++;
  23039. indices.setX( indexOffset, c ); indexOffset++;
  23040. // face two
  23041. indices.setX( indexOffset, a ); indexOffset++;
  23042. indices.setX( indexOffset, c ); indexOffset++;
  23043. indices.setX( indexOffset, d ); indexOffset++;
  23044. }
  23045. }
  23046. // build geometry
  23047. this.setIndex( indices );
  23048. this.addAttribute( 'position', vertices );
  23049. this.addAttribute( 'normal', normals );
  23050. this.addAttribute( 'uv', uvs );
  23051. };
  23052. THREE.RingBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  23053. THREE.RingBufferGeometry.prototype.constructor = THREE.RingBufferGeometry;
  23054. // File:src/extras/geometries/RingGeometry.js
  23055. /**
  23056. * @author Kaleb Murphy
  23057. */
  23058. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  23059. THREE.Geometry.call( this );
  23060. this.type = 'RingGeometry';
  23061. this.parameters = {
  23062. innerRadius: innerRadius,
  23063. outerRadius: outerRadius,
  23064. thetaSegments: thetaSegments,
  23065. phiSegments: phiSegments,
  23066. thetaStart: thetaStart,
  23067. thetaLength: thetaLength
  23068. };
  23069. this.fromBufferGeometry( new THREE.RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  23070. };
  23071. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23072. THREE.RingGeometry.prototype.constructor = THREE.RingGeometry;
  23073. // File:src/extras/geometries/SphereGeometry.js
  23074. /**
  23075. * @author mrdoob / http://mrdoob.com/
  23076. */
  23077. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  23078. THREE.Geometry.call( this );
  23079. this.type = 'SphereGeometry';
  23080. this.parameters = {
  23081. radius: radius,
  23082. widthSegments: widthSegments,
  23083. heightSegments: heightSegments,
  23084. phiStart: phiStart,
  23085. phiLength: phiLength,
  23086. thetaStart: thetaStart,
  23087. thetaLength: thetaLength
  23088. };
  23089. this.fromBufferGeometry( new THREE.SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  23090. };
  23091. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23092. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  23093. // File:src/extras/geometries/SphereBufferGeometry.js
  23094. /**
  23095. * @author benaadams / https://twitter.com/ben_a_adams
  23096. * based on THREE.SphereGeometry
  23097. */
  23098. THREE.SphereBufferGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  23099. THREE.BufferGeometry.call( this );
  23100. this.type = 'SphereBufferGeometry';
  23101. this.parameters = {
  23102. radius: radius,
  23103. widthSegments: widthSegments,
  23104. heightSegments: heightSegments,
  23105. phiStart: phiStart,
  23106. phiLength: phiLength,
  23107. thetaStart: thetaStart,
  23108. thetaLength: thetaLength
  23109. };
  23110. radius = radius || 50;
  23111. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  23112. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  23113. phiStart = phiStart !== undefined ? phiStart : 0;
  23114. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  23115. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  23116. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  23117. var thetaEnd = thetaStart + thetaLength;
  23118. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  23119. var positions = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23120. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23121. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23122. var index = 0, vertices = [], normal = new THREE.Vector3();
  23123. for ( var y = 0; y <= heightSegments; y ++ ) {
  23124. var verticesRow = [];
  23125. var v = y / heightSegments;
  23126. for ( var x = 0; x <= widthSegments; x ++ ) {
  23127. var u = x / widthSegments;
  23128. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23129. var py = radius * Math.cos( thetaStart + v * thetaLength );
  23130. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  23131. normal.set( px, py, pz ).normalize();
  23132. positions.setXYZ( index, px, py, pz );
  23133. normals.setXYZ( index, normal.x, normal.y, normal.z );
  23134. uvs.setXY( index, u, 1 - v );
  23135. verticesRow.push( index );
  23136. index ++;
  23137. }
  23138. vertices.push( verticesRow );
  23139. }
  23140. var indices = [];
  23141. for ( var y = 0; y < heightSegments; y ++ ) {
  23142. for ( var x = 0; x < widthSegments; x ++ ) {
  23143. var v1 = vertices[ y ][ x + 1 ];
  23144. var v2 = vertices[ y ][ x ];
  23145. var v3 = vertices[ y + 1 ][ x ];
  23146. var v4 = vertices[ y + 1 ][ x + 1 ];
  23147. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  23148. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  23149. }
  23150. }
  23151. this.setIndex( new ( positions.count > 65535 ? THREE.Uint32Attribute : THREE.Uint16Attribute )( indices, 1 ) );
  23152. this.addAttribute( 'position', positions );
  23153. this.addAttribute( 'normal', normals );
  23154. this.addAttribute( 'uv', uvs );
  23155. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  23156. };
  23157. THREE.SphereBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  23158. THREE.SphereBufferGeometry.prototype.constructor = THREE.SphereBufferGeometry;
  23159. // File:src/extras/geometries/TextGeometry.js
  23160. /**
  23161. * @author zz85 / http://www.lab4games.net/zz85/blog
  23162. * @author alteredq / http://alteredqualia.com/
  23163. *
  23164. * Text = 3D Text
  23165. *
  23166. * parameters = {
  23167. * font: <THREE.Font>, // font
  23168. *
  23169. * size: <float>, // size of the text
  23170. * height: <float>, // thickness to extrude text
  23171. * curveSegments: <int>, // number of points on the curves
  23172. *
  23173. * bevelEnabled: <bool>, // turn on bevel
  23174. * bevelThickness: <float>, // how deep into text bevel goes
  23175. * bevelSize: <float> // how far from text outline is bevel
  23176. * }
  23177. */
  23178. THREE.TextGeometry = function ( text, parameters ) {
  23179. parameters = parameters || {};
  23180. var font = parameters.font;
  23181. if ( font instanceof THREE.Font === false ) {
  23182. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  23183. return new THREE.Geometry();
  23184. }
  23185. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  23186. // translate parameters to ExtrudeGeometry API
  23187. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  23188. // defaults
  23189. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  23190. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  23191. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  23192. THREE.ExtrudeGeometry.call( this, shapes, parameters );
  23193. this.type = 'TextGeometry';
  23194. };
  23195. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  23196. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  23197. // File:src/extras/geometries/TorusBufferGeometry.js
  23198. /**
  23199. * @author Mugen87 / https://github.com/Mugen87
  23200. */
  23201. THREE.TorusBufferGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  23202. THREE.BufferGeometry.call( this );
  23203. this.type = 'TorusBufferGeometry';
  23204. this.parameters = {
  23205. radius: radius,
  23206. tube: tube,
  23207. radialSegments: radialSegments,
  23208. tubularSegments: tubularSegments,
  23209. arc: arc
  23210. };
  23211. radius = radius || 100;
  23212. tube = tube || 40;
  23213. radialSegments = Math.floor( radialSegments ) || 8;
  23214. tubularSegments = Math.floor( tubularSegments ) || 6;
  23215. arc = arc || Math.PI * 2;
  23216. // used to calculate buffer length
  23217. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  23218. var indexCount = radialSegments * tubularSegments * 2 * 3;
  23219. // buffers
  23220. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  23221. var vertices = new Float32Array( vertexCount * 3 );
  23222. var normals = new Float32Array( vertexCount * 3 );
  23223. var uvs = new Float32Array( vertexCount * 2 );
  23224. // offset variables
  23225. var vertexBufferOffset = 0;
  23226. var uvBufferOffset = 0;
  23227. var indexBufferOffset = 0;
  23228. // helper variables
  23229. var center = new THREE.Vector3();
  23230. var vertex = new THREE.Vector3();
  23231. var normal = new THREE.Vector3();
  23232. var j, i;
  23233. // generate vertices, normals and uvs
  23234. for ( j = 0; j <= radialSegments; j ++ ) {
  23235. for ( i = 0; i <= tubularSegments; i ++ ) {
  23236. var u = i / tubularSegments * arc;
  23237. var v = j / radialSegments * Math.PI * 2;
  23238. // vertex
  23239. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  23240. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  23241. vertex.z = tube * Math.sin( v );
  23242. vertices[ vertexBufferOffset ] = vertex.x;
  23243. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  23244. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  23245. // this vector is used to calculate the normal
  23246. center.x = radius * Math.cos( u );
  23247. center.y = radius * Math.sin( u );
  23248. // normal
  23249. normal.subVectors( vertex, center ).normalize();
  23250. normals[ vertexBufferOffset ] = normal.x;
  23251. normals[ vertexBufferOffset + 1 ] = normal.y;
  23252. normals[ vertexBufferOffset + 2 ] = normal.z;
  23253. // uv
  23254. uvs[ uvBufferOffset ] = i / tubularSegments;
  23255. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  23256. // update offsets
  23257. vertexBufferOffset += 3;
  23258. uvBufferOffset += 2;
  23259. }
  23260. }
  23261. // generate indices
  23262. for ( j = 1; j <= radialSegments; j ++ ) {
  23263. for ( i = 1; i <= tubularSegments; i ++ ) {
  23264. // indices
  23265. var a = ( tubularSegments + 1 ) * j + i - 1;
  23266. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  23267. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  23268. var d = ( tubularSegments + 1 ) * j + i;
  23269. // face one
  23270. indices[ indexBufferOffset ] = a;
  23271. indices[ indexBufferOffset + 1 ] = b;
  23272. indices[ indexBufferOffset + 2 ] = d;
  23273. // face two
  23274. indices[ indexBufferOffset + 3 ] = b;
  23275. indices[ indexBufferOffset + 4 ] = c;
  23276. indices[ indexBufferOffset + 5 ] = d;
  23277. // update offset
  23278. indexBufferOffset += 6;
  23279. }
  23280. }
  23281. // build geometry
  23282. this.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  23283. this.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  23284. this.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  23285. this.addAttribute( 'uv', new THREE.BufferAttribute( uvs, 2 ) );
  23286. };
  23287. THREE.TorusBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  23288. THREE.TorusBufferGeometry.prototype.constructor = THREE.TorusBufferGeometry;
  23289. // File:src/extras/geometries/TorusGeometry.js
  23290. /**
  23291. * @author oosmoxiecode
  23292. * @author mrdoob / http://mrdoob.com/
  23293. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  23294. */
  23295. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  23296. THREE.Geometry.call( this );
  23297. this.type = 'TorusGeometry';
  23298. this.parameters = {
  23299. radius: radius,
  23300. tube: tube,
  23301. radialSegments: radialSegments,
  23302. tubularSegments: tubularSegments,
  23303. arc: arc
  23304. };
  23305. this.fromBufferGeometry( new THREE.TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  23306. };
  23307. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23308. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  23309. // File:src/extras/geometries/TorusKnotBufferGeometry.js
  23310. /**
  23311. * @author Mugen87 / https://github.com/Mugen87
  23312. *
  23313. * see: http://www.blackpawn.com/texts/pqtorus/
  23314. */
  23315. THREE.TorusKnotBufferGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q ) {
  23316. THREE.BufferGeometry.call( this );
  23317. this.type = 'TorusKnotBufferGeometry';
  23318. this.parameters = {
  23319. radius: radius,
  23320. tube: tube,
  23321. tubularSegments: tubularSegments,
  23322. radialSegments: radialSegments,
  23323. p: p,
  23324. q: q
  23325. };
  23326. radius = radius || 100;
  23327. tube = tube || 40;
  23328. tubularSegments = Math.floor( tubularSegments ) || 64;
  23329. radialSegments = Math.floor( radialSegments ) || 8;
  23330. p = p || 2;
  23331. q = q || 3;
  23332. // used to calculate buffer length
  23333. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  23334. var indexCount = radialSegments * tubularSegments * 2 * 3;
  23335. // buffers
  23336. var indices = new THREE.BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  23337. var vertices = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23338. var normals = new THREE.BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  23339. var uvs = new THREE.BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  23340. // helper variables
  23341. var i, j, index = 0, indexOffset = 0;
  23342. var vertex = new THREE.Vector3();
  23343. var normal = new THREE.Vector3();
  23344. var uv = new THREE.Vector2();
  23345. var P1 = new THREE.Vector3();
  23346. var P2 = new THREE.Vector3();
  23347. var B = new THREE.Vector3();
  23348. var T = new THREE.Vector3();
  23349. var N = new THREE.Vector3();
  23350. // generate vertices, normals and uvs
  23351. for ( i = 0; i <= tubularSegments; ++ i ) {
  23352. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  23353. var u = i / tubularSegments * p * Math.PI * 2;
  23354. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  23355. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  23356. calculatePositionOnCurve( u, p, q, radius, P1 );
  23357. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  23358. // calculate orthonormal basis
  23359. T.subVectors( P2, P1 );
  23360. N.addVectors( P2, P1 );
  23361. B.crossVectors( T, N );
  23362. N.crossVectors( B, T );
  23363. // normalize B, N. T can be ignored, we don't use it
  23364. B.normalize();
  23365. N.normalize();
  23366. for ( j = 0; j <= radialSegments; ++ j ) {
  23367. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  23368. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  23369. var v = j / radialSegments * Math.PI * 2;
  23370. var cx = - tube * Math.cos( v );
  23371. var cy = tube * Math.sin( v );
  23372. // now calculate the final vertex position.
  23373. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  23374. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  23375. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  23376. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  23377. // vertex
  23378. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  23379. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  23380. normal.subVectors( vertex, P1 ).normalize();
  23381. normals.setXYZ( index, normal.x, normal.y, normal.z );
  23382. // uv
  23383. uv.x = i / tubularSegments;
  23384. uv.y = j / radialSegments;
  23385. uvs.setXY( index, uv.x, uv.y );
  23386. // increase index
  23387. index ++;
  23388. }
  23389. }
  23390. // generate indices
  23391. for ( j = 1; j <= tubularSegments; j ++ ) {
  23392. for ( i = 1; i <= radialSegments; i ++ ) {
  23393. // indices
  23394. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  23395. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  23396. var c = ( radialSegments + 1 ) * j + i;
  23397. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  23398. // face one
  23399. indices.setX( indexOffset, a ); indexOffset++;
  23400. indices.setX( indexOffset, b ); indexOffset++;
  23401. indices.setX( indexOffset, d ); indexOffset++;
  23402. // face two
  23403. indices.setX( indexOffset, b ); indexOffset++;
  23404. indices.setX( indexOffset, c ); indexOffset++;
  23405. indices.setX( indexOffset, d ); indexOffset++;
  23406. }
  23407. }
  23408. // build geometry
  23409. this.setIndex( indices );
  23410. this.addAttribute( 'position', vertices );
  23411. this.addAttribute( 'normal', normals );
  23412. this.addAttribute( 'uv', uvs );
  23413. // this function calculates the current position on the torus curve
  23414. function calculatePositionOnCurve( u, p, q, radius, position ) {
  23415. var cu = Math.cos( u );
  23416. var su = Math.sin( u );
  23417. var quOverP = q / p * u;
  23418. var cs = Math.cos( quOverP );
  23419. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  23420. position.y = radius * ( 2 + cs ) * su * 0.5;
  23421. position.z = radius * Math.sin( quOverP ) * 0.5;
  23422. }
  23423. };
  23424. THREE.TorusKnotBufferGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  23425. THREE.TorusKnotBufferGeometry.prototype.constructor = THREE.TorusKnotBufferGeometry;
  23426. // File:src/extras/geometries/TorusKnotGeometry.js
  23427. /**
  23428. * @author oosmoxiecode
  23429. */
  23430. THREE.TorusKnotGeometry = function ( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  23431. THREE.Geometry.call( this );
  23432. this.type = 'TorusKnotGeometry';
  23433. this.parameters = {
  23434. radius: radius,
  23435. tube: tube,
  23436. tubularSegments: tubularSegments,
  23437. radialSegments: radialSegments,
  23438. p: p,
  23439. q: q
  23440. };
  23441. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  23442. this.fromBufferGeometry( new THREE.TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  23443. this.mergeVertices();
  23444. };
  23445. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23446. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  23447. // File:src/extras/geometries/TubeGeometry.js
  23448. /**
  23449. * @author WestLangley / https://github.com/WestLangley
  23450. * @author zz85 / https://github.com/zz85
  23451. * @author miningold / https://github.com/miningold
  23452. * @author jonobr1 / https://github.com/jonobr1
  23453. *
  23454. * Modified from the TorusKnotGeometry by @oosmoxiecode
  23455. *
  23456. * Creates a tube which extrudes along a 3d spline
  23457. *
  23458. * Uses parallel transport frames as described in
  23459. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23460. */
  23461. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed, taper ) {
  23462. THREE.Geometry.call( this );
  23463. this.type = 'TubeGeometry';
  23464. this.parameters = {
  23465. path: path,
  23466. segments: segments,
  23467. radius: radius,
  23468. radialSegments: radialSegments,
  23469. closed: closed,
  23470. taper: taper
  23471. };
  23472. segments = segments || 64;
  23473. radius = radius || 1;
  23474. radialSegments = radialSegments || 8;
  23475. closed = closed || false;
  23476. taper = taper || THREE.TubeGeometry.NoTaper;
  23477. var grid = [];
  23478. var scope = this,
  23479. tangent,
  23480. normal,
  23481. binormal,
  23482. numpoints = segments + 1,
  23483. u, v, r,
  23484. cx, cy,
  23485. pos, pos2 = new THREE.Vector3(),
  23486. i, j,
  23487. ip, jp,
  23488. a, b, c, d,
  23489. uva, uvb, uvc, uvd;
  23490. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  23491. tangents = frames.tangents,
  23492. normals = frames.normals,
  23493. binormals = frames.binormals;
  23494. // proxy internals
  23495. this.tangents = tangents;
  23496. this.normals = normals;
  23497. this.binormals = binormals;
  23498. function vert( x, y, z ) {
  23499. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  23500. }
  23501. // construct the grid
  23502. for ( i = 0; i < numpoints; i ++ ) {
  23503. grid[ i ] = [];
  23504. u = i / ( numpoints - 1 );
  23505. pos = path.getPointAt( u );
  23506. tangent = tangents[ i ];
  23507. normal = normals[ i ];
  23508. binormal = binormals[ i ];
  23509. r = radius * taper( u );
  23510. for ( j = 0; j < radialSegments; j ++ ) {
  23511. v = j / radialSegments * 2 * Math.PI;
  23512. cx = - r * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  23513. cy = r * Math.sin( v );
  23514. pos2.copy( pos );
  23515. pos2.x += cx * normal.x + cy * binormal.x;
  23516. pos2.y += cx * normal.y + cy * binormal.y;
  23517. pos2.z += cx * normal.z + cy * binormal.z;
  23518. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  23519. }
  23520. }
  23521. // construct the mesh
  23522. for ( i = 0; i < segments; i ++ ) {
  23523. for ( j = 0; j < radialSegments; j ++ ) {
  23524. ip = ( closed ) ? ( i + 1 ) % segments : i + 1;
  23525. jp = ( j + 1 ) % radialSegments;
  23526. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  23527. b = grid[ ip ][ j ];
  23528. c = grid[ ip ][ jp ];
  23529. d = grid[ i ][ jp ];
  23530. uva = new THREE.Vector2( i / segments, j / radialSegments );
  23531. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  23532. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  23533. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  23534. this.faces.push( new THREE.Face3( a, b, d ) );
  23535. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  23536. this.faces.push( new THREE.Face3( b, c, d ) );
  23537. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  23538. }
  23539. }
  23540. this.computeFaceNormals();
  23541. this.computeVertexNormals();
  23542. };
  23543. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23544. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  23545. THREE.TubeGeometry.NoTaper = function ( u ) {
  23546. return 1;
  23547. };
  23548. THREE.TubeGeometry.SinusoidalTaper = function ( u ) {
  23549. return Math.sin( Math.PI * u );
  23550. };
  23551. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  23552. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  23553. var normal = new THREE.Vector3(),
  23554. tangents = [],
  23555. normals = [],
  23556. binormals = [],
  23557. vec = new THREE.Vector3(),
  23558. mat = new THREE.Matrix4(),
  23559. numpoints = segments + 1,
  23560. theta,
  23561. smallest,
  23562. tx, ty, tz,
  23563. i, u;
  23564. // expose internals
  23565. this.tangents = tangents;
  23566. this.normals = normals;
  23567. this.binormals = binormals;
  23568. // compute the tangent vectors for each segment on the path
  23569. for ( i = 0; i < numpoints; i ++ ) {
  23570. u = i / ( numpoints - 1 );
  23571. tangents[ i ] = path.getTangentAt( u );
  23572. tangents[ i ].normalize();
  23573. }
  23574. initialNormal3();
  23575. /*
  23576. function initialNormal1(lastBinormal) {
  23577. // fixed start binormal. Has dangers of 0 vectors
  23578. normals[ 0 ] = new THREE.Vector3();
  23579. binormals[ 0 ] = new THREE.Vector3();
  23580. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  23581. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  23582. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  23583. }
  23584. function initialNormal2() {
  23585. // This uses the Frenet-Serret formula for deriving binormal
  23586. var t2 = path.getTangentAt( epsilon );
  23587. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  23588. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  23589. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  23590. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  23591. }
  23592. */
  23593. function initialNormal3() {
  23594. // select an initial normal vector perpendicular to the first tangent vector,
  23595. // and in the direction of the smallest tangent xyz component
  23596. normals[ 0 ] = new THREE.Vector3();
  23597. binormals[ 0 ] = new THREE.Vector3();
  23598. smallest = Number.MAX_VALUE;
  23599. tx = Math.abs( tangents[ 0 ].x );
  23600. ty = Math.abs( tangents[ 0 ].y );
  23601. tz = Math.abs( tangents[ 0 ].z );
  23602. if ( tx <= smallest ) {
  23603. smallest = tx;
  23604. normal.set( 1, 0, 0 );
  23605. }
  23606. if ( ty <= smallest ) {
  23607. smallest = ty;
  23608. normal.set( 0, 1, 0 );
  23609. }
  23610. if ( tz <= smallest ) {
  23611. normal.set( 0, 0, 1 );
  23612. }
  23613. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23614. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23615. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23616. }
  23617. // compute the slowly-varying normal and binormal vectors for each segment on the path
  23618. for ( i = 1; i < numpoints; i ++ ) {
  23619. normals[ i ] = normals[ i - 1 ].clone();
  23620. binormals[ i ] = binormals[ i - 1 ].clone();
  23621. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23622. if ( vec.length() > Number.EPSILON ) {
  23623. vec.normalize();
  23624. theta = Math.acos( THREE.Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  23625. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23626. }
  23627. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23628. }
  23629. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23630. if ( closed ) {
  23631. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints - 1 ] ), - 1, 1 ) );
  23632. theta /= ( numpoints - 1 );
  23633. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints - 1 ] ) ) > 0 ) {
  23634. theta = - theta;
  23635. }
  23636. for ( i = 1; i < numpoints; i ++ ) {
  23637. // twist a little...
  23638. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23639. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23640. }
  23641. }
  23642. };
  23643. // File:src/extras/geometries/PolyhedronGeometry.js
  23644. /**
  23645. * @author clockworkgeek / https://github.com/clockworkgeek
  23646. * @author timothypratley / https://github.com/timothypratley
  23647. * @author WestLangley / http://github.com/WestLangley
  23648. */
  23649. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  23650. THREE.Geometry.call( this );
  23651. this.type = 'PolyhedronGeometry';
  23652. this.parameters = {
  23653. vertices: vertices,
  23654. indices: indices,
  23655. radius: radius,
  23656. detail: detail
  23657. };
  23658. radius = radius || 1;
  23659. detail = detail || 0;
  23660. var that = this;
  23661. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  23662. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  23663. }
  23664. var p = this.vertices;
  23665. var faces = [];
  23666. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  23667. var v1 = p[ indices[ i ] ];
  23668. var v2 = p[ indices[ i + 1 ] ];
  23669. var v3 = p[ indices[ i + 2 ] ];
  23670. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, j );
  23671. }
  23672. var centroid = new THREE.Vector3();
  23673. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23674. subdivide( faces[ i ], detail );
  23675. }
  23676. // Handle case when face straddles the seam
  23677. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  23678. var uvs = this.faceVertexUvs[ 0 ][ i ];
  23679. var x0 = uvs[ 0 ].x;
  23680. var x1 = uvs[ 1 ].x;
  23681. var x2 = uvs[ 2 ].x;
  23682. var max = Math.max( x0, x1, x2 );
  23683. var min = Math.min( x0, x1, x2 );
  23684. if ( max > 0.9 && min < 0.1 ) {
  23685. // 0.9 is somewhat arbitrary
  23686. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  23687. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  23688. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  23689. }
  23690. }
  23691. // Apply radius
  23692. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  23693. this.vertices[ i ].multiplyScalar( radius );
  23694. }
  23695. // Merge vertices
  23696. this.mergeVertices();
  23697. this.computeFaceNormals();
  23698. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  23699. // Project vector onto sphere's surface
  23700. function prepare( vector ) {
  23701. var vertex = vector.normalize().clone();
  23702. vertex.index = that.vertices.push( vertex ) - 1;
  23703. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  23704. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  23705. var v = inclination( vector ) / Math.PI + 0.5;
  23706. vertex.uv = new THREE.Vector2( u, 1 - v );
  23707. return vertex;
  23708. }
  23709. // Approximate a curved face with recursively sub-divided triangles.
  23710. function make( v1, v2, v3, materialIndex ) {
  23711. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ], undefined, materialIndex );
  23712. that.faces.push( face );
  23713. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  23714. var azi = azimuth( centroid );
  23715. that.faceVertexUvs[ 0 ].push( [
  23716. correctUV( v1.uv, v1, azi ),
  23717. correctUV( v2.uv, v2, azi ),
  23718. correctUV( v3.uv, v3, azi )
  23719. ] );
  23720. }
  23721. // Analytically subdivide a face to the required detail level.
  23722. function subdivide( face, detail ) {
  23723. var cols = Math.pow( 2, detail );
  23724. var a = prepare( that.vertices[ face.a ] );
  23725. var b = prepare( that.vertices[ face.b ] );
  23726. var c = prepare( that.vertices[ face.c ] );
  23727. var v = [];
  23728. var materialIndex = face.materialIndex;
  23729. // Construct all of the vertices for this subdivision.
  23730. for ( var i = 0 ; i <= cols; i ++ ) {
  23731. v[ i ] = [];
  23732. var aj = prepare( a.clone().lerp( c, i / cols ) );
  23733. var bj = prepare( b.clone().lerp( c, i / cols ) );
  23734. var rows = cols - i;
  23735. for ( var j = 0; j <= rows; j ++ ) {
  23736. if ( j === 0 && i === cols ) {
  23737. v[ i ][ j ] = aj;
  23738. } else {
  23739. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  23740. }
  23741. }
  23742. }
  23743. // Construct all of the faces.
  23744. for ( var i = 0; i < cols ; i ++ ) {
  23745. for ( var j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  23746. var k = Math.floor( j / 2 );
  23747. if ( j % 2 === 0 ) {
  23748. make(
  23749. v[ i ][ k + 1 ],
  23750. v[ i + 1 ][ k ],
  23751. v[ i ][ k ],
  23752. materialIndex
  23753. );
  23754. } else {
  23755. make(
  23756. v[ i ][ k + 1 ],
  23757. v[ i + 1 ][ k + 1 ],
  23758. v[ i + 1 ][ k ],
  23759. materialIndex
  23760. );
  23761. }
  23762. }
  23763. }
  23764. }
  23765. // Angle around the Y axis, counter-clockwise when looking from above.
  23766. function azimuth( vector ) {
  23767. return Math.atan2( vector.z, - vector.x );
  23768. }
  23769. // Angle above the XZ plane.
  23770. function inclination( vector ) {
  23771. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23772. }
  23773. // Texture fixing helper. Spheres have some odd behaviours.
  23774. function correctUV( uv, vector, azimuth ) {
  23775. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  23776. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  23777. return uv.clone();
  23778. }
  23779. };
  23780. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23781. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  23782. // File:src/extras/geometries/DodecahedronGeometry.js
  23783. /**
  23784. * @author Abe Pazos / https://hamoid.com
  23785. */
  23786. THREE.DodecahedronGeometry = function ( radius, detail ) {
  23787. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23788. var r = 1 / t;
  23789. var vertices = [
  23790. // (±1, ±1, ±1)
  23791. - 1, - 1, - 1, - 1, - 1, 1,
  23792. - 1, 1, - 1, - 1, 1, 1,
  23793. 1, - 1, - 1, 1, - 1, 1,
  23794. 1, 1, - 1, 1, 1, 1,
  23795. // (0, ±1/φ, ±φ)
  23796. 0, - r, - t, 0, - r, t,
  23797. 0, r, - t, 0, r, t,
  23798. // (±1/φ, ±φ, 0)
  23799. - r, - t, 0, - r, t, 0,
  23800. r, - t, 0, r, t, 0,
  23801. // (±φ, 0, ±1/φ)
  23802. - t, 0, - r, t, 0, - r,
  23803. - t, 0, r, t, 0, r
  23804. ];
  23805. var indices = [
  23806. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23807. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23808. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23809. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23810. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23811. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23812. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23813. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23814. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23815. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23816. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23817. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23818. ];
  23819. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23820. this.type = 'DodecahedronGeometry';
  23821. this.parameters = {
  23822. radius: radius,
  23823. detail: detail
  23824. };
  23825. };
  23826. THREE.DodecahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  23827. THREE.DodecahedronGeometry.prototype.constructor = THREE.DodecahedronGeometry;
  23828. // File:src/extras/geometries/IcosahedronGeometry.js
  23829. /**
  23830. * @author timothypratley / https://github.com/timothypratley
  23831. */
  23832. THREE.IcosahedronGeometry = function ( radius, detail ) {
  23833. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23834. var vertices = [
  23835. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  23836. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  23837. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  23838. ];
  23839. var indices = [
  23840. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  23841. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  23842. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  23843. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  23844. ];
  23845. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23846. this.type = 'IcosahedronGeometry';
  23847. this.parameters = {
  23848. radius: radius,
  23849. detail: detail
  23850. };
  23851. };
  23852. THREE.IcosahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  23853. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  23854. // File:src/extras/geometries/OctahedronGeometry.js
  23855. /**
  23856. * @author timothypratley / https://github.com/timothypratley
  23857. */
  23858. THREE.OctahedronGeometry = function ( radius, detail ) {
  23859. var vertices = [
  23860. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  23861. ];
  23862. var indices = [
  23863. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  23864. ];
  23865. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23866. this.type = 'OctahedronGeometry';
  23867. this.parameters = {
  23868. radius: radius,
  23869. detail: detail
  23870. };
  23871. };
  23872. THREE.OctahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  23873. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  23874. // File:src/extras/geometries/TetrahedronGeometry.js
  23875. /**
  23876. * @author timothypratley / https://github.com/timothypratley
  23877. */
  23878. THREE.TetrahedronGeometry = function ( radius, detail ) {
  23879. var vertices = [
  23880. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  23881. ];
  23882. var indices = [
  23883. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  23884. ];
  23885. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  23886. this.type = 'TetrahedronGeometry';
  23887. this.parameters = {
  23888. radius: radius,
  23889. detail: detail
  23890. };
  23891. };
  23892. THREE.TetrahedronGeometry.prototype = Object.create( THREE.PolyhedronGeometry.prototype );
  23893. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  23894. // File:src/extras/geometries/ParametricGeometry.js
  23895. /**
  23896. * @author zz85 / https://github.com/zz85
  23897. * Parametric Surfaces Geometry
  23898. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  23899. *
  23900. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  23901. *
  23902. */
  23903. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  23904. THREE.Geometry.call( this );
  23905. this.type = 'ParametricGeometry';
  23906. this.parameters = {
  23907. func: func,
  23908. slices: slices,
  23909. stacks: stacks
  23910. };
  23911. var verts = this.vertices;
  23912. var faces = this.faces;
  23913. var uvs = this.faceVertexUvs[ 0 ];
  23914. var i, j, p;
  23915. var u, v;
  23916. var sliceCount = slices + 1;
  23917. for ( i = 0; i <= stacks; i ++ ) {
  23918. v = i / stacks;
  23919. for ( j = 0; j <= slices; j ++ ) {
  23920. u = j / slices;
  23921. p = func( u, v );
  23922. verts.push( p );
  23923. }
  23924. }
  23925. var a, b, c, d;
  23926. var uva, uvb, uvc, uvd;
  23927. for ( i = 0; i < stacks; i ++ ) {
  23928. for ( j = 0; j < slices; j ++ ) {
  23929. a = i * sliceCount + j;
  23930. b = i * sliceCount + j + 1;
  23931. c = ( i + 1 ) * sliceCount + j + 1;
  23932. d = ( i + 1 ) * sliceCount + j;
  23933. uva = new THREE.Vector2( j / slices, i / stacks );
  23934. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  23935. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  23936. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  23937. faces.push( new THREE.Face3( a, b, d ) );
  23938. uvs.push( [ uva, uvb, uvd ] );
  23939. faces.push( new THREE.Face3( b, c, d ) );
  23940. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  23941. }
  23942. }
  23943. // console.log(this);
  23944. // magic bullet
  23945. // var diff = this.mergeVertices();
  23946. // console.log('removed ', diff, ' vertices by merging');
  23947. this.computeFaceNormals();
  23948. this.computeVertexNormals();
  23949. };
  23950. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  23951. THREE.ParametricGeometry.prototype.constructor = THREE.ParametricGeometry;
  23952. // File:src/extras/geometries/WireframeGeometry.js
  23953. /**
  23954. * @author mrdoob / http://mrdoob.com/
  23955. */
  23956. THREE.WireframeGeometry = function ( geometry ) {
  23957. THREE.BufferGeometry.call( this );
  23958. var edge = [ 0, 0 ], hash = {};
  23959. function sortFunction( a, b ) {
  23960. return a - b;
  23961. }
  23962. var keys = [ 'a', 'b', 'c' ];
  23963. if ( geometry instanceof THREE.Geometry ) {
  23964. var vertices = geometry.vertices;
  23965. var faces = geometry.faces;
  23966. var numEdges = 0;
  23967. // allocate maximal size
  23968. var edges = new Uint32Array( 6 * faces.length );
  23969. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  23970. var face = faces[ i ];
  23971. for ( var j = 0; j < 3; j ++ ) {
  23972. edge[ 0 ] = face[ keys[ j ] ];
  23973. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  23974. edge.sort( sortFunction );
  23975. var key = edge.toString();
  23976. if ( hash[ key ] === undefined ) {
  23977. edges[ 2 * numEdges ] = edge[ 0 ];
  23978. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  23979. hash[ key ] = true;
  23980. numEdges ++;
  23981. }
  23982. }
  23983. }
  23984. var coords = new Float32Array( numEdges * 2 * 3 );
  23985. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  23986. for ( var j = 0; j < 2; j ++ ) {
  23987. var vertex = vertices[ edges [ 2 * i + j ] ];
  23988. var index = 6 * i + 3 * j;
  23989. coords[ index + 0 ] = vertex.x;
  23990. coords[ index + 1 ] = vertex.y;
  23991. coords[ index + 2 ] = vertex.z;
  23992. }
  23993. }
  23994. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  23995. } else if ( geometry instanceof THREE.BufferGeometry ) {
  23996. if ( geometry.index !== null ) {
  23997. // Indexed BufferGeometry
  23998. var indices = geometry.index.array;
  23999. var vertices = geometry.attributes.position;
  24000. var groups = geometry.groups;
  24001. var numEdges = 0;
  24002. if ( groups.length === 0 ) {
  24003. geometry.addGroup( 0, indices.length );
  24004. }
  24005. // allocate maximal size
  24006. var edges = new Uint32Array( 2 * indices.length );
  24007. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  24008. var group = groups[ o ];
  24009. var start = group.start;
  24010. var count = group.count;
  24011. for ( var i = start, il = start + count; i < il; i += 3 ) {
  24012. for ( var j = 0; j < 3; j ++ ) {
  24013. edge[ 0 ] = indices[ i + j ];
  24014. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  24015. edge.sort( sortFunction );
  24016. var key = edge.toString();
  24017. if ( hash[ key ] === undefined ) {
  24018. edges[ 2 * numEdges ] = edge[ 0 ];
  24019. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  24020. hash[ key ] = true;
  24021. numEdges ++;
  24022. }
  24023. }
  24024. }
  24025. }
  24026. var coords = new Float32Array( numEdges * 2 * 3 );
  24027. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  24028. for ( var j = 0; j < 2; j ++ ) {
  24029. var index = 6 * i + 3 * j;
  24030. var index2 = edges[ 2 * i + j ];
  24031. coords[ index + 0 ] = vertices.getX( index2 );
  24032. coords[ index + 1 ] = vertices.getY( index2 );
  24033. coords[ index + 2 ] = vertices.getZ( index2 );
  24034. }
  24035. }
  24036. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  24037. } else {
  24038. // non-indexed BufferGeometry
  24039. var vertices = geometry.attributes.position.array;
  24040. var numEdges = vertices.length / 3;
  24041. var numTris = numEdges / 3;
  24042. var coords = new Float32Array( numEdges * 2 * 3 );
  24043. for ( var i = 0, l = numTris; i < l; i ++ ) {
  24044. for ( var j = 0; j < 3; j ++ ) {
  24045. var index = 18 * i + 6 * j;
  24046. var index1 = 9 * i + 3 * j;
  24047. coords[ index + 0 ] = vertices[ index1 ];
  24048. coords[ index + 1 ] = vertices[ index1 + 1 ];
  24049. coords[ index + 2 ] = vertices[ index1 + 2 ];
  24050. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  24051. coords[ index + 3 ] = vertices[ index2 ];
  24052. coords[ index + 4 ] = vertices[ index2 + 1 ];
  24053. coords[ index + 5 ] = vertices[ index2 + 2 ];
  24054. }
  24055. }
  24056. this.addAttribute( 'position', new THREE.BufferAttribute( coords, 3 ) );
  24057. }
  24058. }
  24059. };
  24060. THREE.WireframeGeometry.prototype = Object.create( THREE.BufferGeometry.prototype );
  24061. THREE.WireframeGeometry.prototype.constructor = THREE.WireframeGeometry;
  24062. // File:src/extras/helpers/AxisHelper.js
  24063. /**
  24064. * @author sroucheray / http://sroucheray.org/
  24065. * @author mrdoob / http://mrdoob.com/
  24066. */
  24067. THREE.AxisHelper = function ( size ) {
  24068. size = size || 1;
  24069. var vertices = new Float32Array( [
  24070. 0, 0, 0, size, 0, 0,
  24071. 0, 0, 0, 0, size, 0,
  24072. 0, 0, 0, 0, 0, size
  24073. ] );
  24074. var colors = new Float32Array( [
  24075. 1, 0, 0, 1, 0.6, 0,
  24076. 0, 1, 0, 0.6, 1, 0,
  24077. 0, 0, 1, 0, 0.6, 1
  24078. ] );
  24079. var geometry = new THREE.BufferGeometry();
  24080. geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  24081. geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  24082. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  24083. THREE.LineSegments.call( this, geometry, material );
  24084. };
  24085. THREE.AxisHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24086. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  24087. // File:src/extras/helpers/ArrowHelper.js
  24088. /**
  24089. * @author WestLangley / http://github.com/WestLangley
  24090. * @author zz85 / http://github.com/zz85
  24091. * @author bhouston / http://clara.io
  24092. *
  24093. * Creates an arrow for visualizing directions
  24094. *
  24095. * Parameters:
  24096. * dir - Vector3
  24097. * origin - Vector3
  24098. * length - Number
  24099. * color - color in hex value
  24100. * headLength - Number
  24101. * headWidth - Number
  24102. */
  24103. THREE.ArrowHelper = ( function () {
  24104. var lineGeometry = new THREE.Geometry();
  24105. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 1, 0 ) );
  24106. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  24107. coneGeometry.translate( 0, - 0.5, 0 );
  24108. return function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  24109. // dir is assumed to be normalized
  24110. THREE.Object3D.call( this );
  24111. if ( color === undefined ) color = 0xffff00;
  24112. if ( length === undefined ) length = 1;
  24113. if ( headLength === undefined ) headLength = 0.2 * length;
  24114. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24115. this.position.copy( origin );
  24116. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: color } ) );
  24117. this.line.matrixAutoUpdate = false;
  24118. this.add( this.line );
  24119. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: color } ) );
  24120. this.cone.matrixAutoUpdate = false;
  24121. this.add( this.cone );
  24122. this.setDirection( dir );
  24123. this.setLength( length, headLength, headWidth );
  24124. }
  24125. }() );
  24126. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  24127. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  24128. THREE.ArrowHelper.prototype.setDirection = ( function () {
  24129. var axis = new THREE.Vector3();
  24130. var radians;
  24131. return function setDirection( dir ) {
  24132. // dir is assumed to be normalized
  24133. if ( dir.y > 0.99999 ) {
  24134. this.quaternion.set( 0, 0, 0, 1 );
  24135. } else if ( dir.y < - 0.99999 ) {
  24136. this.quaternion.set( 1, 0, 0, 0 );
  24137. } else {
  24138. axis.set( dir.z, 0, - dir.x ).normalize();
  24139. radians = Math.acos( dir.y );
  24140. this.quaternion.setFromAxisAngle( axis, radians );
  24141. }
  24142. };
  24143. }() );
  24144. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  24145. if ( headLength === undefined ) headLength = 0.2 * length;
  24146. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  24147. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  24148. this.line.updateMatrix();
  24149. this.cone.scale.set( headWidth, headLength, headWidth );
  24150. this.cone.position.y = length;
  24151. this.cone.updateMatrix();
  24152. };
  24153. THREE.ArrowHelper.prototype.setColor = function ( color ) {
  24154. this.line.material.color.set( color );
  24155. this.cone.material.color.set( color );
  24156. };
  24157. // File:src/extras/helpers/BoxHelper.js
  24158. /**
  24159. * @author mrdoob / http://mrdoob.com/
  24160. */
  24161. THREE.BoxHelper = function ( object ) {
  24162. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  24163. var positions = new Float32Array( 8 * 3 );
  24164. var geometry = new THREE.BufferGeometry();
  24165. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  24166. geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
  24167. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ) );
  24168. if ( object !== undefined ) {
  24169. this.update( object );
  24170. }
  24171. };
  24172. THREE.BoxHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24173. THREE.BoxHelper.prototype.constructor = THREE.BoxHelper;
  24174. THREE.BoxHelper.prototype.update = ( function () {
  24175. var box = new THREE.Box3();
  24176. return function ( object ) {
  24177. if ( object instanceof THREE.Box3 ) {
  24178. box.copy( object );
  24179. } else {
  24180. box.setFromObject( object );
  24181. }
  24182. if ( box.isEmpty() ) return;
  24183. var min = box.min;
  24184. var max = box.max;
  24185. /*
  24186. 5____4
  24187. 1/___0/|
  24188. | 6__|_7
  24189. 2/___3/
  24190. 0: max.x, max.y, max.z
  24191. 1: min.x, max.y, max.z
  24192. 2: min.x, min.y, max.z
  24193. 3: max.x, min.y, max.z
  24194. 4: max.x, max.y, min.z
  24195. 5: min.x, max.y, min.z
  24196. 6: min.x, min.y, min.z
  24197. 7: max.x, min.y, min.z
  24198. */
  24199. var position = this.geometry.attributes.position;
  24200. var array = position.array;
  24201. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  24202. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  24203. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  24204. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  24205. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  24206. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  24207. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  24208. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  24209. position.needsUpdate = true;
  24210. this.geometry.computeBoundingSphere();
  24211. };
  24212. } )();
  24213. // File:src/extras/helpers/BoundingBoxHelper.js
  24214. /**
  24215. * @author WestLangley / http://github.com/WestLangley
  24216. */
  24217. // a helper to show the world-axis-aligned bounding box for an object
  24218. THREE.BoundingBoxHelper = function ( object, hex ) {
  24219. var color = ( hex !== undefined ) ? hex : 0x888888;
  24220. this.object = object;
  24221. this.box = new THREE.Box3();
  24222. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  24223. };
  24224. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  24225. THREE.BoundingBoxHelper.prototype.constructor = THREE.BoundingBoxHelper;
  24226. THREE.BoundingBoxHelper.prototype.update = function () {
  24227. this.box.setFromObject( this.object );
  24228. this.box.size( this.scale );
  24229. this.box.center( this.position );
  24230. };
  24231. // File:src/extras/helpers/CameraHelper.js
  24232. /**
  24233. * @author alteredq / http://alteredqualia.com/
  24234. *
  24235. * - shows frustum, line of sight and up of the camera
  24236. * - suitable for fast updates
  24237. * - based on frustum visualization in lightgl.js shadowmap example
  24238. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  24239. */
  24240. THREE.CameraHelper = function ( camera ) {
  24241. var geometry = new THREE.Geometry();
  24242. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  24243. var pointMap = {};
  24244. // colors
  24245. var hexFrustum = 0xffaa00;
  24246. var hexCone = 0xff0000;
  24247. var hexUp = 0x00aaff;
  24248. var hexTarget = 0xffffff;
  24249. var hexCross = 0x333333;
  24250. // near
  24251. addLine( "n1", "n2", hexFrustum );
  24252. addLine( "n2", "n4", hexFrustum );
  24253. addLine( "n4", "n3", hexFrustum );
  24254. addLine( "n3", "n1", hexFrustum );
  24255. // far
  24256. addLine( "f1", "f2", hexFrustum );
  24257. addLine( "f2", "f4", hexFrustum );
  24258. addLine( "f4", "f3", hexFrustum );
  24259. addLine( "f3", "f1", hexFrustum );
  24260. // sides
  24261. addLine( "n1", "f1", hexFrustum );
  24262. addLine( "n2", "f2", hexFrustum );
  24263. addLine( "n3", "f3", hexFrustum );
  24264. addLine( "n4", "f4", hexFrustum );
  24265. // cone
  24266. addLine( "p", "n1", hexCone );
  24267. addLine( "p", "n2", hexCone );
  24268. addLine( "p", "n3", hexCone );
  24269. addLine( "p", "n4", hexCone );
  24270. // up
  24271. addLine( "u1", "u2", hexUp );
  24272. addLine( "u2", "u3", hexUp );
  24273. addLine( "u3", "u1", hexUp );
  24274. // target
  24275. addLine( "c", "t", hexTarget );
  24276. addLine( "p", "c", hexCross );
  24277. // cross
  24278. addLine( "cn1", "cn2", hexCross );
  24279. addLine( "cn3", "cn4", hexCross );
  24280. addLine( "cf1", "cf2", hexCross );
  24281. addLine( "cf3", "cf4", hexCross );
  24282. function addLine( a, b, hex ) {
  24283. addPoint( a, hex );
  24284. addPoint( b, hex );
  24285. }
  24286. function addPoint( id, hex ) {
  24287. geometry.vertices.push( new THREE.Vector3() );
  24288. geometry.colors.push( new THREE.Color( hex ) );
  24289. if ( pointMap[ id ] === undefined ) {
  24290. pointMap[ id ] = [];
  24291. }
  24292. pointMap[ id ].push( geometry.vertices.length - 1 );
  24293. }
  24294. THREE.LineSegments.call( this, geometry, material );
  24295. this.camera = camera;
  24296. this.camera.updateProjectionMatrix();
  24297. this.matrix = camera.matrixWorld;
  24298. this.matrixAutoUpdate = false;
  24299. this.pointMap = pointMap;
  24300. this.update();
  24301. };
  24302. THREE.CameraHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24303. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  24304. THREE.CameraHelper.prototype.update = function () {
  24305. var geometry, pointMap;
  24306. var vector = new THREE.Vector3();
  24307. var camera = new THREE.Camera();
  24308. function setPoint( point, x, y, z ) {
  24309. vector.set( x, y, z ).unproject( camera );
  24310. var points = pointMap[ point ];
  24311. if ( points !== undefined ) {
  24312. for ( var i = 0, il = points.length; i < il; i ++ ) {
  24313. geometry.vertices[ points[ i ] ].copy( vector );
  24314. }
  24315. }
  24316. }
  24317. return function () {
  24318. geometry = this.geometry;
  24319. pointMap = this.pointMap;
  24320. var w = 1, h = 1;
  24321. // we need just camera projection matrix
  24322. // world matrix must be identity
  24323. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  24324. // center / target
  24325. setPoint( "c", 0, 0, - 1 );
  24326. setPoint( "t", 0, 0, 1 );
  24327. // near
  24328. setPoint( "n1", - w, - h, - 1 );
  24329. setPoint( "n2", w, - h, - 1 );
  24330. setPoint( "n3", - w, h, - 1 );
  24331. setPoint( "n4", w, h, - 1 );
  24332. // far
  24333. setPoint( "f1", - w, - h, 1 );
  24334. setPoint( "f2", w, - h, 1 );
  24335. setPoint( "f3", - w, h, 1 );
  24336. setPoint( "f4", w, h, 1 );
  24337. // up
  24338. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  24339. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  24340. setPoint( "u3", 0, h * 2, - 1 );
  24341. // cross
  24342. setPoint( "cf1", - w, 0, 1 );
  24343. setPoint( "cf2", w, 0, 1 );
  24344. setPoint( "cf3", 0, - h, 1 );
  24345. setPoint( "cf4", 0, h, 1 );
  24346. setPoint( "cn1", - w, 0, - 1 );
  24347. setPoint( "cn2", w, 0, - 1 );
  24348. setPoint( "cn3", 0, - h, - 1 );
  24349. setPoint( "cn4", 0, h, - 1 );
  24350. geometry.verticesNeedUpdate = true;
  24351. };
  24352. }();
  24353. // File:src/extras/helpers/DirectionalLightHelper.js
  24354. /**
  24355. * @author alteredq / http://alteredqualia.com/
  24356. * @author mrdoob / http://mrdoob.com/
  24357. * @author WestLangley / http://github.com/WestLangley
  24358. */
  24359. THREE.DirectionalLightHelper = function ( light, size ) {
  24360. THREE.Object3D.call( this );
  24361. this.light = light;
  24362. this.light.updateMatrixWorld();
  24363. this.matrix = light.matrixWorld;
  24364. this.matrixAutoUpdate = false;
  24365. size = size || 1;
  24366. var geometry = new THREE.Geometry();
  24367. geometry.vertices.push(
  24368. new THREE.Vector3( - size, size, 0 ),
  24369. new THREE.Vector3( size, size, 0 ),
  24370. new THREE.Vector3( size, - size, 0 ),
  24371. new THREE.Vector3( - size, - size, 0 ),
  24372. new THREE.Vector3( - size, size, 0 )
  24373. );
  24374. var material = new THREE.LineBasicMaterial( { fog: false } );
  24375. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24376. this.lightPlane = new THREE.Line( geometry, material );
  24377. this.add( this.lightPlane );
  24378. geometry = new THREE.Geometry();
  24379. geometry.vertices.push(
  24380. new THREE.Vector3(),
  24381. new THREE.Vector3()
  24382. );
  24383. material = new THREE.LineBasicMaterial( { fog: false } );
  24384. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24385. this.targetLine = new THREE.Line( geometry, material );
  24386. this.add( this.targetLine );
  24387. this.update();
  24388. };
  24389. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  24390. THREE.DirectionalLightHelper.prototype.constructor = THREE.DirectionalLightHelper;
  24391. THREE.DirectionalLightHelper.prototype.dispose = function () {
  24392. this.lightPlane.geometry.dispose();
  24393. this.lightPlane.material.dispose();
  24394. this.targetLine.geometry.dispose();
  24395. this.targetLine.material.dispose();
  24396. };
  24397. THREE.DirectionalLightHelper.prototype.update = function () {
  24398. var v1 = new THREE.Vector3();
  24399. var v2 = new THREE.Vector3();
  24400. var v3 = new THREE.Vector3();
  24401. return function () {
  24402. v1.setFromMatrixPosition( this.light.matrixWorld );
  24403. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  24404. v3.subVectors( v2, v1 );
  24405. this.lightPlane.lookAt( v3 );
  24406. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24407. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  24408. this.targetLine.geometry.verticesNeedUpdate = true;
  24409. this.targetLine.material.color.copy( this.lightPlane.material.color );
  24410. };
  24411. }();
  24412. // File:src/extras/helpers/EdgesHelper.js
  24413. /**
  24414. * @author WestLangley / http://github.com/WestLangley
  24415. * @param object THREE.Mesh whose geometry will be used
  24416. * @param hex line color
  24417. * @param thresholdAngle the minimum angle (in degrees),
  24418. * between the face normals of adjacent faces,
  24419. * that is required to render an edge. A value of 10 means
  24420. * an edge is only rendered if the angle is at least 10 degrees.
  24421. */
  24422. THREE.EdgesHelper = function ( object, hex, thresholdAngle ) {
  24423. var color = ( hex !== undefined ) ? hex : 0xffffff;
  24424. THREE.LineSegments.call( this, new THREE.EdgesGeometry( object.geometry, thresholdAngle ), new THREE.LineBasicMaterial( { color: color } ) );
  24425. this.matrix = object.matrixWorld;
  24426. this.matrixAutoUpdate = false;
  24427. };
  24428. THREE.EdgesHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24429. THREE.EdgesHelper.prototype.constructor = THREE.EdgesHelper;
  24430. // File:src/extras/helpers/FaceNormalsHelper.js
  24431. /**
  24432. * @author mrdoob / http://mrdoob.com/
  24433. * @author WestLangley / http://github.com/WestLangley
  24434. */
  24435. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  24436. // FaceNormalsHelper only supports THREE.Geometry
  24437. this.object = object;
  24438. this.size = ( size !== undefined ) ? size : 1;
  24439. var color = ( hex !== undefined ) ? hex : 0xffff00;
  24440. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24441. //
  24442. var nNormals = 0;
  24443. var objGeometry = this.object.geometry;
  24444. if ( objGeometry instanceof THREE.Geometry ) {
  24445. nNormals = objGeometry.faces.length;
  24446. } else {
  24447. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  24448. }
  24449. //
  24450. var geometry = new THREE.BufferGeometry();
  24451. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  24452. geometry.addAttribute( 'position', positions );
  24453. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  24454. //
  24455. this.matrixAutoUpdate = false;
  24456. this.update();
  24457. };
  24458. THREE.FaceNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24459. THREE.FaceNormalsHelper.prototype.constructor = THREE.FaceNormalsHelper;
  24460. THREE.FaceNormalsHelper.prototype.update = ( function () {
  24461. var v1 = new THREE.Vector3();
  24462. var v2 = new THREE.Vector3();
  24463. var normalMatrix = new THREE.Matrix3();
  24464. return function update() {
  24465. this.object.updateMatrixWorld( true );
  24466. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24467. var matrixWorld = this.object.matrixWorld;
  24468. var position = this.geometry.attributes.position;
  24469. //
  24470. var objGeometry = this.object.geometry;
  24471. var vertices = objGeometry.vertices;
  24472. var faces = objGeometry.faces;
  24473. var idx = 0;
  24474. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24475. var face = faces[ i ];
  24476. var normal = face.normal;
  24477. v1.copy( vertices[ face.a ] )
  24478. .add( vertices[ face.b ] )
  24479. .add( vertices[ face.c ] )
  24480. .divideScalar( 3 )
  24481. .applyMatrix4( matrixWorld );
  24482. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24483. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24484. idx = idx + 1;
  24485. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24486. idx = idx + 1;
  24487. }
  24488. position.needsUpdate = true;
  24489. return this;
  24490. }
  24491. }() );
  24492. // File:src/extras/helpers/GridHelper.js
  24493. /**
  24494. * @author mrdoob / http://mrdoob.com/
  24495. */
  24496. THREE.GridHelper = function ( size, step ) {
  24497. var geometry = new THREE.Geometry();
  24498. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  24499. this.color1 = new THREE.Color( 0x444444 );
  24500. this.color2 = new THREE.Color( 0x888888 );
  24501. for ( var i = - size; i <= size; i += step ) {
  24502. geometry.vertices.push(
  24503. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  24504. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  24505. );
  24506. var color = i === 0 ? this.color1 : this.color2;
  24507. geometry.colors.push( color, color, color, color );
  24508. }
  24509. THREE.LineSegments.call( this, geometry, material );
  24510. };
  24511. THREE.GridHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24512. THREE.GridHelper.prototype.constructor = THREE.GridHelper;
  24513. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  24514. this.color1.set( colorCenterLine );
  24515. this.color2.set( colorGrid );
  24516. this.geometry.colorsNeedUpdate = true;
  24517. };
  24518. // File:src/extras/helpers/HemisphereLightHelper.js
  24519. /**
  24520. * @author alteredq / http://alteredqualia.com/
  24521. * @author mrdoob / http://mrdoob.com/
  24522. */
  24523. THREE.HemisphereLightHelper = function ( light, sphereSize ) {
  24524. THREE.Object3D.call( this );
  24525. this.light = light;
  24526. this.light.updateMatrixWorld();
  24527. this.matrix = light.matrixWorld;
  24528. this.matrixAutoUpdate = false;
  24529. this.colors = [ new THREE.Color(), new THREE.Color() ];
  24530. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  24531. geometry.rotateX( - Math.PI / 2 );
  24532. for ( var i = 0, il = 8; i < il; i ++ ) {
  24533. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  24534. }
  24535. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  24536. this.lightSphere = new THREE.Mesh( geometry, material );
  24537. this.add( this.lightSphere );
  24538. this.update();
  24539. };
  24540. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  24541. THREE.HemisphereLightHelper.prototype.constructor = THREE.HemisphereLightHelper;
  24542. THREE.HemisphereLightHelper.prototype.dispose = function () {
  24543. this.lightSphere.geometry.dispose();
  24544. this.lightSphere.material.dispose();
  24545. };
  24546. THREE.HemisphereLightHelper.prototype.update = function () {
  24547. var vector = new THREE.Vector3();
  24548. return function () {
  24549. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  24550. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  24551. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  24552. this.lightSphere.geometry.colorsNeedUpdate = true;
  24553. }
  24554. }();
  24555. // File:src/extras/helpers/PointLightHelper.js
  24556. /**
  24557. * @author alteredq / http://alteredqualia.com/
  24558. * @author mrdoob / http://mrdoob.com/
  24559. */
  24560. THREE.PointLightHelper = function ( light, sphereSize ) {
  24561. this.light = light;
  24562. this.light.updateMatrixWorld();
  24563. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  24564. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  24565. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24566. THREE.Mesh.call( this, geometry, material );
  24567. this.matrix = this.light.matrixWorld;
  24568. this.matrixAutoUpdate = false;
  24569. /*
  24570. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  24571. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  24572. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  24573. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  24574. var d = light.distance;
  24575. if ( d === 0.0 ) {
  24576. this.lightDistance.visible = false;
  24577. } else {
  24578. this.lightDistance.scale.set( d, d, d );
  24579. }
  24580. this.add( this.lightDistance );
  24581. */
  24582. };
  24583. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  24584. THREE.PointLightHelper.prototype.constructor = THREE.PointLightHelper;
  24585. THREE.PointLightHelper.prototype.dispose = function () {
  24586. this.geometry.dispose();
  24587. this.material.dispose();
  24588. };
  24589. THREE.PointLightHelper.prototype.update = function () {
  24590. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24591. /*
  24592. var d = this.light.distance;
  24593. if ( d === 0.0 ) {
  24594. this.lightDistance.visible = false;
  24595. } else {
  24596. this.lightDistance.visible = true;
  24597. this.lightDistance.scale.set( d, d, d );
  24598. }
  24599. */
  24600. };
  24601. // File:src/extras/helpers/SkeletonHelper.js
  24602. /**
  24603. * @author Sean Griffin / http://twitter.com/sgrif
  24604. * @author Michael Guerrero / http://realitymeltdown.com
  24605. * @author mrdoob / http://mrdoob.com/
  24606. * @author ikerr / http://verold.com
  24607. */
  24608. THREE.SkeletonHelper = function ( object ) {
  24609. this.bones = this.getBoneList( object );
  24610. var geometry = new THREE.Geometry();
  24611. for ( var i = 0; i < this.bones.length; i ++ ) {
  24612. var bone = this.bones[ i ];
  24613. if ( bone.parent instanceof THREE.Bone ) {
  24614. geometry.vertices.push( new THREE.Vector3() );
  24615. geometry.vertices.push( new THREE.Vector3() );
  24616. geometry.colors.push( new THREE.Color( 0, 0, 1 ) );
  24617. geometry.colors.push( new THREE.Color( 0, 1, 0 ) );
  24618. }
  24619. }
  24620. geometry.dynamic = true;
  24621. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  24622. THREE.LineSegments.call( this, geometry, material );
  24623. this.root = object;
  24624. this.matrix = object.matrixWorld;
  24625. this.matrixAutoUpdate = false;
  24626. this.update();
  24627. };
  24628. THREE.SkeletonHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24629. THREE.SkeletonHelper.prototype.constructor = THREE.SkeletonHelper;
  24630. THREE.SkeletonHelper.prototype.getBoneList = function( object ) {
  24631. var boneList = [];
  24632. if ( object instanceof THREE.Bone ) {
  24633. boneList.push( object );
  24634. }
  24635. for ( var i = 0; i < object.children.length; i ++ ) {
  24636. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  24637. }
  24638. return boneList;
  24639. };
  24640. THREE.SkeletonHelper.prototype.update = function () {
  24641. var geometry = this.geometry;
  24642. var matrixWorldInv = new THREE.Matrix4().getInverse( this.root.matrixWorld );
  24643. var boneMatrix = new THREE.Matrix4();
  24644. var j = 0;
  24645. for ( var i = 0; i < this.bones.length; i ++ ) {
  24646. var bone = this.bones[ i ];
  24647. if ( bone.parent instanceof THREE.Bone ) {
  24648. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  24649. geometry.vertices[ j ].setFromMatrixPosition( boneMatrix );
  24650. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  24651. geometry.vertices[ j + 1 ].setFromMatrixPosition( boneMatrix );
  24652. j += 2;
  24653. }
  24654. }
  24655. geometry.verticesNeedUpdate = true;
  24656. geometry.computeBoundingSphere();
  24657. };
  24658. // File:src/extras/helpers/SpotLightHelper.js
  24659. /**
  24660. * @author alteredq / http://alteredqualia.com/
  24661. * @author mrdoob / http://mrdoob.com/
  24662. * @author WestLangley / http://github.com/WestLangley
  24663. */
  24664. THREE.SpotLightHelper = function ( light ) {
  24665. THREE.Object3D.call( this );
  24666. this.light = light;
  24667. this.light.updateMatrixWorld();
  24668. this.matrix = light.matrixWorld;
  24669. this.matrixAutoUpdate = false;
  24670. var geometry = new THREE.BufferGeometry();
  24671. var positions = [
  24672. 0, 0, 0, 0, 0, 1,
  24673. 0, 0, 0, 1, 0, 1,
  24674. 0, 0, 0, - 1, 0, 1,
  24675. 0, 0, 0, 0, 1, 1,
  24676. 0, 0, 0, 0, - 1, 1
  24677. ];
  24678. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  24679. var p1 = ( i / l ) * Math.PI * 2;
  24680. var p2 = ( j / l ) * Math.PI * 2;
  24681. positions.push(
  24682. Math.cos( p1 ), Math.sin( p1 ), 1,
  24683. Math.cos( p2 ), Math.sin( p2 ), 1
  24684. );
  24685. }
  24686. geometry.addAttribute( 'position', new THREE.Float32Attribute( positions, 3 ) );
  24687. var material = new THREE.LineBasicMaterial( { fog: false } );
  24688. this.cone = new THREE.LineSegments( geometry, material );
  24689. this.add( this.cone );
  24690. this.update();
  24691. };
  24692. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  24693. THREE.SpotLightHelper.prototype.constructor = THREE.SpotLightHelper;
  24694. THREE.SpotLightHelper.prototype.dispose = function () {
  24695. this.cone.geometry.dispose();
  24696. this.cone.material.dispose();
  24697. };
  24698. THREE.SpotLightHelper.prototype.update = function () {
  24699. var vector = new THREE.Vector3();
  24700. var vector2 = new THREE.Vector3();
  24701. return function () {
  24702. var coneLength = this.light.distance ? this.light.distance : 1000;
  24703. var coneWidth = coneLength * Math.tan( this.light.angle );
  24704. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  24705. vector.setFromMatrixPosition( this.light.matrixWorld );
  24706. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  24707. this.cone.lookAt( vector2.sub( vector ) );
  24708. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  24709. };
  24710. }();
  24711. // File:src/extras/helpers/VertexNormalsHelper.js
  24712. /**
  24713. * @author mrdoob / http://mrdoob.com/
  24714. * @author WestLangley / http://github.com/WestLangley
  24715. */
  24716. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  24717. this.object = object;
  24718. this.size = ( size !== undefined ) ? size : 1;
  24719. var color = ( hex !== undefined ) ? hex : 0xff0000;
  24720. var width = ( linewidth !== undefined ) ? linewidth : 1;
  24721. //
  24722. var nNormals = 0;
  24723. var objGeometry = this.object.geometry;
  24724. if ( objGeometry instanceof THREE.Geometry ) {
  24725. nNormals = objGeometry.faces.length * 3;
  24726. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  24727. nNormals = objGeometry.attributes.normal.count
  24728. }
  24729. //
  24730. var geometry = new THREE.BufferGeometry();
  24731. var positions = new THREE.Float32Attribute( nNormals * 2 * 3, 3 );
  24732. geometry.addAttribute( 'position', positions );
  24733. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ) );
  24734. //
  24735. this.matrixAutoUpdate = false;
  24736. this.update();
  24737. };
  24738. THREE.VertexNormalsHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24739. THREE.VertexNormalsHelper.prototype.constructor = THREE.VertexNormalsHelper;
  24740. THREE.VertexNormalsHelper.prototype.update = ( function () {
  24741. var v1 = new THREE.Vector3();
  24742. var v2 = new THREE.Vector3();
  24743. var normalMatrix = new THREE.Matrix3();
  24744. return function update() {
  24745. var keys = [ 'a', 'b', 'c' ];
  24746. this.object.updateMatrixWorld( true );
  24747. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  24748. var matrixWorld = this.object.matrixWorld;
  24749. var position = this.geometry.attributes.position;
  24750. //
  24751. var objGeometry = this.object.geometry;
  24752. if ( objGeometry instanceof THREE.Geometry ) {
  24753. var vertices = objGeometry.vertices;
  24754. var faces = objGeometry.faces;
  24755. var idx = 0;
  24756. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24757. var face = faces[ i ];
  24758. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  24759. var vertex = vertices[ face[ keys[ j ] ] ];
  24760. var normal = face.vertexNormals[ j ];
  24761. v1.copy( vertex ).applyMatrix4( matrixWorld );
  24762. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24763. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24764. idx = idx + 1;
  24765. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24766. idx = idx + 1;
  24767. }
  24768. }
  24769. } else if ( objGeometry instanceof THREE.BufferGeometry ) {
  24770. var objPos = objGeometry.attributes.position;
  24771. var objNorm = objGeometry.attributes.normal;
  24772. var idx = 0;
  24773. // for simplicity, ignore index and drawcalls, and render every normal
  24774. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  24775. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  24776. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  24777. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  24778. position.setXYZ( idx, v1.x, v1.y, v1.z );
  24779. idx = idx + 1;
  24780. position.setXYZ( idx, v2.x, v2.y, v2.z );
  24781. idx = idx + 1;
  24782. }
  24783. }
  24784. position.needsUpdate = true;
  24785. return this;
  24786. }
  24787. }() );
  24788. // File:src/extras/helpers/WireframeHelper.js
  24789. /**
  24790. * @author mrdoob / http://mrdoob.com/
  24791. */
  24792. THREE.WireframeHelper = function ( object, hex ) {
  24793. var color = ( hex !== undefined ) ? hex : 0xffffff;
  24794. THREE.LineSegments.call( this, new THREE.WireframeGeometry( object.geometry ), new THREE.LineBasicMaterial( { color: color } ) );
  24795. this.matrix = object.matrixWorld;
  24796. this.matrixAutoUpdate = false;
  24797. };
  24798. THREE.WireframeHelper.prototype = Object.create( THREE.LineSegments.prototype );
  24799. THREE.WireframeHelper.prototype.constructor = THREE.WireframeHelper;
  24800. // File:src/extras/objects/ImmediateRenderObject.js
  24801. /**
  24802. * @author alteredq / http://alteredqualia.com/
  24803. */
  24804. THREE.ImmediateRenderObject = function ( material ) {
  24805. THREE.Object3D.call( this );
  24806. this.material = material;
  24807. this.render = function ( renderCallback ) {};
  24808. };
  24809. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  24810. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  24811. // File:src/extras/objects/MorphBlendMesh.js
  24812. /**
  24813. * @author alteredq / http://alteredqualia.com/
  24814. */
  24815. THREE.MorphBlendMesh = function( geometry, material ) {
  24816. THREE.Mesh.call( this, geometry, material );
  24817. this.animationsMap = {};
  24818. this.animationsList = [];
  24819. // prepare default animation
  24820. // (all frames played together in 1 second)
  24821. var numFrames = this.geometry.morphTargets.length;
  24822. var name = "__default";
  24823. var startFrame = 0;
  24824. var endFrame = numFrames - 1;
  24825. var fps = numFrames / 1;
  24826. this.createAnimation( name, startFrame, endFrame, fps );
  24827. this.setAnimationWeight( name, 1 );
  24828. };
  24829. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  24830. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  24831. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  24832. var animation = {
  24833. start: start,
  24834. end: end,
  24835. length: end - start + 1,
  24836. fps: fps,
  24837. duration: ( end - start ) / fps,
  24838. lastFrame: 0,
  24839. currentFrame: 0,
  24840. active: false,
  24841. time: 0,
  24842. direction: 1,
  24843. weight: 1,
  24844. directionBackwards: false,
  24845. mirroredLoop: false
  24846. };
  24847. this.animationsMap[ name ] = animation;
  24848. this.animationsList.push( animation );
  24849. };
  24850. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  24851. var pattern = /([a-z]+)_?(\d+)/i;
  24852. var firstAnimation, frameRanges = {};
  24853. var geometry = this.geometry;
  24854. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  24855. var morph = geometry.morphTargets[ i ];
  24856. var chunks = morph.name.match( pattern );
  24857. if ( chunks && chunks.length > 1 ) {
  24858. var name = chunks[ 1 ];
  24859. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  24860. var range = frameRanges[ name ];
  24861. if ( i < range.start ) range.start = i;
  24862. if ( i > range.end ) range.end = i;
  24863. if ( ! firstAnimation ) firstAnimation = name;
  24864. }
  24865. }
  24866. for ( var name in frameRanges ) {
  24867. var range = frameRanges[ name ];
  24868. this.createAnimation( name, range.start, range.end, fps );
  24869. }
  24870. this.firstAnimation = firstAnimation;
  24871. };
  24872. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  24873. var animation = this.animationsMap[ name ];
  24874. if ( animation ) {
  24875. animation.direction = 1;
  24876. animation.directionBackwards = false;
  24877. }
  24878. };
  24879. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  24880. var animation = this.animationsMap[ name ];
  24881. if ( animation ) {
  24882. animation.direction = - 1;
  24883. animation.directionBackwards = true;
  24884. }
  24885. };
  24886. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  24887. var animation = this.animationsMap[ name ];
  24888. if ( animation ) {
  24889. animation.fps = fps;
  24890. animation.duration = ( animation.end - animation.start ) / animation.fps;
  24891. }
  24892. };
  24893. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  24894. var animation = this.animationsMap[ name ];
  24895. if ( animation ) {
  24896. animation.duration = duration;
  24897. animation.fps = ( animation.end - animation.start ) / animation.duration;
  24898. }
  24899. };
  24900. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  24901. var animation = this.animationsMap[ name ];
  24902. if ( animation ) {
  24903. animation.weight = weight;
  24904. }
  24905. };
  24906. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  24907. var animation = this.animationsMap[ name ];
  24908. if ( animation ) {
  24909. animation.time = time;
  24910. }
  24911. };
  24912. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  24913. var time = 0;
  24914. var animation = this.animationsMap[ name ];
  24915. if ( animation ) {
  24916. time = animation.time;
  24917. }
  24918. return time;
  24919. };
  24920. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  24921. var duration = - 1;
  24922. var animation = this.animationsMap[ name ];
  24923. if ( animation ) {
  24924. duration = animation.duration;
  24925. }
  24926. return duration;
  24927. };
  24928. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  24929. var animation = this.animationsMap[ name ];
  24930. if ( animation ) {
  24931. animation.time = 0;
  24932. animation.active = true;
  24933. } else {
  24934. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  24935. }
  24936. };
  24937. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  24938. var animation = this.animationsMap[ name ];
  24939. if ( animation ) {
  24940. animation.active = false;
  24941. }
  24942. };
  24943. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  24944. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  24945. var animation = this.animationsList[ i ];
  24946. if ( ! animation.active ) continue;
  24947. var frameTime = animation.duration / animation.length;
  24948. animation.time += animation.direction * delta;
  24949. if ( animation.mirroredLoop ) {
  24950. if ( animation.time > animation.duration || animation.time < 0 ) {
  24951. animation.direction *= - 1;
  24952. if ( animation.time > animation.duration ) {
  24953. animation.time = animation.duration;
  24954. animation.directionBackwards = true;
  24955. }
  24956. if ( animation.time < 0 ) {
  24957. animation.time = 0;
  24958. animation.directionBackwards = false;
  24959. }
  24960. }
  24961. } else {
  24962. animation.time = animation.time % animation.duration;
  24963. if ( animation.time < 0 ) animation.time += animation.duration;
  24964. }
  24965. var keyframe = animation.start + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  24966. var weight = animation.weight;
  24967. if ( keyframe !== animation.currentFrame ) {
  24968. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  24969. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  24970. this.morphTargetInfluences[ keyframe ] = 0;
  24971. animation.lastFrame = animation.currentFrame;
  24972. animation.currentFrame = keyframe;
  24973. }
  24974. var mix = ( animation.time % frameTime ) / frameTime;
  24975. if ( animation.directionBackwards ) mix = 1 - mix;
  24976. if ( animation.currentFrame !== animation.lastFrame ) {
  24977. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  24978. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  24979. } else {
  24980. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  24981. }
  24982. }
  24983. };